CORS on Spring-OAuth2 - spring-rest

I am using Spring-Boot and Spring-OAuth2 to protect my Rest APIs. I have implemented OAuth2. It gets executed properly. I developed AngularJS and try to access it, but I am getting CORS error.
Error -> Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://192.168.2.45:8080/Jaihind/oauth/token. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
URL -> curl -X POST -vu clientapp:123456 http://localhost:8080/Jaihind/oauth/token -H "Accept: application/json" -d "password=password&username=gaurav&grant_type=password&scope=read%20write&client_secret=123456&client_id=clientapp"
Below are the codes.
OAuth2ServerConfiguration.java
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class OAuth2ServerConfiguration {
private static final String RESOURCE_ID = "restservice";
#Configuration
#EnableResourceServer
protected static class ResourceServerConfiguration extends
ResourceServerConfigurerAdapter {
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
// #formatter:off
resources.resourceId(RESOURCE_ID);
// #formatter:on
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests().antMatchers("/api/greeting").authenticated();
http.authorizeRequests().antMatchers("/oauth/token").permitAll();
//http.antMatcher("/oauth/token").p
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private TokenStore tokenStore = new InMemoryTokenStore();
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Autowired
private UserDetailServiceBean userDetailsService;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// #formatter:off
endpoints.addInterceptor(new HandlerInterceptorAdapter() {
#Override
public boolean preHandle(HttpServletRequest hsr, HttpServletResponse rs, Object o) throws Exception {
rs.setHeader("Access-Control-Allow-Origin", "*");
rs.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
rs.setHeader("Access-Control-Allow-Headers", "Content-Type,X-Requested-With,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
return true;
}
});
endpoints.tokenStore(this.tokenStore)
.authenticationManager(this.authenticationManager)
.userDetailsService(userDetailsService);
// #formatter:on
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// #formatter:off
clients
.inMemory()
.withClient("clientapp")
.authorizedGrantTypes("password", "refresh_token")
.authorities("USER")
.scopes("read", "write")
.resourceIds(RESOURCE_ID)
.secret("123456");
// #formatter:on
}
#Bean
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(this.tokenStore);
return tokenServices;
}
}
}
I even added Filter.
Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class YourCORSFilter implements Filter {
#Override
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
HttpServletResponse response = (HttpServletResponse) resp;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "Content-Type,x-auth-token,x-requested-with,accept,Origin,Access-Control-Request-Method,Access-Control-Request-Headers,Authorization");
if (request.getMethod() != "OPTIONS") {
chain.doFilter(req, resp);
} else {
}
chain.doFilter(req, resp);
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
}
#Override
public void destroy() {
}
}

Your filter always calls chain.doFilter(req, resp) so if the downstream app doesn't handle the CORS requests then you are going to see errors like that.

Related

After using custom login form , OAuth2 server not redirecting to client server

Authentication and Authorization is working fine. But after successful login it not redirecting me to client side further it open source code of some .js file. While previous (without custom login form loginPage("/login")) it successfully redirecting me to last page clicked (client side) which called for authenticate.
My Server side code as below:
Authorization server
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient("ClientId")
.secret("secret")
.authorizedGrantTypes("authorization_code")
.scopes("user_info")
.redirectUris("http://localhost:8082/ui/login")
.autoApprove(true);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
}
Resource Server
#Configuration
#EnableResourceServer
public class ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.requestMatchers().antMatchers("/api/**").and().authorizeRequests()
.antMatchers("/api/**").authenticated().and()
.antMatcher("/rest/hello/principal")
.authorizeRequests().anyRequest().authenticated();
}
My Security Config
#Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private CustomUserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/oauth/token/revokeById/**").permitAll()
.antMatchers("/tokens/**").permitAll().anyRequest().authenticated().and()
.formLogin().loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.failureUrl("/login?error")
.defaultSuccessUrl("/").permitAll().and()
.csrf().disable();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());
}
#Bean(name = "passwordEncoder")
public PasswordEncoder passwordencoder() {
return new CustomPasswordEncoder();
}
}
you need to create
SimpleUrlAuthenticationSuccessHandler implementation
public class RefererRedirectionAuthenticationSuccessHandler
extends SimpleUrlAuthenticationSuccessHandler
implements AuthenticationSuccessHandler {
public RefererRedirectionAuthenticationSuccessHandler() {
super();
setUseReferer(true);
}
}
and add one line to the WebSecurityConfiguration
.successHandler(new RefererRedirectionAuthenticationSuccessHandler())
And after that you method will look like as shown below
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/login").permitAll().antMatchers("/oauth/token/revokeById/**").permitAll()
.antMatchers("/tokens/**").permitAll().anyRequest().authenticated().and()
.formLogin().loginPage("/login")
.usernameParameter("username")
.passwordParameter("password")
.successHandler(new RefererRedirectionAuthenticationSuccessHandler())
.failureUrl("/login?error")
.defaultSuccessUrl("/").permitAll().and()
.csrf().disable();
}

Spring/OAuth2 Error - InsufficientAuthenticationException, There is no client authentication. Try adding an appropriate authentication filter

I've been stuck for hours trying to figure out what in the world is going wrong with this Spring Security OAuth2 implementation.
The error occurs when I go to hit the /oauth/token endpoint:
localhost:8080/my-oauth-practice-app/oauth/token
Error: InsufficientAuthenticationException, There is no client authentication. Try adding an appropriate authentication filter.
AUTHORIZATION SERVER CONFIGURATION
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
AuthenticationManager authenticationManager;
#Autowired
DefaultTokenServices tokenServices;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
super.configure(endpoints);
endpoints.tokenServices(this.tokenServices).authenticationManager(this.authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
super.configure(security);
security.tokenKeyAccess("permitAll()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientid").secret("clientpass").authorizedGrantTypes("password").scopes("read").autoApprove(true);
}
}
RESOURCE SERVER CONFIGURATION
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
DefaultTokenServices tokenServices;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
super.configure(resources);
resources.tokenServices(this.tokenServices);
}
#Override
public void configure(HttpSecurity http) throws Exception {
super.configure(http);
http.authorizeRequests().anyRequest().hasRole("USER");
}
}
GENERAL WEB SECURITY CONFIGURATION
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Primary
#Bean
DefaultTokenServices tokenServices() {
DefaultTokenServices d = new DefaultTokenServices();
d.setAccessTokenValiditySeconds(600);
d.setRefreshTokenValiditySeconds(1000);
d.setTokenStore(new InMemoryTokenStore());
return d;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("user").password("password").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/**").hasRole("USER");
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
}
You should check WebSecurityConfigurerAdapter method like this:
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/webjars/**", "/oauth/**");
}
remove "/oauth/**" path. otherwise
TokenEndpoint.postAccessToken(Principal principal, #RequestParam Map<String, String> parameters)
principal will be null.

/ not accessible in spring mvc 4

I have following classes
AppConfig.java
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = "com.pdma.dmapp")
public class AppConfig extends WebMvcConfigurerAdapter{
#Bean(name="multipartResolver")
public StandardServletMultipartResolver resolver(){
return new StandardServletMultipartResolver();
}
#Override
public void configureViewResolvers(ViewResolverRegistry registry){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setViewClass(JstlView.class);
viewResolver.setPrefix("/WEB-INF/views/");
viewResolver.setSuffix(".jsp");
registry.viewResolver(viewResolver);
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry){
registry.addResourceHandler("/webResources/**").addResourceLocations("/webResources/");
registry.addResourceHandler("/angularApps/**").addResourceLocations("/angularApps/");
}
}
SecurityConfiguration.java
#Configuration
#EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
#Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception
{
auth.inMemoryAuthentication()
.withUser("GISManager")
.password("gis#manager#pdma")
.roles("GISManager");
}
#Override
public void configure(HttpSecurity http) throws Exception
{
http.authorizeRequests()
.antMatchers("/**").access("hasRole('GISManager')")
.and().formLogin()
.and().exceptionHandling().accessDeniedPage("/Access_Denied");
}
}
AppInitializer.java
public class AppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
private static final String LOCATION = "D:/uploads/";
private static final long MAX_FILE_SIZE = 1024*1024*25;
private static final long MAX_REQUEST_SIZE = 1024*1024*30;
private static final int FILE_SIZE_THRESHOLD = 0;
#Override
protected Class<?>[] getRootConfigClasses() {
// TODO Auto-generated method stub
return new Class [] {AppConfig.class,SecurityConfiguration.class};
}
#Override
protected Class<?>[] getServletConfigClasses() {
// TODO Auto-generated method stub
return null;
}
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
#Override
protected void customizeRegistration(ServletRegistration.Dynamic registration){
registration.setMultipartConfig(getMultipartConfigElement());
}
private MultipartConfigElement getMultipartConfigElement(){
MultipartConfigElement element = new MultipartConfigElement(LOCATION,
MAX_FILE_SIZE,
MAX_REQUEST_SIZE,
FILE_SIZE_THRESHOLD);
return element;
}
}
WelcomeController.java
#Controller
#RequestMapping(value="/")
public class WelcomeController {
#GetMapping(value="")
public String getWelcomePage(){
return "welcome";
}
}
welcome.jsp is placed in /WEB-INF/views/
I am getting login page and all other pages like main.html etc but I am unable to get welcome page. When I try to hit localhost:8080/dmapp/ I get following message in console:
WARNING: No mapping found for HTTP request with URI [/dmapp/] in DispatcherServlet with name 'dispatcher'
This problem was present before I used spring-security
What can be the problem
changing
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/",
"*.html",
"*.htm",
"*.ajax"};
}
to
#Override
protected String[] getServletMappings() {
// TODO Auto-generated method stub
return new String [] {"/"};
}
solved problem in my case

Is it possible to get forward URI from #WebFilter?

In my JSF application I have a #WebFilter and I'd like to, when a page forward occurs, get the URI of the destination page. Is that possible?
#WebFilter(servletNames={"Faces Servlet"})
public class MyFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
// here, can I know the URI?
chain.doFilter(request, response);
}
#Override
public void destroy() {}
#Override
public void init(FilterConfig arg0) throws ServletException {}
}
Thanks

Spring OAuth2 2.0.9 upgrade

I'm trying to upgrade Spring Security OAuth2 from 2.0.3 to 2.0.9.
Below is my configuration.
#Configuration
public class SecurityConfig {
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private RedisConnectionFactory redisConnectionFactory;
#Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
#Primary
#Bean
public AuthorizationServerTokenServices tokenServices() throws Exception {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService);
tokenServices.setTokenEnhancer(new RedrumTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
#Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
RedrumUserApprovalHandler handler = new RedrumUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setUseApprovalStore(true);
return handler;
}
#Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
#Configuration
#Order(Ordered.HIGHEST_PRECEDENCE)
#EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${baseUrl}")
private String baseUrl;
#Autowired
private DataSource dataSource;
#Resource
private PasswordEncoder passwordEncoder;
#Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("xyz")
.secret("...................")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("blah")
return serviceConfig.clientDetailsService();
}
#Bean
public UserDetailsService clientDetailsUserDetailsService() throws Exception {
return new ClientDetailsUserDetailsService(clientDetailsService());
}
#Bean
public ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter() throws Exception {
ClientCredentialsTokenEndpointFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationManager(authenticationManagerBean());
filter.afterPropertiesSet();
return filter;
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery("select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery("select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
auth.userDetailsService(clientDetailsUserDetailsService());
}
#Bean(name="authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Bean
protected AuthenticationEntryPoint authenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("zzz/client");
return entryPoint;
}
#Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.antMatchers(HttpMethod.POST, "/api/**/account")
.and()
.debug(false);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.anonymous().disable()
.requiresChannel().anyRequest().requiresSecure();
http
.antMatcher("/oauth/token")
.authorizeRequests().anyRequest().authenticated()
.and()
.httpBasic().authenticationEntryPoint(authenticationEntryPoint())
.and()
.csrf().requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/token")).disable()
.exceptionHandling().accessDeniedHandler(oAuth2AccessDeniedHandler())
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http
.addFilterBefore(clientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
#Bean
public OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler() {
return new OAuth2AccessDeniedHandler();
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private ResourceServerTokenServices tokenServices;
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Autowired
private ClientCredentialsTokenEndpointFilter clientCredentialsTokenEndpointFilter;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("My resource");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.requiresChannel().anyRequest().requiresSecure();
// API calls
http
.anonymous().disable()
.authorizeRequests()
.antMatchers("/api/**", "/whatever")
.access("#oauth2.hasScope('blah') and (hasRole('ROLE_USER'))")
.and()
.addFilterBefore(clientCredentialsTokenEndpointFilter, BasicAuthenticationFilter.class)
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.NEVER)
.and()
.exceptionHandling()
.accessDeniedHandler(oAuth2AccessDeniedHandler);
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthorizationServerTokenServices tokenServices;
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
private UserApprovalHandler userApprovalHandler;
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private AuthenticationEntryPoint authenticationEntryPoint;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices)
.userApprovalHandler(userApprovalHandler);
}
#Override
public void configure(ClientDetailsServiceConfigurer clients)
throws Exception {
clients.withClientDetails(clientDetailsService);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer)
throws Exception {
oauthServer.authenticationEntryPoint(authenticationEntryPoint)
.realm("zzz/clients");
}
}
}
This was working fine with 2.0.3 but now after upgrading to 2.0.9, I started getting "Unsupported grant type: password"
Here is the test;
curl -k -i -H "Accept: application/json" -X POST -d "grant_type=password&client_id=xyz&client_secret=zzzzzz&scope=blah&username=tester&password=121212" https://localhost:8443/myapp/oauth/token
and the result is;
{"error":"unsupported_grant_type","error_description":"Unsupported grant type: password"}
I'm on springframework.version 4.1.8.RELEASE and spring-security.version 3.2.8.RELEASE Really appreciate if I can get help on this.
The problem is that you are configuring to much.
Most of things, such as SessionCreationPolicy, OAuth2AccessDeniedHandler, AuthenticationEntryPoint, ClientCredentialsTokenEndpointFilter are already configured.
Do not confuse between ClientDetailsService and UserDetailsService. Try avoid to use ClientDetailsUserDetailsService if you don't know what it is.
Move #Bean declaration to right position, so they can wired up.
Care with #Order
Try this:
#Configuration
public class SecurityConfig {
#Configuration
#Order(4)
#EnableWebSecurity
protected static class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Value("${baseUrl}")
private String baseUrl;
#Autowired
private DataSource dataSource;
#Resource
private PasswordEncoder passwordEncoder;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder> jdbcUserDetail = new JdbcUserDetailsManagerConfigurer<AuthenticationManagerBuilder>();
jdbcUserDetail.dataSource(dataSource);
jdbcUserDetail.passwordEncoder(passwordEncoder);
jdbcUserDetail.authoritiesByUsernameQuery(
"select a.username, r.role_name from account a, role r, account_role ar where a.id = ar.account_id and r.id = ar.role_id and a.username = ?");
jdbcUserDetail.usersByUsernameQuery(
"select a.username, a.password, a.enabled, a.email from account a where a.username = ?");
auth.apply(jdbcUserDetail);
}
#Bean(name = "authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(WebSecurity webSecurity) throws Exception {
webSecurity
.ignoring()
.antMatchers("/resources/**", "/swagger/**", "/copyright*", "/api-docs/**")
.antMatchers(HttpMethod.POST, "/api/**/account")
.and()
.debug(false);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.requiresChannel().anyRequest().requiresSecure();
// #formatter:off
http
.authorizeRequests()
.anyRequest().hasRole("USER")
.and()
// TODO put CSRF protection back into this endpoint
.csrf()
.requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize")).disable()
;
// #formatter:on
}
}
#Configuration
#EnableResourceServer
protected static class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private ResourceServerTokenServices tokenServices;
#Autowired
private OAuth2AccessDeniedHandler oAuth2AccessDeniedHandler;
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.tokenServices(tokenServices);
resources.resourceId("My resource");
}
#Override
public void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.requiresChannel().anyRequest().requiresSecure();
// API calls
http
.requestMatchers()
.antMatchers("/api/**", "/whatever")
.and()
.authorizeRequests()
.anyRequest()
.access("#oauth2.hasScope('blah') and (hasRole('ROLE_USER'))");
// #formatter:on
}
}
#Configuration
#EnableAuthorizationServer
protected static class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private RedisConnectionFactory redisConnectionFactory;
#Bean
public TokenStore tokenStore() {
return new RedisTokenStore(redisConnectionFactory);
}
#Bean
public UserApprovalHandler userApprovalHandler() throws Exception {
RedrumUserApprovalHandler handler = new RedrumUserApprovalHandler();
handler.setApprovalStore(approvalStore());
handler.setClientDetailsService(clientDetailsService());
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService()));
handler.setUseApprovalStore(true);
return handler;
}
#Bean
public ApprovalStore approvalStore() {
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore());
return store;
}
#Primary
#Bean
public DefaultTokenServices tokenServices() throws Exception {
final DefaultTokenServices tokenServices = new DefaultTokenServices();
tokenServices.setAccessTokenValiditySeconds(6000);
tokenServices.setClientDetailsService(clientDetailsService());
tokenServices.setTokenEnhancer(new RedrumTokenEnhancer());
tokenServices.setSupportRefreshToken(true);
tokenServices.setTokenStore(tokenStore());
return tokenServices;
}
#Bean
public ClientDetailsService clientDetailsService() throws Exception {
ClientDetailsServiceConfiguration serviceConfig = new ClientDetailsServiceConfiguration();
serviceConfig.clientDetailsServiceConfigurer().inMemory()
.withClient("xyz")
.secret("...................")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "client_credentials")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("blah")
;
return serviceConfig.clientDetailsService();
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.authenticationManager(authenticationManager)
.tokenServices(tokenServices())
.userApprovalHandler(userApprovalHandler());
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.withClientDetails(clientDetailsService());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.realm("zzz/clients")
.allowFormAuthenticationForClients();
}
}
}

Resources