Unable to get EnableOauth2Sso Working -- BadCredentialsException: Could not obtain access token - spring

I'm trying to get a simple Spring OAuth2 SSO application working and I've been unable to do so. Here's the steps and results of what's happened:
Hit endpoint /user, which is secured by OAuth2
I get forwarded to a simple Spring OAuth2 authorization server
I authenticate to the authorization server
I approved the access
Then I get a white label error page on the OAuth2 SSO application with the following:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jul 13 08:19:18 EDT 2015
There was an unexpected error (type=Unauthorized, status=401).
Authentication Failed: Could not obtain access token
The authorization code is in the URL. Here is the sample URL below:
http://localhost:8083/login?code=9s63rU&state=Fo9S2M
I'm not seeing an HTTP POST to the authorization server /oauth/token endpoint to acquire a JWT. I validated this through the /trace endpoint on the authorization server.
The exception stack is:
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/css/**'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/js/**'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/images/**'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/**/favicon.ico'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/error'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/health']
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/health'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/health/**']
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/health/**'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/health.*']
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/health.*'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/info']
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/info'
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/info/**']
2015-07-13 08:23:32.695 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/info/**'
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/info.*']
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/info.*'
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/restart']
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/restart'
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/restart/**']
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/restart/**'
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/restart.*']
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/restart.*'
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/env']
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/env'
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/env/**']
2015-07-13 08:23:32.696 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/env/**'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/env.*']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/env.*'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/refresh']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/refresh'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/refresh/**']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/refresh/**'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/refresh.*']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/refresh.*'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/metrics']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/metrics'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/metrics/**']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/metrics/**'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/metrics.*']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/metrics.*'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/pause']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/pause'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/pause/**']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/pause/**'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/pause.*']
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/pause.*'
2015-07-13 08:23:32.699 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/resume']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/resume'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/resume/**']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/resume/**'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/resume.*']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/resume.*'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/dump']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/dump'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/dump/**']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/dump/**'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/dump.*']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/dump.*'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/configprops']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/configprops'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/configprops/**']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/configprops/**'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/configprops.*']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/configprops.*'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/trace']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/trace'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/trace/**']
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/trace/**'
2015-07-13 08:23:32.700 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/trace.*']
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/trace.*'
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/beans']
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/beans'
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/beans/**']
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/beans/**'
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/beans.*']
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/beans.*'
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/mappings']
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/mappings'
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/mappings/**']
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/mappings/**'
2015-07-13 08:23:32.701 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/mappings.*']
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/mappings.*'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/autoconfig']
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/autoconfig'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/autoconfig/**']
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/autoconfig/**'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/autoconfig.*']
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/autoconfig.*'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Request '/login' matched by universal pattern '/**'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.security.web.FilterChainProxy : /login?code=9s63rU&state=Fo9S2M at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.security.web.FilterChainProxy : /login?code=9s63rU&state=Fo9S2M at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] o.s.security.web.FilterChainProxy : /login?code=9s63rU&state=Fo9S2M at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2015-07-13 08:23:32.702 DEBUG 3516 --- [nio-8083-exec-7] 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#59b4132c
2015-07-13 08:23:32.703 DEBUG 3516 --- [nio-8083-exec-7] o.s.security.web.FilterChainProxy : /login?code=9s63rU&state=Fo9S2M at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2015-07-13 08:23:32.703 DEBUG 3516 --- [nio-8083-exec-7] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/logout'
2015-07-13 08:23:32.703 DEBUG 3516 --- [nio-8083-exec-7] o.s.security.web.FilterChainProxy : /login?code=9s63rU&state=Fo9S2M at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2ClientAuthenticationProcessingFilter'
2015-07-13 08:23:32.703 DEBUG 3516 --- [nio-8083-exec-7] uth2ClientAuthenticationProcessingFilter : Request is to process authentication
2015-07-13 08:23:32.704 DEBUG 3516 --- [nio-8083-exec-7] uth2ClientAuthenticationProcessingFilter : Authentication request failed: org.springframework.security.authentication.BadCredentialsException: Could not obtain access token
2015-07-13 08:23:32.705 DEBUG 3516 --- [nio-8083-exec-7] uth2ClientAuthenticationProcessingFilter : Updated SecurityContextHolder to contain null Authentication
2015-07-13 08:23:32.705 DEBUG 3516 --- [nio-8083-exec-7] uth2ClientAuthenticationProcessingFilter : Delegating to authentication failure handler org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler#6a650b1c
2015-07-13 08:23:32.705 DEBUG 3516 --- [nio-8083-exec-7] .a.SimpleUrlAuthenticationFailureHandler : No failure URL set, sending 401 Unauthorized error
2015-07-13 08:23:32.705 DEBUG 3516 --- [nio-8083-exec-7] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2015-07-13 08:23:32.705 DEBUG 3516 --- [nio-8083-exec-7] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
My sample OAuth2 SSO application:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.security.oauth2.sso.EnableOAuth2Sso;
import org.springframework.cloud.security.oauth2.sso.OAuth2SsoConfigurerAdapter;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
#SpringBootApplication
public class OAuth2ClientApplication {
public static void main(String[] args) {
SpringApplication.run(OAuth2ClientApplication.class, args);
}
#RestController
public static class SecuredController {
#RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
}
#Configuration
#EnableOAuth2Sso
public static class OAuthSsoConfig extends OAuth2SsoConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.logout()
.and().antMatcher("/**")
.authorizeRequests()
.antMatchers("/index.html", "/home.html", "/", "/login").permitAll()
.anyRequest()
.authenticated()
.and().csrf().disable();
}
}
}
The POM:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test</groupId>
<artifactId>oauth2-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>OAuth2 Client</name>
<description>OAuth2 Client POC</description>
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Angel.SR3</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-oauth2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-jwt</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My application.properties file:
server.port=8083
security.basic.enabled=false
spring.oauth2.client.accessTokenUri=http://localhost:8081/oauth/token
spring.oauth2.client.userAuthorizationUri=http://localhost:8081/oauth/authorize
spring.oauth2.client.clientId=oauth2Client
spring.oauth2.client.clientSecret=oauth2ClientSecret
spring.oauth2.resource.jwt.keyUri=http://localhost:8081/oauth/token_key
logging.level.org.springframework.security=DEBUG
If you need the code for the authorization server please let me know.
:: UPDATE 1 ::
I started debugging this and come to find out the actual exception being thrown is an InvalidRequestException with a message of: Possible CSRF detected - state parameter was present but no state could be found on line 244 of AuthorizationCodeAccessTokenProvider.
I tried modifying my Oauth2SsoConfigurerAdapter to this, but I'm still getting the same exception:
#Configuration
protected static class SecurityConfiguration extends OAuth2SsoConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.logout().and().antMatcher("/**").authorizeRequests()
.antMatchers("/index.html", "/home.html", "/", "/login").permitAll()
.anyRequest().authenticated().and().csrf()
.csrfTokenRepository(csrfTokenRepository()).and()
.addFilterAfter(csrfHeaderFilter(), CsrfFilter.class);
}
private Filter csrfHeaderFilter() {
return new OncePerRequestFilter() {
#Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
CsrfToken csrf = (CsrfToken) request.getAttribute(CsrfToken.class
.getName());
if (csrf != null) {
Cookie cookie = WebUtils.getCookie(request, "XSRF-TOKEN");
String token = csrf.getToken();
if (cookie == null || token != null
&& !token.equals(cookie.getValue())) {
cookie = new Cookie("XSRF-TOKEN", token);
cookie.setPath("/");
response.addCookie(cookie);
}
}
filterChain.doFilter(request, response);
}
};
}
private CsrfTokenRepository csrfTokenRepository() {
HttpSessionCsrfTokenRepository repository = new HttpSessionCsrfTokenRepository();
repository.setHeaderName("X-XSRF-TOKEN");
return repository;
}
}
:: UPDATE 2 ::
The InvalidRequestException is being thrown because the preservedState from the DefaultAccessTokenRequest is returning null (see line 239 of AuthorizationCodeAccessTokenProvider).
The preservedState is set on the DefaultAccessTokenRequest in the Oauth2RestTemplate on line 212 and I determined that the DefaultOauth2ClientContext map was empty and returning null.
I'll be attempting to validate the setPreserveState call in the DefaultOAuth2ClientContext next.
:: UPDATE 3 ::
I updated my client configuration to use Github instead of my own Spring OAuth2 authorization server and it works. To me that indicates there may be a problem with my authorization server configuration.
I'll try and do a bit of debugging on my OAuth server to see if I can figure out what's going wrong.
:: UPDATE 4 ::
Success! I was running the OAuth2 authorization and client servers on the same host, but different ports. When I set the context path of the client to something other than the root it all started working.
I suspect this has something to do with JSESSIONID and cookies. Could anyone link me to documentation to explain how this works for future reference?
Thanks!

Creating a Client Application :
The context path has to be explicit if you are running both the client and the auth server on localhost, otherwise the cookie paths clash and the two apps cannot agree on a session identifier.
src : https://spring.io/guides/tutorials/spring-boot-oauth2/#_social_login_authserver

Centinul as you've figured out this happens due to a cookie conflict, unfortunately cookies don't respect the port numbers. And so both Apps interfere with each other since both are setting JSESSIONID.
There are two easy workarounds:
use server.context-path to move each App to different paths, note that you need to do this for both
set the server.session.cookie.name for one App to something different, e.g., APPSESSIONID
I would suggest to put this workaround in a profile that you activate for localhost only.

Related

How to handle custom exceptions thrown by a filter in Spring Security

I am new to Spring Security.
I have a piece of code where I check if an Authorization header is passed in a request and I throw an exception if it's missing.
public class TokenAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
private static final String BEARER = "Bearer";
public TokenAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher) {
super(requiresAuthenticationRequestMatcher);
}
#Override
public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
throws AuthenticationException, IOException, ServletException {
String username = request.getParameter("username");
String authorization = request.getHeader("AUTHORIZATION");
if (!request.getRequestURI().equals(UniversalConstants.LOGIN_PATH)) {
if (authorization == null || authorization.length() == 0 || !authorization.startsWith(BEARER)) {
throw new InvalidCredentialsException("Missing authentication token"); //<-----------------
}
}
String password = request.getParameter("password");
return getAuthenticationManager().authenticate(new UsernamePasswordAuthenticationToken(username, password));
}
I am targeting to handle all exceptions globally so I'm using #ControllerAdvice.
Note: I know that #ControllerAdvice will not work for exceptions thrown outside of Controllers from this and this, so I have also followed the suggestions in these links.
RestAuthenticationEntryPoint.java
#Component("restAuthenticationEntryPoint")
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
public RestAuthenticationEntryPoint() {
System.out.println("RestAuthenticationEntryPoint");
}
#Autowired
#Qualifier("handlerExceptionResolver")
private HandlerExceptionResolver resolver;
#Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
resolver.resolveException(request, response, null, authException);
}
}
This is how I configure the authenticationEntryPoint:
#Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling().authenticationEntryPoint(new RestAuthenticationEntryPoint()).and().cors().and().csrf().disable().exceptionHandling().defaultAuthenticationEntryPointFor(new RestAuthenticationEntryPoint(), PROTECTED_URLS)
.and().authenticationProvider(customAuthenticationProvider())
.addFilterBefore(tokenAuthenticationFilter(), AnonymousAuthenticationFilter.class).authorizeRequests()
.requestMatchers(PROTECTED_URLS).authenticated().and().formLogin().disable().httpBasic().disable();
}
CustomExceptionHandler.java
#ControllerAdvice
public class CustomExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler({InvalidCredentialsException.class, AuthenticationException.class})
public ResponseEntity<ErrorResponse> handleUnauthorizedError(InvalidCredentialsException e, WebRequest request) {
String errorMessage = e.getLocalizedMessage();
ErrorResponse errorResponse = new ErrorResponse(errorMessage, null);
return new ResponseEntity<>(errorResponse, HttpStatus.UNAUTHORIZED);
}
}
InvalidCredentialsException.java
#ResponseStatus(HttpStatus.UNAUTHORIZED)
public class InvalidCredentialsException extends RuntimeException {
public InvalidCredentialsException(String errorMessage) {
super(errorMessage);
}
}
Upon debugging, I've found that the resolver.resolveException(...) in RestAuthenticationEntryPoint and the handleUnauthorizedError(..) in CustomExceptionHandler never get called.
I wish to handle throw new InvalidCredentialsException("Missing authentication token") in an elegant way and show a decent JSON output in the response.
Any help would be appreciated.
Edit: The stack trace
2021-05-20 17:41:29.985 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/public/**']
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user/hello'; against '/public/**'
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/error**']
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user/hello'; against '/error**'
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.986 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2021-05-20 17:41:29.988 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /user/hello' doesn't match 'DELETE /logout'
2021-05-20 17:41:29.988 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.988 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /user/hello?username=user&password=user at position 8 of 12 in additional filter chain; firing Filter: 'TokenAuthenticationFilter'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/public/**']
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user/hello'; against '/public/**'
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:29.989 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.NegatedRequestMatcher : matches = true
2021-05-20 17:41:38.030 DEBUG 24808 --- [nio-8181-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#7fb6b4e0
2021-05-20 17:41:38.030 DEBUG 24808 --- [nio-8181-exec-3] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2021-05-20 17:41:38.030 DEBUG 24808 --- [nio-8181-exec-3] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2021-05-20 17:41:38.033 ERROR 24808 --- [nio-8181-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception
com.spring.fieldSecurity.Exceptions.InvalidCredentialsException: Missing authentication token
at com.spring.fieldSecurity.Service.TokenAuthenticationFilter.attemptAuthentication(TokenAuthenticationFilter.java:44) ~[classes/:na]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
.
. // more error trace here
.
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/public/**']
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/error'; against '/public/**'
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/error**']
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/error'; against '/error**'
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : matched
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.security.web.FilterChainProxy : /error?username=user&password=user has an empty filter list
2021-05-20 17:41:38.034 DEBUG 24808 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : "ERROR" dispatch for GET "/error?username=user&password=user", parameters={masked}
2021-05-20 17:41:38.035 DEBUG 24808 --- [nio-8181-exec-3] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController#error(HttpServletRequest)
2021-05-20 17:41:38.035 DEBUG 24808 --- [nio-8181-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Opening JPA EntityManager in OpenEntityManagerInViewInterceptor
2021-05-20 17:41:38.724 DEBUG 24808 --- [nio-8181-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Using 'application/json', given [application/json] and supported [application/json, application/*+json, application/json, application/*+json]
2021-05-20 17:41:38.724 DEBUG 24808 --- [nio-8181-exec-3] o.s.w.s.m.m.a.HttpEntityMethodProcessor : Writing [{timestamp=Thu May 20 17:41:38 IST 2021, status=500, error=Internal Server Error, message=, path=/us (truncated)...]
2021-05-20 17:41:38.726 DEBUG 24808 --- [nio-8181-exec-3] o.j.s.OpenEntityManagerInViewInterceptor : Closing JPA EntityManager in OpenEntityManagerInViewInterceptor
2021-05-20 17:41:38.727 DEBUG 24808 --- [nio-8181-exec-3] o.s.web.servlet.DispatcherServlet : Exiting from "ERROR" dispatch, status 500
Spring security has a filter which is called the ExceptionTranslationFilter which translates AccessDeniedException and AuthenticationException into responses. This filter catches these thrown exceptions in the spring security filter chain.
So if you want to return a custom exception, you could instead inherit from one of these classes instead of RuntimeException and add a custom message.
I just want to emphasis and it can never be said too many times:
Providing friendly error messages in production applications when it comes to authentication/authorization is in general bad practice from a security standpoint. These types of messages can benefit malicious actors, when trying out things so that they realize what they have done wrong and guide them in their hacking attempts.
Providing friendly messages in test environments may be okey, but make sure that they are disabled in production. In production all failed authentication attempts a recommendation is to return a 401 with no additional information. And in graphical clients, generalized error messages should be displayed for instance "failed to authenticate" with no given specifics.
Also:
Writing custom security as you have done is also in general bad practice. Spring security is battle tested with 100000 of applications running it in production environments. Writing a custom filter to handle token and passwords, is in general not needed. Spring security already has implemented filters to handle security and authentication using standards like BASIC authentication and TOKEN/JWT. If you implement a non standard login, one bug might expose your application to a huge risk.
Username and password authentication in spring
Oauth2 authentication in spring

Spring Boot 2 + Spring Security + Login Form + Session Redis not working

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

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

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

Spring 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

Swagger2 ui not accessbile

I am using Swagger in a Spring boot application,
I somehow can access most of Swagger's endpoints such as /v2/api-docs, /swagger-resources but I can't figure out why /swagger-ui.html is not accessible.
I am using these dependencies:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
here is my Swagger Config class:
#Configuration
#EnableSwagger2
public class SwaggerConfig {
#Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("app.controllers"))
.paths(PathSelectors.any())
.build();
}
}
Here is the interesting part of the log:
2017-12-27 14:12:09.896 DEBUG 10212 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /springfox/swagger-ui.html at position 12 of 13 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-12-27 14:12:09.896 DEBUG 10212 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /springfox/swagger-ui.html at position 13 of 13 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/v2/api-docs'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/configuration/ui'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/swagger-resources'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/configuration/security'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/swagger-ui.html'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/springfox/swagger-ui.html'; against '/webjars/**'
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /springfox/swagger-ui.html' doesn't match 'POST /login
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /springfox/swagger-ui.html; Attributes: [authenticated]
2017-12-27 14:12:09.897 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8f3b828e: Principal: 0001; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#45d0a23, returned: 1
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2017-12-27 14:12:09.903 DEBUG 10212 --- [nio-8080-exec-1] o.s.security.web.FilterChainProxy : /springfox/swagger-ui.html reached end of additional filter chain; proceeding with original chain
2017-12-27 14:12:09.904 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/springfox/swagger-ui.html]
2017-12-27 14:12:09.906 DEBUG 10212 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /springfox/swagger-ui.html
2017-12-27 14:12:09.919 DEBUG 10212 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-12-27 14:12:09.920 DEBUG 10212 --- [nio-8080-exec-1] .w.s.m.a.ResponseStatusExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-12-27 14:12:09.920 DEBUG 10212 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-12-27 14:12:09.920 WARN 10212 --- [nio-8080-exec-1] o.s.web.servlet.PageNotFound : Request method 'GET' not supported
2017-12-27 14:12:09.921 DEBUG 10212 --- [nio-8080-exec-1] w.c.HttpSessionSecurityContextRepository : SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#8f3b828e: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#8f3b828e: Principal: 0001; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_ADMIN, ROLE_USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#3bcccd7c
2017-12-27 14:12:09.921 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2017-12-27 14:12:09.921 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Successfully completed request
2017-12-27 14:12:09.922 DEBUG 10212 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'delegatingApplicationListener'
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] o.s.b.w.f.OrderedRequestContextFilter : Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#203209de
2017-12-27 14:12:09.923 DEBUG 10212 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost] : Processing ErrorPage[errorCode=0, location=/error]
2017-12-27 14:12:09.928 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/error]
2017-12-27 14:12:09.928 DEBUG 10212 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error
2017-12-27 14:12:09.930 DEBUG 10212 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning handler method [public org.springframework.http.ResponseEntity io.xhub.secusid.exception.SecusidErrorHandler.error(javax.servlet.http.HttpServletRequest)]
2017-12-27 14:12:09.930 DEBUG 10212 --- [nio-8080-exec-1] o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance of singleton bean 'secusidErrorHandler'
2017-12-27 14:12:09.930 DEBUG 10212 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Last-Modified value for [/error] is: -1
2017-12-27 14:12:09.943 DEBUG 10212 --- [nio-8080-exec-1] i.x.s.exception.SecusidErrorHandler : Request method 'GET' not supported
org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
Try adding a class like this
#Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
#Override
public void addResourceHandlers(final ResourceHandlerRegistry registry) {
// Make Swagger meta-data available via <baseURL>/v2/api-docs/
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
// Make Swagger UI available via <baseURL>/swagger-ui.html
registry.addResourceHandler("/**").addResourceLocations("classpath:/META-INF/resources/");
}
}

Resources