Spring Security: null Principal on pages accessible by anonymous and logged users - spring-boot

I need that a page in my application can be accessed by both anonymous and logged in users.
The application is part of a SSO context, where Keycloak is in charge for authentication and the access control is managed by Spring Security.
Each application has its own client configured in Keycloak.
I need that:
anonymous users can access this page with no restrictions
users already authenticated on other applications in the SSO context should be immediately recognized, so that I can print the name of the logged user
So far, I always get null when I try to retrieve the Principal:
SecurityContext context = SecurityContextHolder.getContext();
Authentication authentication = context.getAuthentication();
User = (User) authentication.getPrincipal();
The strange thing is that if I navigate a secured page, the Principal is then populated; otherwise, it is always null.
Also following the indications from https://spring.io/guides/topicals/spring-security-architecture (at the paragraph "Creating and Customizing Filter Chains") I continue to get a null Principal: it seems that there is no fallback filter intercepting all the URLS that are not matched by my configuration.
In the following, my security configuration:
#Configuration
#Order(1)
public class MyConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
http
.authorizeRequests()
.antMatchers("/secure/**")
.authenticated()
.and()
.csrf().disable();
}
#Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers("/js/**");
web.ignoring().antMatchers("/actuator/**");
web.ignoring().antMatchers("/robot**");
}
}
I also tried to setup a fallback configuration, obtaining always the same result.
#Configuration
#Order(2)
public class BasicAuthConfigurationAdapter extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/**")
.permitAll();
}
}
Any idea?
Thanks in advance for your suggestions.
>>> Update 1 <<<
super.configure(http) in my security file calls this method of the class KeycloakWebSecurityConfigurerAdapter
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().requireCsrfProtectionMatcher(keycloakCsrfRequestMatcher())
.and()
.sessionManagement()
.sessionAuthenticationStrategy(sessionAuthenticationStrategy())
.and()
.addFilterBefore(keycloakPreAuthActionsFilter(), LogoutFilter.class)
.addFilterBefore(keycloakAuthenticationProcessingFilter(), BasicAuthenticationFilter.class)
.addFilterBefore(keycloakAuthenticatedActionsFilter(), BasicAuthenticationFilter.class)
.addFilterAfter(keycloakSecurityContextRequestFilter(), SecurityContextHolderAwareRequestFilter.class)
.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint())
.and()
.logout()
.addLogoutHandler(keycloakLogoutHandler())
.logoutUrl("/sso/logout").permitAll()
.logoutSuccessUrl("/");
}
>>> Update 2 <<<
I report some details that emerged from a deeper analysis.
a) Logs related to the creation of the filter chain (printed at startup):
Creating filter chain: Ant [pattern='/js/**'], []
Creating filter chain: Ant [pattern='/actuator/**'], []
Adding web access control expression 'permitAll', for OrRequestMatcher [requestMatchers=[Ant [pattern='/sso/logout', GET], Ant [pattern='/sso/logout', POST], Ant [pattern='/sso/logout', PUT], Ant [pattern='/sso/logout', DELETE]]]
Adding web access control expression 'permitAll', for ExactUrl [processUrl='/']
Adding web access control expression 'authenticated', for Ant [pattern='/secure/**']
Creating filter chain: any request, [org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter#4c4cc360,
org.springframework.security.web.context.SecurityContextPersistenceFilter#6710a0e3,
org.springframework.security.web.header.HeaderWriterFilter#685b095c,
org.keycloak.adapters.springsecurity.filter.KeycloakPreAuthActionsFilter#5aec45a0,
org.springframework.security.web.authentication.logout.LogoutFilter#a766049,
org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticationProcessingFilter#3ac44e13,
org.keycloak.adapters.springsecurity.filter.KeycloakAuthenticatedActionsFilter#3829182c,
org.springframework.security.web.savedrequest.RequestCacheAwareFilter#3f20b0d8,
org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter#715bfed,
org.keycloak.adapters.springsecurity.filter.KeycloakSecurityContextRequestFilter#67b72f63,
org.springframework.security.web.authentication.AnonymousAuthenticationFilter#2719a5c3,
org.springframework.security.web.session.SessionManagementFilter#508bfcfe,
org.springframework.security.web.access.ExceptionTranslationFilter#46aab01d,
org.springframework.security.web.access.intercept.FilterSecurityInterceptor#152f7bc5]
b) Logs appearing when calling a NON SECURED page
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/js/**'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/actuator/**'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper$HttpSessionWrapper#d99b189. A new one will be created.
o.s.security.web.FilterChainProxy : /edizione/4745 at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 4 of 14 in additional filter chain; firing Filter: 'KeycloakPreAuthActionsFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 5 of 14 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', GET]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', POST]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'POST /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', PUT]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'PUT /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', DELETE]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'DELETE /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.security.web.FilterChainProxy : /edizione/4745 at position 6 of 14 in additional filter chain; firing Filter: 'KeycloakAuthenticationProcessingFilter'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/login']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/login'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=Authorization, expectedHeaderValue=null]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using org.keycloak.adapters.springsecurity.filter.QueryParamPresenceRequestMatcher#594f1699
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.security.web.FilterChainProxy : /edizione/4745 at position 7 of 14 in additional filter chain; firing Filter: 'KeycloakAuthenticatedActionsFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 8 of 14 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
o.s.security.web.FilterChainProxy : /edizione/4745 at position 9 of 14 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 10 of 14 in additional filter chain; firing Filter: 'KeycloakSecurityContextRequestFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 11 of 14 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#e8fcd0e2: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#ffff6a82: RemoteIpAddress: 127.0.0.1; SessionId: 968df9fb-cf20-4f16-9962-df78ee71a960; Granted Authorities: ROLE_ANONYMOUS'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 12 of 14 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 13 of 14 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 14 of 14 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', GET]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', POST]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'POST /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', PUT]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'PUT /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', DELETE]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'DELETE /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/secure/**'
o.s.s.w.a.i.FilterSecurityInterceptor : Public object - authentication not attempted
o.s.security.web.FilterChainProxy : /edizione/4745 reached end of additional filter chain; proceeding with original chain
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/login']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/login'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=Authorization, expectedHeaderValue=null]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using org.keycloak.adapters.springsecurity.filter.QueryParamPresenceRequestMatcher#594f1699
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
c) Logs appearing when calling a SECURED page
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/js/**'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/actuator/**'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 1 of 14 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 2 of 14 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
w.c.HttpSessionSecurityContextRepository : Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#93b05922: Authentication: org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken#93b05922: Principal: f:891de36f-d7ef-48aa-b7eb-1089417e8a81:7A1062D9-3101-4CB7-84BC-81D2080263DC; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount#15a225c4; Granted Authorities: ROLE_offline_access, ROLE_uma_authorization'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 3 of 14 in additional filter chain; firing Filter: 'HeaderWriterFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 4 of 14 in additional filter chain; firing Filter: 'KeycloakPreAuthActionsFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 5 of 14 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', GET]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', POST]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'POST /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', PUT]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'PUT /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', DELETE]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'DELETE /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.security.web.FilterChainProxy : /edizione/4745 at position 6 of 14 in additional filter chain; firing Filter: 'KeycloakAuthenticationProcessingFilter'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/login']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/login'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=Authorization, expectedHeaderValue=null]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using org.keycloak.adapters.springsecurity.filter.QueryParamPresenceRequestMatcher#594f1699
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.security.web.FilterChainProxy : /edizione/4745 at position 7 of 14 in additional filter chain; firing Filter: 'KeycloakAuthenticatedActionsFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 8 of 14 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
o.s.security.web.FilterChainProxy : /edizione/4745 at position 9 of 14 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 10 of 14 in additional filter chain; firing Filter: 'KeycloakSecurityContextRequestFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 11 of 14 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.keycloak.adapters.springsecurity.token.KeycloakAuthenticationToken#93b05922: Principal: f:891de36f-d7ef-48aa-b7eb-1089417e8a81:7A1062D9-3101-4CB7-84BC-81D2080263DC; Credentials: [PROTECTED]; Authenticated: true; Details: org.keycloak.adapters.springsecurity.account.SimpleKeycloakAccount#15a225c4; Granted Authorities: ROLE_offline_access, ROLE_uma_authorization'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 12 of 14 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 13 of 14 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.security.web.FilterChainProxy : /edizione/4745 at position 14 of 14 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', GET]
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', POST]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'POST /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', PUT]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'PUT /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/logout', DELETE]
o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /edizione/4745' doesn't match 'DELETE /sso/logout'
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/secure/**'
o.s.s.w.a.i.FilterSecurityInterceptor : Public object - authentication not attempted
o.s.security.web.FilterChainProxy : /edizione/4745 reached end of additional filter chain; proceeding with original chain
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/sso/login']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/edizione/4745'; against '/sso/login'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using RequestHeaderRequestMatcher [expectedHeaderName=Authorization, expectedHeaderValue=null]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using org.keycloak.adapters.springsecurity.filter.QueryParamPresenceRequestMatcher#594f1699
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Some considerations
As far as I can see debugging the class AbstractAuthenticationProcessingFilter.doFilter(...), in the first case (NON SECURED page) the incoming request never attempts authentication since the following check
if (!requiresAuthentication(request, response)) {
chain.doFilter(request, response);
return;
}
always returns TRUE (for that page, in fact, authentication is not mandatory) and so the execution flow continues to the next filter, skipping the population of the context.

Related

Spring Security applying HttpSecurity filter before building user principal

I have a springboot application that is using Keycloak to handle JWT authentication. If I use #PreAuthorize on my controller method, everything works as expected, but the URL antMatcher pattern based HttpSecurity is not. From what I can tell, Spring is applying the security filter BEFORE building the user principal. In the logs, I see it testing against Anonymous, even though a valid Bearer token was passed, and I'm able to see the AuthenticationPrincipal inside the controller method.
Basically, HttpSecurity is running its rules against Anonymous, even though later a valid Principal is created and can be used by #PreAuthorize checks.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(
AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider
= keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
#Bean
public KeycloakConfigResolver KeycloakConfigResolver() {
return new KeycloakConfigResolver() {
#Override
public KeycloakDeployment resolve(HttpFacade.Request request) {
KeycloakDeployment deployment = null;
AdapterConfig adapterConfig = new AdapterConfig();
adapterConfig.setAuthServerUrl(System.getProperty("keycloak.auth-server-url"));
adapterConfig.setRealm(System.getProperty("keycloak.realm"));
adapterConfig.setResource(System.getProperty("keycloak.resource"));
// adapterConfig.setUseResourceRoleMappings(true);
adapterConfig.setSslRequired("external");
adapterConfig.setPublicClient(true);
deployment = KeycloakDeploymentBuilder.build(adapterConfig);
return deployment;
}
};
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(
new SessionRegistryImpl());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
.and().csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/*").permitAll()
.antMatchers("/api/admin/*").hasRole("admin")
.antMatchers("/api/*").authenticated()
;
}
}
The spring security logs look like
2020-11-28 10:00:45.659 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-28 10:00:45.659 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-28 10:00:45.660 DEBUG 25655 --- [nio-8180-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2020-11-28 10:00:45.660 DEBUG 25655 --- [nio-8180-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-11-28 10:00:45.662 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-28 10:00:45.663 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 4 of 11 in additional filter chain; firing Filter: 'CorsFilter'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 5 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/admin/condition' doesn't match 'GET /logout'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/admin/condition'; against '/logout'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/admin/condition' doesn't match 'PUT /logout'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/admin/condition' doesn't match 'DELETE /logout'
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-11-28 10:00:45.666 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-11-28 10:00:45.667 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#2aa3a4a: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2020-11-28 10:00:45.667 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-11-28 10:00:45.668 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.session.SessionManagementFilter : Requested session ID 8C6524CDA3CD92F69B885542B2E5DF1C is invalid.
2020-11-28 10:00:45.668 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-11-28 10:00:45.668 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/admin/condition'; against '/api/public/*'
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/admin/condition'; against '/api/admin/*'
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /api/admin/condition; Attributes: [hasRole('ROLE_admin')]
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#2aa3a4a: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2020-11-28 10:00:45.673 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#4e7d07d7, returned: -1
2020-11-28 10:00:45.679 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point
Before you configure your own specific configuration, you need to call the Keycloak-configuration
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http); // <----
http.... //
}
The configure method needs to called first and better option user principal would be to add an interceptor rather than filters..and please add super.configure(http);
Thanks!

Spring Security Authorization Code not able to fetch token after getting user consent

I have tried to replicate https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_manual but for only GitHub.
The issue is that I get redirected to GitHub, gets authenticated but then nothing happens, it does not actually retrieve the token with the response code etc.
I have searched on numerous threads.
I have the same issue as: Unable to expose endpoint in Spring Boot to receive authorization code from Google
I could try https://dzone.com/articles/spring-boot-oauth2-getting-the-authorization-code but would like Spring to handle as much security stuff as possible not manually make the rest call.
This goes into some detail about modifying filter chain: Spring oauth2 dont redirect to original url
Spring provides OAuth2LoginAuthenticationFilter and OAuth2AuthorizationRequestRedirectFilter but do I have to use implement that?
2019-08-01 04:36:09.473 DEBUG 13884 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/login/github' matched by universal pattern '/**'
2019-08-01 04:36:09.474 DEBUG 13884 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy : /login/github at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-08-01 04:36:09.476 DEBUG 13884 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy : /login/github at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-08-01 04:36:09.477 DEBUG 13884 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2019-08-01 04:36:09.477 DEBUG 13884 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2019-08-01 04:36:09.479 DEBUG 13884 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy : /login/github at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-08-01 04:36:09.480 DEBUG 13884 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy : /login/github at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2019-08-01 04:36:09.488 DEBUG 13884 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy : /login/github at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2019-08-01 04:36:09.489 DEBUG 13884 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login/github' doesn't match 'POST /logout
2019-08-01 04:36:09.490 DEBUG 13884 --- [nio-8080-exec-9] o.s.security.web.FilterChainProxy : /login/github at position 6 of 12 in additional filter chain; firing Filter: 'OAuth2ClientAuthenticationProcessingFilter'
2019-08-01 04:36:09.491 DEBUG 13884 --- [nio-8080-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login/github'; against '/login/github'
2019-08-01 04:36:09.491 DEBUG 13884 --- [nio-8080-exec-9] uth2ClientAuthenticationProcessingFilter : Request is to process authentication
2019-08-01 04:36:14.533 DEBUG 13884 --- [nio-8080-exec-9] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#422e37e6
2019-08-01 04:36:14.534 DEBUG 13884 --- [nio-8080-exec-9] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2019-08-01 04:36:14.534 DEBUG 13884 --- [nio-8080-exec-9] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2019-08-01 04:36:15.238 DEBUG 13884 --- [nio-8080-exec-9] o.s.s.web.DefaultRedirectStrategy : Redirecting to 'https://github.com/login/oauth/authorize?client_id=SOMETHING&redirect_uri=http://localhost:8080/login/oauth2/code/github&response_type=code&state=bT8lSK'
2019-08-01 04:36:15.542 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/login/oauth2/code/github' matched by universal pattern '/**'
2019-08-01 04:36:15.542 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-08-01 04:36:15.542 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-08-01 04:36:15.542 DEBUG 13884 --- [io-8080-exec-10] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2019-08-01 04:36:15.543 DEBUG 13884 --- [io-8080-exec-10] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#250f33e4. A new one will be created.
2019-08-01 04:36:15.543 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-08-01 04:36:15.543 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
2019-08-01 04:36:15.545 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2019-08-01 04:36:15.546 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login/oauth2/code/github' doesn't match 'POST /logout
2019-08-01 04:36:15.546 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 6 of 12 in additional filter chain; firing Filter: 'OAuth2ClientAuthenticationProcessingFilter'
2019-08-01 04:36:15.546 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login/oauth2/code/github'; against '/login/github'
2019-08-01 04:36:15.546 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2019-08-01 04:36:15.547 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2019-08-01 04:36:15.550 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2019-08-01 04:36:15.554 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#bc4979c4: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 9ABF40E66AE6EDF4FA955A1EC1E728AA; Granted Authorities: ROLE_ANONYMOUS'
2019-08-01 04:36:15.555 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2019-08-01 04:36:15.555 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2019-08-01 04:36:15.555 DEBUG 13884 --- [io-8080-exec-10] o.s.security.web.FilterChainProxy : /login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2019-08-01 04:36:15.557 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login/oauth2/code/github' doesn't match 'POST /logout
2019-08-01 04:36:15.557 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login/oauth2/code/github'; against '/'
2019-08-01 04:36:15.557 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login/oauth2/code/github'; against '/login**'
2019-08-01 04:36:15.558 DEBUG 13884 --- [io-8080-exec-10] o.s.s.w.u.matcher.AntPathR
I tried to replicate the tutorial exactly and did some digging around but have not been able to solve the problem.
#EnableOAuth2Client
public class SocialApplication extends WebSecurityConfigurerAdapter {
#Bean
public FilterRegistrationBean<OAuth2ClientContextFilter> oauth2ClientFilterRegistration(OAuth2ClientContextFilter filter) {
FilterRegistrationBean<OAuth2ClientContextFilter> registration = new FilterRegistrationBean<OAuth2ClientContextFilter>();
registration.setFilter(filter);
registration.setOrder(-100);
return registration;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.antMatcher("/**").authorizeRequests().antMatchers("/", "/login**", "/webjars/**", "/error**").permitAll().anyRequest()
.authenticated().and().exceptionHandling()
.authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/")).and().logout()
.logoutSuccessUrl("/").permitAll().and().csrf()
.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()).and()
.addFilterBefore(ssoFilter(), BasicAuthenticationFilter.class);
// #formatter:on
}
private Filter ssoFilter() {
OAuth2ClientAuthenticationProcessingFilter facebookFilter = new OAuth2ClientAuthenticationProcessingFilter(
"/login/github");
OAuth2RestTemplate facebookTemplate = new OAuth2RestTemplate(facebook(), oauth2ClientContext);
facebookFilter.setRestTemplate(facebookTemplate);
UserInfoTokenServices tokenServices = new UserInfoTokenServices(facebookResource().getUserInfoUri(),
facebook().getClientId());
facebook().setUseCurrentUri(false);
facebook().setPreEstablishedRedirectUri("http://localhost:8080/login/oauth2/code/github");
tokenServices.setRestTemplate(facebookTemplate);
facebookFilter.setTokenServices(tokenServices);
return facebookFilter;
}
The problem is
org.springframework.security.access.AccessDeniedException: Access is denied
Based on debug logs it seems that OAuth2LoginAuthenticationFilter is missing in security filter chain, client receives code from gihub authorization server which should be exchanged for token.
This is the request received by client app from authorization server:
/login/oauth2/code/github?code=d899209d67e0105486d8&state=bT8lSK
Which should be intercepted by OAuth2LoginAuthenticationFilter with default filter processing uri: "/login/oauth2/code/*"- this is what you are missing.
Your question:
Spring provides OAuth2LoginAuthenticationFilter and OAuth2AuthorizationRequestRedirectFilter but do I have to use implement that?
Spring security filter chain is not configured to include above mentioned filters by default, so we can provide HttpSecurity.oauth2Login(). For Example:
#Override
public void configure(HttpSecurity http) throws Exception {
http.
.
.oauth2Login()
.
.
.clientRegistrationRepository(clientRegistrationRepository())
.authorizedClientService(oAuth2AuthorizedClientService());
}
#Bean
public ClientRegistrationRepository clientRegistrationRepository() {
ClientRegistration github =
CommonOAuth2Provider.GITHUB.getBuilder("github")
.clientId("ClientId")
.clientSecret("ClientSecret")
.redirectUriTemplate("http://localhost:PORT/contextpath/login/oauth2/code/")
.scope("email","profile")
.build();
//inmemory is temporary
List<ClientRegistration> clientRegistrationList = new ArrayList<>();
clientRegistrationList.add(github);
return new InMemoryClientRegistrationRepository(clientRegistrationList);
}
#Bean
public OAuth2AuthorizedClientService oAuth2AuthorizedClientService() {
return new
InMemoryOAuth2AuthorizedClientService(clientRegistrationRepository());
}
which will configure OAuth2LoginAuthenticationFilter and OAuth2AuthorizationRequestRedirectFilter for more information see https://docs.spring.io/spring-security/site/docs/5.0.7.RELEASE/reference/html/oauth2login-advanced.html
Alternative to http.oauth2Login() for adding those 2 filters is to manually configure and add them, which is a little bit not elegant. For example:
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(oAuth2LoginAuthenticationProvider());
}
#Bean
public DefaultAuthorizationCodeTokenResponseClient defaultAuthorizationCodeTokenResponseClient(){
return new DefaultAuthorizationCodeTokenResponseClient();
}
#Bean
public DefaultOAuth2UserService defaultOAuth2UserService(){
return new DefaultOAuth2UserService();
}
#Bean
public OAuth2LoginAuthenticationProvider oAuth2LoginAuthenticationProvider(){
return new OAuth2LoginAuthenticationProvider(defaultAuthorizationCodeTokenResponseClient(),defaultOAuth2UserService());
}
#Bean
public OAuth2LoginAuthenticationFilter oAuth2LoginAuthenticationFilter() throws Exception {
OAuth2LoginAuthenticationFilter oAuth2LoginAuthenticationFilter =
new OAuth2LoginAuthenticationFilter(clientRegistrationRepository(),oAuth2AuthorizedClientService());
oAuth2LoginAuthenticationFilter.setAuthenticationManager(super.authenticationManagerBean());
return oAuth2LoginAuthenticationFilter;
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.
.
.addFilterBefore(oAuth2LoginAuthenticationFilter(), RequestCacheAwareFilter.class)
.addFilterBefore(oAuth2AuthorizationRequestRedirectFilter(),OAuth2LoginAuthenticationFilter.class)
.
.
}

Getting 404 after oauth2 authentication success and an anonymous token

I am using oauth2 with springboot 1.5.6.RELEASE and I am using jdbc authentication with oauth2.
I added the property: security.oauth2.resource.filter-order = 3
1- AuthorizationServerConfigurerAdapter:
#Configuration
#EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
#Lazy
private AuthenticationManager authenticationManager;
#Autowired
private Environment env;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
endpoints.authenticationManager(authenticationManager);
}
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource());
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
}
2- ResourceServerConfigurerAdapter
#EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/ws/**").authorizeRequests().anyRequest().authenticated();
}
}
3- SecurityConfig
#Configuration
#EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private CustomAuthenticationSuccessHandler successHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/", "/registerCompany", "/registerEmployee", "/jobs", "/returnPassword", "/resetPassword",
"/faces/public/**", "/resources/**", "/template/**", "/faces/fonts/*",
"/faces/javax.faces.resource/**", "/ws/**", "/login", "/oauth/**", "/error")
.permitAll().antMatchers("/admin/**", "/faces/admin/**").hasAuthority("ROLE_ADMIN")
.antMatchers("/employeeProfile", "/employeeMainPage", "/employeeAskJob").hasAuthority("ROLE_EMPLOYEE")
.antMatchers("/companyProfile", "/companyMainPage", "/companyPostJob", "/companySearch",
"/branchProfile")
.hasAnyAuthority("ROLE_COMPANY,ROLE_BRANCH,ROLE_ADMIN").anyRequest().fullyAuthenticated().and()
.formLogin().loginPage("/login").permitAll().successHandler(successHandler).failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password").and().logout().deleteCookies("JSESSIONID")
.logoutUrl("/logout").deleteCookies("remember-me").logoutSuccessUrl("/").permitAll().and().rememberMe();
// http.sessionManagement().invalidSessionUrl("/login?invalidSession");
// cache resources
http.headers().addHeaderWriter(new DelegatingRequestMatcherHeaderWriter(
new AntPathRequestMatcher("/javax.faces.resource/**"), new HeaderWriter() {
#Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Cache-Control", "private, max-age=86400");
}
})).defaultsDisabled();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
}
I am trying to generate a token using postman with a post request to url http://localhost:8082/dawam2/oauth/token?grant_type=password
and I use basic authentication and set the username=myclient_id and password=myclient_secret. So the header (Authorization : Basic Basic bXljbGllbnRfaWQ6bXljbGllbnRfc2VjcmV0) was generated
and I set the header Content-Type: application/x-www-form-urlencoded; charset=utf-8.
The response I am getting instead of a generated token :
!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Not Found</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/9.0.0.M18</h3></body></html>
Here are the debugging info:
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token']
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/oauth/token'
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - matched
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-09-26 15:32:16,833 DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#1d47c7a
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', GET]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/logout'
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', POST]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /oauth/token' doesn't match 'POST /logout
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', PUT]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /oauth/token' doesn't match 'PUT /logout
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', DELETE]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /oauth/token' doesn't match 'DELETE /logout
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
2017-09-26 15:32:16,834 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2017-09-26 15:32:16,834 DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Basic Authentication Authorization header found for user 'myclient_id'
2017-09-26 15:32:16,834 DEBUG o.s.s.a.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2017-09-26 15:32:16,849 DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#d9cf8114: Principal: org.springframework.security.core.userdetails.User#6a9879e3: Username: myclient_id; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_EMPLOYEE; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_EMPLOYEE
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#d9cf8114: Principal: org.springframework.security.core.userdetails.User#6a9879e3: Username: myclient_id; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_EMPLOYEE; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_EMPLOYEE'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.s.CompositeSessionAuthenticationStrategy - Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#15d6aaa
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/oauth/token'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /oauth/token?grant_type=password; Attributes: [fullyAuthenticated]
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#d9cf8114: Principal: org.springframework.security.core.userdetails.User#6a9879e3: Username: myclient_id; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_EMPLOYEE; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_EMPLOYEE
2017-09-26 15:32:16,851 DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#14cb584, returned: 1
2017-09-26 15:32:16,851 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful
2017-09-26 15:32:16,851 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object
2017-09-26 15:32:16,851 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password reached end of additional filter chain; proceeding with original chain
2017-09-26 15:32:16,853 DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
2017-09-26 15:32:16,853 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token']
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/oauth/token'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token_key']
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/oauth/token_key'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/check_token']
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/oauth/check_token'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No HttpSession currently exists
2017-09-26 15:32:16,854 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', GET]
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/logout'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', POST]
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'POST /logout
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', PUT]
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'PUT /logout
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', DELETE]
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'DELETE /logout
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'POST /login
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password reached end of additional filter chain; proceeding with original chain
2017-09-26 15:32:16,856 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2017-09-26 15:32:16,856 DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
2017-09-26 15:32:16,856 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
How can I fix this issue?
The issue was related to Jersey configuration, it was stealing requests from oauth2, i had to reconfigure it with #ApplicationPath("/ws")
so the configuration now looks like :
#Configuration
#ApplicationPath("/ws")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(DawamService.class);
}
}
and my webservice implementation class like :
#Component
#Path("/dawam")
public class DawamService extends DawamServiceBase {
#GET
#Produces({ MediaType.TEXT_HTML })
#Path("/test")
public String getHTML() {
System.out.println("##### Welcome to test webservice #########");
return "Welcome to test webservice";
}
}
I have the same problem and I can fixed it.
In my case the reason was in the following:
My servlet-mapping for dispather servlet in web.xml
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
It means the all http requests for access to your resources should be started with '/api' (ex. /api/user/2 or /api/login) even if #RequestMapping points as '/user/{id}' or /login. When you request a token by oauth2/token URL, spring or other filters handle it, but dispatcherServlet could not find any controller corresponding to your request and we have 404 error.
To resolve this, I just added the one method to endpoints in AuthorizationServerConfiguration class.
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
...
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.prefix("/api") //<---- PREFIX WAS ADDED
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
...
}
I think the
.pathMapping("/oauth/token", "/api/oauth/token")
code instead of .prefix("/api") also can resolve the problem.
It changes request for getting the tokens.
After made change I get the tokens by URL
/api/oauth/token
Of course I can mistake but it works for me. Thanks.

not able to display image from a folder

I use spring boot 1.4.3, I created a class to try to access a folder from ther server
#Configuration
public class WebConfigurer extends WebMvcConfigurerAdapter {
#Value("${img.app.path}")
private String imgAppPath;
#Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/img/**").addResourceLocations("/home/bob/bin/");
}
}
In /home/bob/bin/ I have many image:
When I try to access to http://localhost:8080//img/logo.png
I get:
2016-12-28 22:35:44.690 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-12-28 22:35:44.690 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-12-28 22:35:44.691 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-12-28 22:35:44.691 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2016-12-28 22:35:44.691 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2016-12-28 22:35:44.691 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/img/logo.png'; against '/logout'
2016-12-28 22:35:44.691 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2016-12-28 22:35:44.692 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /img/logo.png' doesn't match 'POST /logout
2016-12-28 22:35:44.692 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2016-12-28 22:35:44.692 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /img/logo.png' doesn't match 'PUT /logout
2016-12-28 22:35:44.692 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2016-12-28 22:35:44.692 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /img/logo.png' doesn't match 'DELETE /logout
2016-12-28 22:35:44.692 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2016-12-28 22:35:44.693 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2016-12-28 22:35:44.693 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-12-28 22:35:44.693 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-12-28 22:35:44.693 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-12-28 22:35:44.693 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2016-12-28 22:35:44.693 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2016-12-28 22:35:44.694 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2016-12-28 22:35:44.694 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2016-12-28 22:35:44.694 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/img/logo.png'; against '/rest/**'
2016-12-28 22:35:44.695 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Public object - authentication not attempted
2016-12-28 22:35:44.695 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.security.web.FilterChainProxy : /img/logo.png reached end of additional filter chain; proceeding with original chain
2016-12-28 22:35:44.716 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.header.writers.HstsHeaderWriter : Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#738bf2c8
2016-12-28 22:35:44.717 DEBUG 10000 --- [http-nio-8080-exec-3] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2016-12-28 22:35:44.718 DEBUG 10000 --- [http-nio-8080-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
You need allow access to the static resources with spring security.
<http pattern="/img/**" security="none"/>
Java Config
web.ignoring().antMatchers("/img/**");
And change the resource path.
registry.addResourceHandler("/img/**").addResourceLocations("file:///home/bob/bin/");
Detail see here

Oauth 2.0 configuration conflicts with Spring Security

I am trying to configure an Oauth2 with Spring Security. But my Oauth configuration conflicts with Spring Security configuration.
It seems like the Resource Server configuration is not limited to /api/v0/.* but is overriding ALL security configuration. Resource Server works well. But my form-based authentication with Spring Security doesn't work - it returns the HTTP 404 error.
I have the following code in my WebSecurityConfigurerAdapter
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").access("hasRole('ADMINISTRATOR')")
.antMatchers("/1/admin/**").access("hasRole('ADMINISTRATOR')")
.antMatchers("/profile**").authenticated()
.antMatchers("/oauth/authorize").authenticated()
.and()
.formLogin()
.loginPage("/login")
.failureUrl("/login?error=1")
.loginProcessingUrl("/login-attempt")
.defaultSuccessUrl("/", false)
.and()
.csrf();
}
This is my configuration from ResourceServerConfigurerAdapter
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.regexMatchers("/api/v0/.*").authenticated();
}
Logs
AntPathRequestMatcher:151 - Checking match of request : '/login-attempt'; against '/html/**'
AntPathRequestMatcher:151 - Checking match of request : '/login-attempt'; against '/webapi/**'
OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/token']
AntPathRequestMatcher:151 - Checking match of request : '/login-attempt'; against '/oauth/token'
OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/token_key']
AntPathRequestMatcher:151 - Checking match of request : '/login-attempt'; against '/oauth/token_key'
OrRequestMatcher:65 - Trying to match using Ant [pattern='/oauth/check_token']
AntPathRequestMatcher:151 - Checking match of request : '/login-attempt'; against '/oauth/check_token'
OrRequestMatcher:72 - No matches found
FilterChainProxy:324 - /login-attempt at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
FilterChainProxy:324 - /login-attempt at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
FilterChainProxy:324 - /login-attempt at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
HstsHeaderWriter:128 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#2fa4c8cd
FilterChainProxy:324 - /login-attempt at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
AntPathRequestMatcher:151 - Checking match of request : '/login-attempt'; against '/logout'
FilterChainProxy:324 - /login-attempt at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
BearerTokenExtractor:54 - Token not found in headers. Trying request parameters.
BearerTokenExtractor:57 - Token not found in request parameters. Not an OAuth2 request.
OAuth2AuthenticationProcessingFilter:141 - No token in request, will continue chain.
FilterChainProxy:324 - /login-attempt at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
FilterChainProxy:324 - /login-attempt at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
FilterChainProxy:324 - /login-attempt at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
AnonymousAuthenticationFilter:100 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9056f12c: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 127.0.0.1;SessionId:672t27n01ruouli4a041a0xq;Granted Authorities: ROLE_ANONYMOUS'
FilterChainProxy:324 - /login-attempt at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
FilterChainProxy:324 - /login-attempt at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
FilterChainProxy:324 - /login-attempt at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
RegexRequestMatcher:106 - Checking match of request : '/login-attempt'; against '/api/v0/.*'
FilterSecurityInterceptor:209 - Public object - authentication not attempted
FilterChainProxy:309 - /login-attempt reached end of additional filter chain; proceeding with original chain
What am I doing wrong? Thanks in advance!
Not sure whether it fixes your problem or not. Lets give a try.
Add
#Order(1)
#Order(2)
to your configuration classes and try again.

Resources