not able to display image from a folder - spring

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

Related

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

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.

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 Boot 2 + Spring Security + Login Form + Session Redis not working

I'm trying to use Spring Boot 2 + Spring Security + Session Redis but for some reason after login the page is redirect to / but got access denied then page is back to login, anyone knows how to solve that please?
Following piece of code.
Security Config
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers(WHITELIST).permitAll()
.anyRequest().hasRole("ADMIN")
.and()
.formLogin()
.and()
.logout();
}
Spring Boot Config
spring:
application:
name: eureka-server
session:
store-type: redis
Stacktrace
2019-09-29 18:43:23.578 INFO 29922 --- [nio-8761-exec-2] Spring Security Debugger :
2019-09-30 21:27:15.053 DEBUG 28916 --- [nio-8761-exec-3] o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=2019-09-30T20:27:15.051Z, principal=admin#gmail.com, type=AUTHENTICATION_SUCCESS, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null}]
2019-09-30 21:27:15.054 DEBUG 28916 --- [nio-8761-exec-3] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#4910afdf
2019-09-30 21:27:15.055 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-30 21:27:15.055 DEBUG 28916 --- [nio-8761-exec-3] w.a.UsernamePasswordAuthenticationFilter : Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#4893c999: Principal: Authentication(id=5d8d299d42eba40001932c0f, email=admin#gmail.com, password={bcrypt}$2a$10$DNbJo.ktPvjiVbsZdKEmDeC27R3y4RW/XZ1WsCSjPNmEmIf9JozNi, fullName=Admin dos Santos, enabled=true, authorities=[Authority(role=ROLE_ADMIN)]); 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: Authority(role=ROLE_ADMIN)
2019-09-30 21:27:15.057 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-30 21:27:15.057 DEBUG 28916 --- [nio-8761-exec-3] RequestAwareAuthenticationSuccessHandler : Using default Url: /
2019-09-30 21:27:15.057 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.web.DefaultRedirectStrategy : Redirecting to '/'
2019-09-30 21:27:15.057 DEBUG 28916 --- [nio-8761-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#2f60713f
2019-09-30 21:27:15.058 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-30 21:27:15.058 DEBUG 28916 --- [nio-8761-exec-3] w.c.HttpSessionSecurityContextRepository : HttpSession being created as SecurityContext is non-default
2019-09-30 21:27:15.058 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-30 21:27:15.058 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-30 21:27:15.059 DEBUG 28916 --- [nio-8761-exec-3] o.s.s.w.h.S.SESSION_LOGGER : A new session was created. To help you troubleshoot where the session was created we provided a StackTrace (this is not an error). You can prevent this from appearing by disabling DEBUG logging for org.springframework.session.web.http.SessionRepositoryFilter.SESSION_LOGGER
************************************************************
Request received for GET '/':
org.springframework.session.web.http.SessionRepositoryFilter$SessionRepositoryRequestWrapper#fc73db7
servletPath:/
pathInfo:null
headers:
host: localhost:8761
connection: keep-alive
cache-control: max-age=0
upgrade-insecure-requests: 1
user-agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
sec-fetch-mode: navigate
sec-fetch-user: ?1
accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
sec-fetch-site: same-origin
referer: http://localhost:8761/login
accept-encoding: gzip, deflate, br
accept-language: en-IE,en;q=0.9,pt-BR;q=0.8,pt;q=0.7,en-US;q=0.6
cookie: io=udDSi_WRWSnc1P5rAAAB; JSESSIONID=711725AFFC0C8C60E5A099A72EF2F420
Security filter chain: [
WebAsyncManagerIntegrationFilter
SecurityContextPersistenceFilter
HeaderWriterFilter
LogoutFilter
UsernamePasswordAuthenticationFilter
DefaultLoginPageGeneratingFilter
DefaultLogoutPageGeneratingFilter
RequestCacheAwareFilter
SecurityContextHolderAwareRequestFilter
AnonymousAuthenticationFilter
SessionManagementFilter
ExceptionTranslationFilter
FilterSecurityInterceptor
]
************************************************************
2019-09-29 18:43:23.579 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 1 of 13 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-09-29 18:43:23.579 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 2 of 13 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 3 of 13 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 4 of 13 in additional filter chain; firing Filter: 'LogoutFilter'
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/logout'
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /' doesn't match 'POST /logout'
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /' doesn't match 'PUT /logout'
2019-09-29 18:43:23.580 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /' doesn't match 'DELETE /logout'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 5 of 13 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /' doesn't match 'POST /login'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 6 of 13 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 7 of 13 in additional filter chain; firing Filter: 'DefaultLogoutPageGeneratingFilter'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/logout'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 8 of 13 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-29 18:43:23.581 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2019-09-29 18:43:23.582 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 9 of 13 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 10 of 13 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#8360265a: 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'
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 11 of 13 in additional filter chain; firing Filter: 'SessionManagementFilter'
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.h.S.SESSION_LOGGER : No session found by id: Caching result for getSession(false) for this HttpServletRequest.
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2019-09-29 18:43:23.583 DEBUG 29922 --- [nio-8761-exec-2] o.s.security.web.FilterChainProxy : / at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/eureka/apps/**'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/logout'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/actuator/**'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/v1/agent/self'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/eureka/peerreplication/batch/**'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/v1/catalog/services'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/v1/catalog/service/**'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/**/*.js'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/**/*.css'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/**/*.html'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/'; against '/favicon.ico'
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /; Attributes: [hasRole('ROLE_ADMIN')]
2019-09-29 18:43:23.584 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#8360265a: 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
2019-09-29 18:43:23.586 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5a1e2d1b, returned: -1
2019-09-29 18:43:23.587 DEBUG 29922 --- [nio-8761-exec-2] o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=2019-09-29T17:43:23.586Z, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null, type=org.springframework.security.access.AccessDeniedException, message=Access is denied}]
2019-09-29 18:43:23.588 DEBUG 29922 --- [nio-8761-exec-2] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point
org.springframework.security.access.AccessDeniedException: Access is denied
pom.xml
<dependency>
<groupId>org.springframework.session</groupId>
<artifactId>spring-session-data-redis</artifactId>
</dependency>
<dependency>
<groupId>io.lettuce</groupId>
<artifactId>lettuce-core</artifactId>
</dependency>
I've tried to follow example of documentation but got same issue - https://docs.spring.io/spring-session/docs/current/reference/html5/guides/boot-redis.html
PS: Using Docker
Fixed the issue adding a Custom CookieSerializer.
#Bean
public CookieSerializer cookieSerializer() {
DefaultCookieSerializer serializer = new DefaultCookieSerializer();
serializer.setCookieName("SESSIONID");
serializer.setCookiePath("/");
serializer.setDomainNamePattern("^.+?\\.(\\w+\\.[a-z]+)$");
return serializer;
}

Access Token not being fetched from Authorization Code in Spring Security Oauth2? Call for access token fails giving ERR_TOO_MANY_REDIRECTS?

I'm writing a spring-boot application which is an Oauth2 client, I'm using my Organization's Oauth server (custom written). I'm running into trouble while fetching the access token. Initially, the call for the authorization code works fine, the server redirects to my application with code=RANDOM_AUTHORIZATION_CODE. But the application doesn't try to fetch the access token from this authorization code. It treats redirect request as a new one and fetches the code again, and the original call ends up giving ERR_TOO_MANY_REDIRECTS.
I am not sure if I am supposed to do something more (like fetch token manually making a network call from my application). I was unable to get any documentation regarding this. Can someone guide me on what I'm doing wrong?
Here's the configure method that is in the config class which extends WebSecurityConfigurerAdapter
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("login","/login/**","oauth2/**")
.permitAll()
.anyRequest()
.authenticated()
.and()
.oauth2Login()
.authorizationEndpoint()
.baseUri("/oauth2/authorize")
.authorizationRequestResolver(customAuthResolver())
.and()
.redirectionEndpoint()
.baseUri("/oauth2/callback")
.and()
.tokenEndpoint()
.accessTokenResponseClient(accessTokenResponseClient())
.and()
.userInfoEndpoint()
.and();
}
#Bean
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
DefaultAuthorizationCodeTokenResponseClient accessTokenResponseClient = new DefaultAuthorizationCodeTokenResponseClient();
return accessTokenResponseClient;
}
Here's the application.yml which has oauth2 configs.
security:
basic:
enabled: false
oauth2:
client:
clientId: pgm-backend
clientSecret: 2XmrKjm2AJkWrSl2WwaqMBioHHQB6YOgSlaBWR0
accessTokenUri: https://auth.server.com/oauth2/token
userAuthorizationUri: https://auth.server.com/oauth2/auth
redirectUri: http://localhost:9095/oauth2/callback
scope:
- openid
- offline
tokenName: oauth_token
resource:
userInfoUri: https://auth.server.com/userinfo
preferTokenInfo: false
Please note that, I wanted to override the state parameter Spring Security automatically adds to the authorization request before making the request to match the validations of the auth server, hence I used
customAuthResolver() which is an instance of class that implements
OAuth2AuthorizationRequestResolver .
The Error is as follows:
Auth server call goes like this: https://auth.server.com/oauth2/auth?response_type=code&client_id=pgm-backend&scope=openid%20offline&state={STATE}&redirect_uri=http://localhost:9095/oauth2/callback/pgm-backend
Redirection I get: http://localhost:9095/oauth2/callback/pgm-backend?code={CODE}&scope=openid%20offline&state={STATE}
This call is again treated as a new one and the application fetches another auth code. This happens a few times and I end up with ERR_TOO_MANY_REDIRECTS.
Debug logs
2019-07-31 22:53:29.082 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/api/v1/currency/code/23' matched by universal pattern '/**'
2019-07-31 22:53:29.083 DEBUG 1094 --- [ XNIO-1 task-1] o.s.security.web.FilterChainProxy : /api/v1/currency/code/23 at position 1 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-07-31 22:53:29.085 DEBUG 1094 --- [ XNIO-1 task-1] o.s.security.web.FilterChainProxy : /api/v1/currency/code/23 at position 2 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-07-31 22:53:29.086 DEBUG 1094 --- [ XNIO-1 task-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2019-07-31 22:53:29.086 DEBUG 1094 --- [ XNIO-1 task-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2019-07-31 22:53:29.088 DEBUG 1094 --- [ XNIO-1 task-1] o.s.security.web.FilterChainProxy : /api/v1/currency/code/23 at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-07-31 22:53:29.088 DEBUG 1094 --- [ XNIO-1 task-1] o.s.security.web.FilterChainProxy : /api/v1/currency/code/23 at position 4 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
2019-07-31 22:53:29.088 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/v1/currency/code/23'; against '/logout'
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /api/v1/currency/code/23' doesn't match 'POST /logout'
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /api/v1/currency/code/23' doesn't match 'PUT /logout'
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /api/v1/currency/code/23' doesn't match 'DELETE /logout'
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2019-07-31 22:53:29.089 DEBUG 1094 --- [ XNIO-1 task-1] o.s.security.web.FilterChainProxy : /api/v1/currency/code/23 at position 5 of 15 in additional filter chain; firing Filter: 'OAuth2AuthorizationRequestRedirectFilter'
2019-07-31 22:53:29.103 DEBUG 1094 --- [ XNIO-1 task-1] o.s.s.web.DefaultRedirectStrategy : Redirecting to 'https://auth.dev.server.com/oauth2/auth?response_type=code&client_id=pgm-backend&scope=openid%20offline&state=A17nHr-X3SO0fovVsVKUs0XbfxwknQ0kYZnfAYubNEw%3D&redirect_uri=http://localhost:9095/oauth2/callback'
2019-07-31 22:53:29.103 DEBUG 1094 --- [ XNIO-1 task-1] 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#5508a98e
2019-07-31 22:53:29.104 DEBUG 1094 --- [ XNIO-1 task-1] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2019-07-31 22:53:29.129 DEBUG 1094 --- [ XNIO-1 task-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
=======================================================
2019-07-31 22:53:29.603 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/oauth2/callback' matched by universal pattern '/**'
2019-07-31 22:53:29.603 DEBUG 1094 --- [ XNIO-1 task-2] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jF6na6l9dkyvdFvw6gXZenvxAG02ww4YuV1DCfH6Dks.q79aNezWFuP-PK_JXgbEz7KhUEmv6VRe12obVB3j8ho&scope=openid%20offline&state=A17nHr-X3SO0fovVsVKUs0XbfxwknQ0kYZnfAYubNEw%3D at position 1 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-07-31 22:53:29.603 DEBUG 1094 --- [ XNIO-1 task-2] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jF6na6l9dkyvdFvw6gXZenvxAG02ww4YuV1DCfH6Dks.q79aNezWFuP-PK_JXgbEz7KhUEmv6VRe12obVB3j8ho&scope=openid%20offline&state=A17nHr-X3SO0fovVsVKUs0XbfxwknQ0kYZnfAYubNEw%3D at position 2 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: io.undertow.servlet.spec.HttpSessionImpl#1dede21d. A new one will be created.
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jF6na6l9dkyvdFvw6gXZenvxAG02ww4YuV1DCfH6Dks.q79aNezWFuP-PK_JXgbEz7KhUEmv6VRe12obVB3j8ho&scope=openid%20offline&state=A17nHr-X3SO0fovVsVKUs0XbfxwknQ0kYZnfAYubNEw%3D at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jF6na6l9dkyvdFvw6gXZenvxAG02ww4YuV1DCfH6Dks.q79aNezWFuP-PK_JXgbEz7KhUEmv6VRe12obVB3j8ho&scope=openid%20offline&state=A17nHr-X3SO0fovVsVKUs0XbfxwknQ0kYZnfAYubNEw%3D at position 4 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth2/callback'; against '/logout'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /oauth2/callback' doesn't match 'POST /logout'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /oauth2/callback' doesn't match 'PUT /logout'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /oauth2/callback' doesn't match 'DELETE /logout'
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2019-07-31 22:53:29.604 DEBUG 1094 --- [ XNIO-1 task-2] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jF6na6l9dkyvdFvw6gXZenvxAG02ww4YuV1DCfH6Dks.q79aNezWFuP-PK_JXgbEz7KhUEmv6VRe12obVB3j8ho&scope=openid%20offline&state=A17nHr-X3SO0fovVsVKUs0XbfxwknQ0kYZnfAYubNEw%3D at position 5 of 15 in additional filter chain; firing Filter: 'OAuth2AuthorizationRequestRedirectFilter'
2019-07-31 22:53:29.605 DEBUG 1094 --- [ XNIO-1 task-2] o.s.s.web.DefaultRedirectStrategy : Redirecting to 'https://auth.dev.server.com/oauth2/auth?response_type=code&client_id=pgm-backend&scope=openid%20offline&state=9vVqWfKQCu24UWrG9hItXiFGqExrfSQ6OEYKyJUu-nI%3D&redirect_uri=http://localhost:9095/oauth2/callback'
2019-07-31 22:53:29.606 DEBUG 1094 --- [ XNIO-1 task-2] 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#5508a98e
2019-07-31 22:53:29.606 DEBUG 1094 --- [ XNIO-1 task-2] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2019-07-31 22:53:29.607 DEBUG 1094 --- [ XNIO-1 task-2] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
=======================================================
2019-07-31 22:53:30.407 DEBUG 1094 --- [ XNIO-1 task-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/oauth2/callback' matched by universal pattern '/**'
2019-07-31 22:53:32.106 DEBUG 1094 --- [ XNIO-1 task-6] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jIhYeU5grp9temJiB8WT94ctAyfQrRXDAkHZBO8vMRc.6DSC0Yo7a37uRKj69TYb4WzBd4MivaqmrksZPLvwaFM&scope=openid%20offline&state=4mz3iODP4Z6I9NoVM8XUjGxToUdumyQj5Skksd0oD8M%3D at position 1 of 15 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2019-07-31 22:53:32.106 DEBUG 1094 --- [ XNIO-1 task-6] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jIhYeU5grp9temJiB8WT94ctAyfQrRXDAkHZBO8vMRc.6DSC0Yo7a37uRKj69TYb4WzBd4MivaqmrksZPLvwaFM&scope=openid%20offline&state=4mz3iODP4Z6I9NoVM8XUjGxToUdumyQj5Skksd0oD8M%3D at position 2 of 15 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2019-07-31 22:53:32.108 DEBUG 1094 --- [ XNIO-1 task-6] w.c.HttpSessionSecurityContextRepository : HttpSession returned null object for SPRING_SECURITY_CONTEXT
2019-07-31 22:53:32.108 DEBUG 1094 --- [ XNIO-1 task-6] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: io.undertow.servlet.spec.HttpSessionImpl#1dede21d. A new one will be created.
2019-07-31 22:53:32.108 DEBUG 1094 --- [ XNIO-1 task-6] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jIhYeU5grp9temJiB8WT94ctAyfQrRXDAkHZBO8vMRc.6DSC0Yo7a37uRKj69TYb4WzBd4MivaqmrksZPLvwaFM&scope=openid%20offline&state=4mz3iODP4Z6I9NoVM8XUjGxToUdumyQj5Skksd0oD8M%3D at position 3 of 15 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-07-31 22:53:32.108 DEBUG 1094 --- [ XNIO-1 task-6] o.s.security.web.FilterChainProxy : /oauth2/callback?code=jIhYeU5grp9temJiB8WT94ctAyfQrRXDAkHZBO8vMRc.6DSC0Yo7a37uRKj69TYb4WzBd4MivaqmrksZPLvwaFM&scope=openid%20offline&state=4mz3iODP4Z6I9NoVM8XUjGxToUdumyQj5Skksd0oD8M%3D at position 4 of 15 in additional filter chain; firing Filter: 'LogoutFilter'
2019-07-31 22:53:32.108 DEBUG 1094 --- [ XNIO-1 task-6] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
.... so on, in a loop
Please also note that the auth server is being used by other python and javascript based applications successfully, and any error is only from my application.
My issue was in the custom authorization request resolver. I was not returning null as the OAuth2AuthorizationRequest in the resolve method (which overrides resolve method of OAuth2AuthorizationRequestResolver) in the case where registrationId was null. So OAuth2AuthorizationRequestRedirectFilter was being applied to all URLs instead of only the auth callback one.

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)
.
.
}

Resources