Spring Boot 2 + Spring Security + Login Form + Session Redis not working - spring-boot

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;
}

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!

Client Loading More times in token end point

Token api I am using http://localhost:8086/oauth/token with grant type password
Input:
username:user
password:password
grant_type:password
First hit After running the application:
1)Client is loading is 4 times (loadClientByClientId method from ClientDetailsService interface)
2)Authenticating user one time (authenticate method from AuthenticationManager interface)
3)Again Client Authenticating 3 times
From second hit:
Client is loading 4 times
Authenticating user one time
AuthorizationServerConfig:
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private TokenStore tokenStore;
#Autowired
private MyAuthenticationManager authenticationManager;
#Autowired
MongoClientDetailsService clientdetailservice;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).authenticationManager(authenticationManager).tokenServices(tokenServices());
}
#Primary
public DefaultTokenServices tokenServices() {
DefaultTokenServices defaultTokenServices = new DefaultTokenServices();
defaultTokenServices.setTokenStore(tokenStore);
defaultTokenServices.setSupportRefreshToken(true);
defaultTokenServices.setClientDetailsService(clientdetailservice);
return defaultTokenServices;
}
}
SecurityConfig:
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().anonymous().disable().authorizeRequests().antMatchers("/**").permitAll();
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Bean
public PasswordEncoder encoder() {
return NoOpPasswordEncoder.getInstance();
}
}
MongoClientDetailsService:
#Primary
#Service
public class MongoClientDetailsService implements ClientDetailsService {
static final String CLIEN_ID = "web-client";
static final String CLIENT_SECRET = "web-client-secret";
static final String GRANT_TYPE = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static final int ACCESS_TOKEN_VALIDITY_SECONDS = 1 * 6 * 60;
static final int FREFRESH_TOKEN_VALIDITY_SECONDS = 6 * 60 * 60;
#Override
public ClientDetails loadClientByClientId(String clientId) throws ClientRegistrationException {
System.out.println("loadClientByClientId");
BaseClientDetails clientDetails = new BaseClientDetails();
clientDetails.setClientId(CLIEN_ID);
clientDetails.setAuthorizedGrantTypes(Arrays.asList(GRANT_TYPE, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT));
clientDetails.setClientSecret(CLIENT_SECRET);
clientDetails.setScope(Arrays.asList(SCOPE_READ, SCOPE_WRITE, TRUST));
clientDetails.setAccessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS);
clientDetails.setRefreshTokenValiditySeconds(FREFRESH_TOKEN_VALIDITY_SECONDS);
clientDetails.setAuthorities(getAuthority());
return clientDetails;
}
private List getAuthority() {
return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
}
MyAuthenticationManager:
#Component
public class MyAuthenticationManager implements AuthenticationManager {
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
System.out.println("authenticate");
return new UsernamePasswordAuthenticationToken("123", "123", getAuthority());
}
private List getAuthority() {
return Arrays.asList(new SimpleGrantedAuthority("ROLE_ADMIN"));
}
}
Logs after hitting api:
2020-01-17 00:17:26.204 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token']
2020-01-17 00:17:26.204 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2020-01-17 00:17:26.205 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : matched
2020-01-17 00:17:26.205 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-01-17 00:17:26.206 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-01-17 00:17:26.207 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'GET /logout'
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/logout'
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'PUT /logout'
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'DELETE /logout'
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2020-01-17 00:17:26.209 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2020-01-17 00:17:26.210 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.www.BasicAuthenticationFilter : Basic Authentication Authorization header found for user 'web-client'
2020-01-17 00:17:26.211 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
loadClientByClientId
2020-01-17 00:17:26.214 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.www.BasicAuthenticationFilter : Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8c4296e2: Principal: org.springframework.security.core.userdetails.User#cce1ec64: Username: web-client; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: 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: ROLE_ADMIN
2020-01-17 00:17:26.214 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-01-17 00:17:26.214 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2020-01-17 00:17:26.214 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-01-17 00:17:26.215 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-01-17 00:17:26.216 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8c4296e2: Principal: org.springframework.security.core.userdetails.User#cce1ec64: Username: web-client; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: 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: ROLE_ADMIN'
2020-01-17 00:17:26.216 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-01-17 00:17:26.216 DEBUG 6432 --- [nio-8086-exec-1] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#248deced
2020-01-17 00:17:26.216 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-01-17 00:17:26.216 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-01-17 00:17:26.217 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2020-01-17 00:17:26.217 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2020-01-17 00:17:26.218 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8c4296e2: Principal: org.springframework.security.core.userdetails.User#cce1ec64: Username: web-client; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: 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: ROLE_ADMIN
2020-01-17 00:17:26.222 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#484f35da, returned: 1
2020-01-17 00:17:26.222 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2020-01-17 00:17:26.222 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2020-01-17 00:17:26.222 DEBUG 6432 --- [nio-8086-exec-1] o.s.security.web.FilterChainProxy : /oauth/token reached end of additional filter chain; proceeding with original chain
2020-01-17 00:17:26.228 DEBUG 6432 --- [nio-8086-exec-1] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped to org.springframework.security.oauth2.provider.endpoint.TokenEndpoint#postAccessToken(Principal, Map)
loadClientByClientId
loadClientByClientId
loadClientByClientId
2020-01-17 00:17:26.246 DEBUG 6432 --- [nio-8086-exec-1] .o.p.p.ResourceOwnerPasswordTokenGranter : Getting access token for: web-client
authenticate
loadClientByClientId
loadClientByClientId
loadClientByClientId
2020-01-17 00:17:26.299 DEBUG 6432 --- [nio-8086-exec-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#4f98e90
2020-01-17 00:17:26.305 DEBUG 6432 --- [nio-8086-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2020-01-17 00:17:26.305 DEBUG 6432 --- [nio-8086-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Yup. That's known. Spring Security hits your store a bunch of times during the authentication process.

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 Boot 2 OAuth2 Resource Server Does not hit authorization server for access token validation

I have implemented Spring boot 2 + OAuth2 Oauthorization server.
I only want to use Client_credential to secure resource Server
I am able to get access token from Auth server, but when I pass this to access rest api, resource server does not validate it from authorization server and gives invalid access token error, I am using postman to get access token and to quest resource server.
Authorization Server
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class AuthorizationApplication {
public static void main(String[] args) {
SpringApplication.run(AuthorizationApplication.class, args);
}
}
Authorization server config
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
private static final String SERVER_RESOURCE_ID = "oauth2-server";
private static InMemoryTokenStore tokenStore = new InMemoryTokenStore();
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager).tokenStore(tokenStore).approvalStoreDisabled();
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.inMemory().withClient("clientABC").secret("{noop}secretXYZ")
.authorizedGrantTypes("client_credentials")
.scopes("resource-server-read", "resource-server-write")
.resourceIds(SERVER_RESOURCE_ID);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
}
Authorization server web config
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
#Configuration
public class AuthorizationServerWebConfig extends WebSecurityConfigurerAdapter {
#Bean
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().permitAll();
}
}
Controller
import java.security.Principal;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class AuthorizationServerController {
#RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
}
Application.yml
server:
port: 8090
logging:
file: /logs/AuthourizationServer.log
level:
org.springframework: DEBUG
pattern:
file: "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx"
security:
basic:
enabled: false
Resource Server
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ResourceApplication {
public static void main(String[] args) {
SpringApplication.run(ResourceApplication.class, args);
}
}
Web security config
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
#EnableResourceServer
#Configuration
public class ResourceApplicationWebSecurityConfig extends ResourceServerConfigurerAdapter {
private static final String[] AUTH_WHITELIST = {
// -- swagger ui
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/**",
"/configuration/ui",
"/configuration/security",
"/swagger-ui.html",
"/webjars/**"
// other public endpoints of your API may be appended to this array
};
#Autowired
private WebEndpointProperties webEndpointProperties;
#Override
public void configure(HttpSecurity http) throws Exception{
http.authorizeRequests().antMatchers(webEndpointProperties.getBasePath()+"/health").permitAll().and()
.authorizeRequests().antMatchers("/swagger-ui.html").permitAll().and()
.authorizeRequests().antMatchers(AUTH_WHITELIST).permitAll().and()
.authorizeRequests().antMatchers("/nonsecured").permitAll()
.anyRequest().authenticated();
}
}
Rest Controller
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ResourceServerController {
#RequestMapping(value = "/secured", method = RequestMethod.GET)
public String securedResource() {
return "This is Secured Resource";
}
#RequestMapping(value = "/nonsecured", method = RequestMethod.GET)
public String nonSecuredResource() {
return "This is Non Secured Resource";
}
}
Application.yml
server:
port: 8092
security:
oauth2:
resource:
user-info-uri: http://localhost:8090/user
basic:
enabled: false
logging:
file: /logs/ResourceServer.log
level:
org.springframework: DEBUG
pattern:
file: "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx"
Postman : getting token from Authorization server
Postman : getting token from Authorization server
Querying secured service and getting erro
AuthorizationServer logs
2018-12-30 21:04:40.599 INFO 5144 --- [nio-8090-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-12-30 21:04:40.599 INFO 5144 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2018-12-30 21:04:40.599 DEBUG 5144 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2018-12-30 21:04:40.599 DEBUG 5144 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2018-12-30 21:04:40.599 INFO 5144 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 0 ms
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token']
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : matched
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'GET /logout'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/logout'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'PUT /logout'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /oauth/token' doesn't match 'DELETE /logout'
2018-12-30 21:04:40.600 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2018-12-30 21:04:40.615 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2018-12-30 21:04:40.615 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.www.BasicAuthenticationFilter : Basic Authentication Authorization header found for user 'clientABC'
2018-12-30 21:04:40.631 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2018-12-30 21:04:40.742 DEBUG 5144 --- [nio-8090-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Creating shared instance of singleton bean 'scopedTarget.clientDetailsService'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=2018-12-30T20:04:40.758Z, principal=clientABC, type=AUTHENTICATION_SUCCESS, data={details=org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null}]
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.www.BasicAuthenticationFilter : Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#717e3c37: Principal: org.springframework.security.core.userdetails.User#8e817097: Username: clientABC; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#717e3c37: Principal: org.springframework.security.core.userdetails.User#8e817097: Username: clientABC; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] s.CompositeSessionAuthenticationStrategy : Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#5a1c3cb4
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2018-12-30 21:04:40.758 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#717e3c37: Principal: org.springframework.security.core.userdetails.User#8e817097: Username: clientABC; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Not granted any authorities; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Not granted any authorities
2018-12-30 21:04:40.773 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#76d8c502, returned: 1
2018-12-30 21:04:40.773 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2018-12-30 21:04:40.773 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2018-12-30 21:04:40.773 DEBUG 5144 --- [nio-8090-exec-1] o.s.security.web.FilterChainProxy : /oauth/token reached end of additional filter chain; proceeding with original chain
2018-12-30 21:04:40.789 DEBUG 5144 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : POST "/oauth/token", parameters={masked}
2018-12-30 21:04:40.790 DEBUG 5144 --- [nio-8090-exec-1] .s.o.p.e.FrameworkEndpointHandlerMapping : Mapped to public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.postAccessToken(java.security.Principal,java.util.Map<java.lang.String, java.lang.String>) throws org.springframework.web.HttpRequestMethodNotSupportedException
2018-12-30 21:04:40.842 DEBUG 5144 --- [nio-8090-exec-1] .s.s.o.p.c.ClientCredentialsTokenGranter : Getting access token for: clientABC
2018-12-30 21:04:40.858 DEBUG 5144 --- [nio-8090-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Found 'Content-Type:application/json;charset=UTF-8' in response
2018-12-30 21:04:40.905 DEBUG 5144 --- [nio-8090-exec-1] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [087b1986-b76e-4ff5-8e84-63ecd62e9583]
2018-12-30 21:04:40.920 DEBUG 5144 --- [nio-8090-exec-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#38dba2a
2018-12-30 21:04:40.921 DEBUG 5144 --- [nio-8090-exec-1] o.s.web.servlet.DispatcherServlet : Completed 200 OK
2018-12-30 21:04:40.921 DEBUG 5144 --- [nio-8090-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2018-12-30 21:04:40.921 DEBUG 5144 --- [nio-8090-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Resource Server logs
2018-12-30 21:04:54.158 INFO 8512 --- [nio-8092-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2018-12-30 21:04:54.158 INFO 8512 --- [nio-8092-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2018-12-30 21:04:54.158 DEBUG 8512 --- [nio-8092-exec-1] o.s.web.servlet.DispatcherServlet : Detected StandardServletMultipartResolver
2018-12-30 21:04:54.159 DEBUG 8512 --- [nio-8092-exec-1] o.s.web.servlet.DispatcherServlet : enableLoggingRequestDetails='false': request parameters and headers will be masked to prevent unsafe logging of potentially sensitive data
2018-12-30 21:04:54.159 INFO 8512 --- [nio-8092-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.security.web.FilterChainProxy : /secured?access_token=087b1986-b76e-4ff5-8e84-63ecd62e9583 at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.security.web.FilterChainProxy : /secured?access_token=087b1986-b76e-4ff5-8e84-63ecd62e9583 at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.security.web.FilterChainProxy : /secured?access_token=087b1986-b76e-4ff5-8e84-63ecd62e9583 at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.security.web.FilterChainProxy : /secured?access_token=087b1986-b76e-4ff5-8e84-63ecd62e9583 at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/secured'; against '/logout'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /secured' doesn't match 'POST /logout'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /secured' doesn't match 'PUT /logout'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /secured' doesn't match 'DELETE /logout'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.security.web.FilterChainProxy : /secured?access_token=087b1986-b76e-4ff5-8e84-63ecd62e9583 at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2018-12-30 21:04:54.190 DEBUG 8512 --- [nio-8092-exec-1] o.s.s.o.p.a.BearerTokenExtractor : Token not found in headers. Trying request parameters.
2018-12-30 21:04:54.206 DEBUG 8512 --- [nio-8092-exec-1] p.a.OAuth2AuthenticationProcessingFilter : Authentication request failed: error="invalid_token", error_description="Invalid access token: 087b1986-b76e-4ff5-8e84-63ecd62e9583"
2018-12-30 21:04:54.206 DEBUG 8512 --- [nio-8092-exec-1] o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=2018-12-30T20:04:54.206Z, principal=access-token, type=AUTHENTICATION_FAILURE, data={type=org.springframework.security.authentication.BadCredentialsException, message=Invalid access token: 087b1986-b76e-4ff5-8e84-63ecd62e9583}]
2018-12-30 21:04:54.300 DEBUG 8512 --- [nio-8092-exec-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#582fa201
2018-12-30 21:04:54.300 DEBUG 8512 --- [nio-8092-exec-1] s.s.o.p.e.DefaultOAuth2ExceptionRenderer : Written [error="invalid_token", error_description="Invalid access token: 087b1986-b76e-4ff5-8e84-63ecd62e9583"] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#29184e62]
2018-12-30 21:04:54.300 DEBUG 8512 --- [nio-8092-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
complete code is available in gihub
https://github.com/harsh-hardaha/springboot2Oauth2
Please ignore Admin server and swagger configuration code in github
After Some more inspection and debug I found Solution, I have to make below changes in resource server configuration
Application.yml
security:
oauth2:
client:
clientId: clientABC
clientSecret: secretXYZ
resource:
user-info-uri: http://localhost:8090/user
token-info-uri: http://localhost:8090/oauth/check_token
preferTokenInfo: true
filter-order: 3
basic:
enabled: false
included dependency in resource server
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.1.1.RELEASE</version>
</dependency>
I faced similar issue and adding the spring-security-oauth2-autoconfigure dependency in resource server solved my problem.
My application.yml :
security:
oauth2:
resource:
userInfoUri: http://localhost:8901/auth/user

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

Resources