Spring Boot 2 OAuth2 Resource Server Does not hit authorization server for access token validation - spring

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

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.

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

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

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