Spring Boot Oauth Custom Login Form - spring

I followed the spring tutorial "SSO with OAuth2: Angular JS and Spring Security Part V".
I converted the "authserver"-project from maven to gradle after that the custom login form doesn't work anymore.
Are the wro tasks in the pom.xml needed for the login form to work?
I also tried this tutorial but it didn't work in my scenario either:
http://docs.spring.io/spring-security/site/docs/3.2.x/guides/form.html
I hope that you can help me.
Logfile:
2016-05-18 11:14:53.667 DEBUG 22312 --- [nio-9999-exec-9] o.s.security.web.FilterChainProxy : /login at position 5 of 14 in additional filter chain; firing Filter: 'LogoutFilter'
2016-05-18 11:14:53.667 DEBUG 22312 --- [nio-9999-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login' doesn't match 'POST /logout
2016-05-18 11:14:53.667 DEBUG 22312 --- [nio-9999-exec-9] o.s.security.web.FilterChainProxy : /login at position 6 of 14 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2016-05-18 11:14:53.667 DEBUG 22312 --- [nio-9999-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'GET /login' doesn't match 'POST /login
2016-05-18 11:14:53.667 DEBUG 22312 --- [nio-9999-exec-9] o.s.security.web.FilterChainProxy : /login at position 7 of 14 in additional filter chain; firing Filter: 'DefaultLoginPageGeneratingFilter'
2016-05-18 11:14:53.667 DEBUG 22312 --- [nio-9999-exec-9] w.c.HttpSessionSecurityContextRepository : SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
Code in the OAuth2ServerConfiguration:
#Override
public void configure(HttpSecurity http) throws Exception {
http.formLogin().loginPage("/login").permitAll()
.and().requestMatchers()
.antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access")
.and().authorizeRequests()
.anyRequest().authenticated();
}
MainAuthserverApplication.java:
#ComponentScan
#SessionAttributes("authorizationRequest")
#EnableAutoConfiguration()
#EnableConfigurationProperties({AuthProperties.class})
public class MainAuthserverApplication extends WebMvcConfigurerAdapter {
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
registry.setOrder(Ordered.HIGHEST_PRECEDENCE);
registry.addViewController("/oauth/confirm_access").setViewName("authorize");
}

I already fixed the problem myself:
It seems that these two methods have to be in the same class:
#Configuration
#Order(-20)
protected static class LoginConfig extends WebSecurityConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.formLogin().loginPage("/login").permitAll().and().requestMatchers()
.antMatchers("/login", "/oauth/authorize", "/oauth/confirm_access").and().authorizeRequests()
.anyRequest().authenticated();
// #formatter:on
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager);
}
}

Related

Filter gets executed even if pattern does not match, Spring Security

The current security configuration I'm using:
#Configuration
public class SecurityConfig {
/**
* Default order of 3 as per Spring documentation.
*/
#Configuration
#EnableWebSecurity
#EnableResourceServer
public static class OAuth2SecurityConfiguration extends ResourceServerConfigurerAdapter {
private final TokenStore tokenStore;
#Autowired
public OAuth2SecurityConfiguration(TokenStore tokenStore) {
this.tokenStore = tokenStore;
}
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.tokenStore(tokenStore);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http.apply(CommonSecurityConfiguration
.commonSecurityConfiguration())
.and()
.authorizeRequests().anyRequest()
.authenticated();
}
}
#Configuration
#Order(1)
public static class SecretAuthSecurityConfiguration extends WebSecurityConfigurerAdapter {
private JPAAuthenticationProvider authenticationProvider;
#Autowired
public void setAuthenticationProvider(JPAAuthenticationProvider authenticationProvider) {
this.authenticationProvider = authenticationProvider;
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) {
auth.authenticationProvider(authenticationProvider);
}
#Bean
public FilterRegistrationBean<Filter> secretFilterRegistrationBean() {
var filterRegistrationBean =
new FilterRegistrationBean<>();
filterRegistrationBean.setFilter(
new SecretFilter();
return filterRegistrationBean;
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.requestMatchers()
.antMatchers("/resource1/api/**", "/resource2/api/**")
.and()
.addFilterAfter(this.secretFilterRegistrationBean().getFilter(),
LogoutFilter.class)
.apply(CommonSecurityConfiguration
.commonSecurityConfiguration());
}
}
public static class CommonSecurityConfiguration
extends AbstractHttpConfigurer<CommonSecurityConfiguration, HttpSecurity> {
#Override
public void init(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable();
}
public static CommonSecurityConfiguration commonSecurityConfiguration() {
return new CommonSecurityConfiguration();
}
}
}
I'm pretty new to Spring Security and my goal is to build an application that allows different types of authentications for different paths within my application.
As far as I understood from articles and Spring documentation, you have a lot of flexibility in managing your filter chains, using ANT matchers and things alike.
In the code snippet above I tried to configure 2 filter chains - each one corresponds to a type of authentication:
OAuth2, token-based security configuration - described in the static class OAuth2SecurityConfiguration - where I used the annotation #EnableResourceServer, which automatically adds the org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter to a new filter chain. As per Spring documentation about #EnableResourceServer:
The annotation creates a WebSecurityConfigurerAdapter with a hard-coded Order (of 3).
A custom authentication type, which is based on a custom filter. What this filter does? It checks a header from the incoming request and it verifies if there is a trusted secret within that header, nothing too special. Here is the core of the filter:
public class SecretFilter extends OncePerRequestFilter {
#Override
protected void doFilterInternal(HttpServletRequest httpServletRequest,
HttpServletResponse httpServletResponse,
FilterChain filterChain)
throws IOException, ServletException {
log.info("Inside SecretFilter.");
String secret = this.resolveSecret(httpServletRequest);
if (secret.isValid()) {
SecurityContextHolder.getContext().setAuthentication(
new UsernamePasswordAuthenticationToken(null, null, null));
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
/**
* Clearing the security context after the request is made.
*/
SecurityContextHolder.getContext().setAuthentication(null);
}
The resulted filter chains:
o.s.s.web.DefaultSecurityFilterChain: Creating filter chain:a OrRequestMatcher [requestMatchers=[Ant [pattern='/resource1/api/star.star'], Ant [pattern='/resource2/api/star.star']]]
- WebAsyncManagerIntegrationFilter
- SecurityContextPersistenceFilter
- HeaderWriterFilter
- CorsFilter
- LogoutFilter
- SecretFilter <------- here is my filter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
o.s.s.web.DefaultSecurityFilterChain: Creating filter chain: org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$NotOAuthRequestMatcher
- WebAsyncManagerIntegrationFilter
- SecurityContextPersistenceFilter
- HeaderWriterFilter
- CorsFilter
- LogoutFilter
- OAuth2AuthenticationProcessingFilter
- RequestCacheAwareFilter
- SecurityContextHolderAwareRequestFilter
- AnonymousAuthenticationFilter
- SessionManagementFilter
- ExceptionTranslationFilter
- FilterSecurityInterceptor
The static configuration class that should handle this type of authentication have been marked with #Order(1) annotation, because I want requests to pass first through the filter chain with the custom filter, otherwise, if requests are not intended to the specified paths, like /resource1/api/**, then pass through the OAuth filter chain.
When I do a normal request to a path /resource1/api/X for example, everything goes well, and the filter chain gets executed. But when a request on a path other than those specified above comes in, the console shows me this:
2020-09-22 01:00:03.698 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-09-22 01:00:03.698 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-09-22 01:00:03.698 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-09-22 01:00:03.698 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 4 of 12 in additional filter chain; firing Filter: 'CorsFilter'
2020-09-22 01:00:03.703 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2020-09-22 01:00:03.703 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 6 of 12 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
2020-09-22 01:00:03.715 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-09-22 01:00:03.715 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-09-22 01:00:03.715 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-09-22 01:00:03.715 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-09-22 01:00:03.715 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-09-22 01:00:03.716 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-09-22 01:00:03.717 DEBUG 928 --- [nio-8080-exec-4] o.s.security.web.FilterChainProxy : /profile/?date=2020-09-21T22:00:03Z reached end of additional filter chain; proceeding with original chain
2020-09-22 01:00:03.718 INFO 928 --- [nio-8080-exec-4] c.s.p.s.filters.SecretFilter : Inside SecretFilter.
Why the SecretFilter gets executed at the end of the OAuth filter chain? It is not annotated with #Order annotation or anything else. My path should not be matched, so the filter chain that contains the filter should not get fired. It looks all so clear, but it is this little thing that I cannot get.
My intuition says that the filter gets registered and placed somehow with the default Ordered.LOWEST_PRECEDENCE order and it is executed after the FilterChainProxy finishes its job with the current multiplexed chain.
Any help or references to read more about it would be really appreciated.

spring boot oauth2 - cannot obtain access token when use Basic Auth

I have problem to get access token from my spring-boot server v.2.0.3.RELEASE. I use spring-security-oauth v.2.3.3.RELEASE.
When I use postman I can get access token and in log I see that BasicAuthenticateFilter is match. But when use angularjs/react, BasicAuthenticateFilter is ommited and I got 401 without any message.
AuthenticationServer
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {
static final String CLIENT_ID = "client";
static final String CLIENT_SECRET = "$2a$04$AMTwWHtjscVAHH4gPHx04.82v/W80KVJptp0l/QUWrlkiWU7g7wbe";
static final String GRANT_TYPE = "password";
static final String AUTHORIZATION_CODE = "authorization_code";
static final String REFRESH_TOKEN = "refresh_token";
static final String IMPLICIT = "implicit";
static final String SCOPE_READ = "read";
static final String SCOPE_WRITE = "write";
static final String TRUST = "trust";
static int ACCESS_TOKEN_VALIDITY_SECONDS = 2*60*60;
static final int REFRESH_TOKEN_VALIDITY_SECONDS = 6*60*60;
#Autowired
private TokenStore tokenStore;
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients
.inMemory()
.withClient(CLIENT_ID)
.secret(CLIENT_SECRET)
.authorizedGrantTypes(GRANT_TYPE, AUTHORIZATION_CODE, REFRESH_TOKEN, IMPLICIT)
.scopes(SCOPE_READ, SCOPE_WRITE, TRUST)
.accessTokenValiditySeconds(ACCESS_TOKEN_VALIDITY_SECONDS)
.refreshTokenValiditySeconds(REFRESH_TOKEN_VALIDITY_SECONDS);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.authenticationManager(authenticationManager);
}
#Bean
public static PropertySourcesPlaceholderConfigurer properties() {
PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
return propertySourcesPlaceholderConfigurer;
}
}
SecurityConfig
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Resource(name = "userService")
private UserDetailsService userDetailsService;
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService)
.passwordEncoder(encoder());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.antMatchers("/oauth/token").permitAll()
.anyRequest().authenticated();
}
#Bean
public BCryptPasswordEncoder encoder() {
return new BCryptPasswordEncoder();
}
#Bean
public TokenStore tokenStore() {
return new InMemoryTokenStore();
}
#Bean
public FilterRegistrationBean corsFilter() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
config.addAllowedOrigin("*");
config.addAllowedHeader("*");
config.addAllowedMethod("*");
source.registerCorsConfiguration("/**", config);
FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
bean.setOrder(50);
return bean;
}
}
ResourceServer
#Configuration
#EnableResourceServer
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "resource_id";
#Override
public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
resources.resourceId(RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/h2-console/**").permitAll()
.antMatchers("/user/register","/user/login").permitAll()
.antMatchers("/**").authenticated()
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler())
.and().headers().frameOptions().disable();
}
}
angularjs code
angular.module('myApp.view1', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/view1', {
templateUrl: 'view1/view1.html',
controller: 'View1Ctrl'
});
}])
.controller('View1Ctrl', ['$http','$httpParamSerializer', function($http, $httpParamSerializer) {
var ctrl = this;
this.data = {
grant_type:"password",
username: "",
password: "",
client_id: "client"
};
this.encoded = btoa("client:secret");
this.login = function() {
var req = {
method: 'POST',
url: "http://localhost:8080/api/oauth/token",
headers: {
"Authorization": "Basic " + ctrl.encoded,
"Content-type": "application/x-www-form-urlencoded; charset=utf-8"
},
data: $httpParamSerializer(ctrl.data)
}
$http(req).then(function(data){
console.log(data);
$http.defaults.headers.common.Authorization =
'Bearer ' + data.data.access_token;
$cookies.put("access_token", data.data.access_token);
window.location.href="index";
}, function(error) {
console.log(error);
});
}
}]);
This is my log from spring-boot
2018-06-22 19:01:45.134 INFO 23778 --- [nio-8080-exec-3] o.a.c.c.C.[Tomcat].[localhost].[/api] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-06-22 19:01:45.134 INFO 23778 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2018-06-22 19:01:45.143 INFO 23778 --- [nio-8080-exec-3] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 9 ms
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token']
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : matched
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'OPTIONS /oauth/token' doesn't match 'GET /logout
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'OPTIONS /oauth/token' doesn't match 'POST /logout
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'OPTIONS /oauth/token' doesn't match 'PUT /logout
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'OPTIONS /oauth/token' doesn't match 'DELETE /logout
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2018-06-22 19:01:45.144 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#64454d87: 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'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.security.web.FilterChainProxy : /oauth/token at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/oauth/token'; against '/oauth/token'
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2018-06-22 19:01:45.145 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#64454d87: 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
2018-06-22 19:01:45.146 DEBUG 23778 --- [nio-8080-exec-3] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#62efc6af, returned: -1
2018-06-22 19:01:45.153 DEBUG 23778 --- [nio-8080-exec-3] 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
I find out solution for my problem. Main problem was with send OPTIONS request to oauth/token. I change my CorsFilter and SecurityConfig.
SecurityConfig.java
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/oauth/token").permitAll();
}
SimpleCorsFilter.java
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class SimpleCorsFilter implements Filter {
public SimpleCorsFilter() {
}
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with, authorization");
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
#Override
public void init(FilterConfig filterConfig) {
}
#Override
public void destroy() {
}
}
After this changes I got access token

Returning bad credential in oauth2 implemention using spring boot 1.5

As i am trying to create simple login in oauth2 implementation using spring boot. Unfortunately its not working, as i am newbie in spring
My configuration
ApplicationStarter.java
#SpringBootApplication
#EnableAutoConfiguration
public class ApplicationStarter extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(ApplicationStarter.class);
}
public static void main(String[] args) throws Exception {
SpringApplication.run(ApplicationStarter.class, args);
}
}
ResourceServerConfiguration.java
#Configuration
#EnableResourceServer
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
private static final String RESOURCE_ID = "my_rest_api";
#Override
public void configure(ResourceServerSecurityConfigurer resources) {
resources.resourceId(RESOURCE_ID);
}
#Override
public void configure(HttpSecurity http) throws Exception {
System.out.println("Inside ResourceServerConfiguration");
http.
anonymous().disable()
.requestMatchers().antMatchers("/user/**")
.and().authorizeRequests()
.antMatchers("/user/**").access("hasRole('ADMIN')")
.and().exceptionHandling().accessDeniedHandler(new OAuth2AccessDeniedHandler());
}
}
AuthorizationServerConfiguration.java
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
private static String REALM="MY_OAUTH_REALM";
#Autowired
private TokenStore tokenStore;
#Autowired
private UserApprovalHandler userApprovalHandler;
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager authenticationManager;
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
System.out.println("Inside AuthorizationServerConfiguration");
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust")
.secret("secret")
.accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore).userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer.realm(REALM+"/client");
}
}
MethodSecurityConfig.java
#Configuration
#EnableGlobalMethodSecurity(prePostEnabled = true, proxyTargetClass = true)
public class MethodSecurityConfig extends GlobalMethodSecurityConfiguration {
#Autowired
private OAuth2SecurityConfiguration securityConfig;
#Override
protected MethodSecurityExpressionHandler createExpressionHandler() {
return new OAuth2MethodSecurityExpressionHandler();
}
}
OAuth2SecurityConfiguration.java
#Configuration
#ComponentScan
#EnableWebSecurity
public class OAuth2SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private ClientDetailsService clientDetailsService;
#Autowired
public void globalUserDetails(AuthenticationManagerBuilder auth) throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : globalUserDetails()");
auth.inMemoryAuthentication()
.withUser("bill").password("abc123").roles("ADMIN").and()
.withUser("bob").password("abc123").roles("USER");
}
#Override
protected void configure(HttpSecurity http) throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : configure()");
http
.csrf().disable()
.anonymous().disable()
.authorizeRequests()
.antMatchers("/oauth/token").permitAll();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : authenticationManagerBean()");
return super.authenticationManagerBean();
}
#Bean
public TokenStore tokenStore() {
System.out.println("inside OAuth2SecurityConfiguration : tokenStore()");
return new InMemoryTokenStore();
}
#Bean
#Autowired
public TokenStoreUserApprovalHandler userApprovalHandler(TokenStore tokenStore){
System.out.println("inside OAuth2SecurityConfiguration : userApprovalHandler()");
TokenStoreUserApprovalHandler handler = new TokenStoreUserApprovalHandler();
handler.setTokenStore(tokenStore);
handler.setRequestFactory(new DefaultOAuth2RequestFactory(clientDetailsService));
handler.setClientDetailsService(clientDetailsService);
return handler;
}
#Bean
#Autowired
public ApprovalStore approvalStore(TokenStore tokenStore) throws Exception {
System.out.println("inside OAuth2SecurityConfiguration : approvalStore()");
TokenApprovalStore store = new TokenApprovalStore();
store.setTokenStore(tokenStore);
return store;
}
}
Please do correct me where i am went wrong? whether any more configuration needed or not?
as i followed
http://websystique.com/spring-security/secure-spring-rest-api-using-oauth2/
as reference.
spring boot log
2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.b.w.f.OrderedRequestContextFilter : Bound request context to
thread: org.apache.catalina.connector.RequestFacade#1f2fcd1 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/css/'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '/css/' 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/js/'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '/js/' 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/images/'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '/images/' 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/webjars/'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '/webjars/' 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='//favicon.ico'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '//favicon.ico'
2017-10-26 11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/error'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '/error' 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : No matches found 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/'] 2017-10-26 11:15:07.851 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Request
'/oauth/token' matched by universal pattern '/' 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : matched 2017-10-26
11:15:07.851 DEBUG 21456 --- [nio-8080-exec-5]
o.s.security.web.FilterChainProxy :
/oauth/token?grant_type=password&username=bill&password=abc123 at
position 1 of 11 in additional filter chain; firing Filter:
'WebAsyncManagerIntegrationFilter' 2017-10-26 11:15:07.851 DEBUG 21456
--- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : /oauth/token?grant_type=password&username=bill&password=abc123 at
position 2 of 11 in additional filter chain; firing Filter:
'SecurityContextPersistenceFilter' 2017-10-26 11:15:07.852 DEBUG 21456
--- [nio-8080-exec-5] o.s.security.web.FilterChainProxy : /oauth/token?grant_type=password&username=bill&password=abc123 at
position 3 of 11 in additional filter chain; firing Filter:
'HeaderWriterFilter' 2017-10-26 11:15:07.852 DEBUG 21456 ---
[nio-8080-exec-5] o.s.security.web.FilterChainProxy :
/oauth/token?grant_type=password&username=bill&password=abc123 at
position 4 of 11 in additional filter chain; firing Filter:
'LogoutFilter' 2017-10-26 11:15:07.852 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.web.util.matcher.OrRequestMatcher : Trying to
match using Ant [pattern='/logout', GET] 2017-10-26 11:15:07.852 DEBUG
21456 --- [nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher :
Request 'POST /oauth/token' doesn't match 'GET /logout 2017-10-26
11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', POST] 2017-10-26 11:15:07.852 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/oauth/token'; against '/logout' 2017-10-26
11:15:07.852 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', PUT] 2017-10-26 11:15:07.869 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Request
'POST /oauth/token' doesn't match 'PUT /logout 2017-10-26 11:15:07.869
DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', DELETE] 2017-10-26 11:15:07.869 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.u.matcher.AntPathRequestMatcher : Request
'POST /oauth/token' doesn't match 'DELETE /logout 2017-10-26
11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.web.util.matcher.OrRequestMatcher : No matches found 2017-10-26
11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5]
o.s.security.web.FilterChainProxy :
/oauth/token?grant_type=password&username=bill&password=abc123 at
position 5 of 11 in additional filter chain; firing Filter:
'BasicAuthenticationFilter' 2017-10-26 11:15:07.869 DEBUG 21456 ---
[nio-8080-exec-5] o.s.s.w.a.www.BasicAuthenticationFilter : Basic
Authentication Authorization header found for user 'my-trusted-client'
2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.authentication.ProviderManager : Authentication attempt
using
org.springframework.security.authentication.dao.DaoAuthenticationProvider
2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.a.dao.DaoAuthenticationProvider : User 'my-trusted-client'
not found 2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5]
o.s.s.w.a.www.BasicAuthenticationFilter : Authentication request for
failed:
org.springframework.security.authentication.BadCredentialsException:
Bad credentials 2017-10-26 11:15:07.869 DEBUG 21456 ---
[nio-8080-exec-5] 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#1ff799
2017-10-26 11:15:07.869 DEBUG 21456 --- [nio-8080-exec-5]
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now
cleared, as request processing completed 2017-10-26 11:15:07.869 DEBUG
21456 --- [nio-8080-exec-5] o.s.b.w.f.OrderedRequestContextFilter :
Cleared thread-bound request context:
org.apache.catalina.connector.RequestFacade#1f2fcd1 2017-10-26
11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5]
o.s.web.servlet.DispatcherServlet : DispatcherServlet with name
'dispatcherServlet' processing POST request for [/auth/error]
2017-10-26 11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5]
s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method
for path /error 2017-10-26 11:15:07.870 DEBUG 21456 ---
[nio-8080-exec-5] s.w.s.m.m.a.RequestMappingHandlerMapping : Returning
handler method [public
org.springframework.http.ResponseEntity>
org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)]
2017-10-26 11:15:07.870 DEBUG 21456 --- [nio-8080-exec-5]
o.s.b.f.s.DefaultListableBeanFactory : Returning cached instance
of singleton bean 'basicErrorController' 2017-10-26 11:15:07.874 DEBUG
21456 --- [nio-8080-exec-5] o.s.w.s.m.m.a.HttpEntityMethodProcessor :
Written [{timestamp=Thu Oct 26 11:15:07 IST 2017, status=401,
error=Unauthorized, message=Bad credentials, path=/auth/oauth/token}]
as "application/json" using
[org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#32886a]
2017-10-26 11:15:07.874 DEBUG 21456 --- [nio-8080-exec-5]
o.s.web.servlet.DispatcherServlet : Null ModelAndView returned
to DispatcherServlet with name 'dispatcherServlet': assuming
HandlerAdapter completed request handling 2017-10-26 11:15:07.874
DEBUG 21456 --- [nio-8080-exec-5] o.s.web.servlet.DispatcherServlet
: Successfully completed request
gradle.build
> /* * This build file was generated by the Gradle 'init' task. * *
> This generated file contains a sample Java Library project to get you
> started. * For more details take a look at the Java Libraries chapter
> in the Gradle * user guide available at
> https://docs.gradle.org/3.5/userguide/java_library_plugin.html */
> buildscript {
> ext { springBootVersion = '1.5.7.RELEASE' }
> repositories { mavenCentral() }
> dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
> } } // Apply the java-library plugin to add support for Java Library
> apply plugin: 'java' apply plugin: 'eclipse' apply plugin:
> 'org.springframework.boot' apply plugin: 'war'
>
>
> sourceCompatibility = 1.8 // In this section you declare where to find
> the dependencies of your project repositories {
> // Use jcenter for resolving your dependencies.
> // You can declare any Maven/Ivy/file repository here. // jcenter() mavenCentral() }
>
> dependencies {
> // This dependency is exported to consumers, that is to say found on their compile classpath.
> //api 'org.apache.commons:commons-math3:3.6.1'
> //providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat:1.5.2.RELEASE'
> // This dependency is used internally, and not exposed to consumers on their own compile classpath.
> implementation 'com.google.guava:guava:21.0'
>
> // Use JUnit test framework
> testImplementation 'junit:junit:4.12'
>
>
> // compile("org.springframework.boot:spring-boot-starter-security:1.4.1.RELEASE")
> // compile("org.springframework.security.oauth:spring-security-oauth2:2.0.2.RELEASE")
> //
> compile("org.springframework.security:spring-security-config:3.2.0.RELEASE")
> // compile("org.gitlab4j:gitlab4j-api:4.6.0")
> // compile("org.springframework.boot:spring-boot-starter-tomcat:1.5.2.RELEASE")
>
> compile('org.springframework.boot:spring-boot-starter-actuator')
> compile('org.springframework.boot:spring-boot-starter-security')
> compile('org.springframework.security.oauth:spring-security-oauth2')
> compile('org.springframework.security:spring-security-config')
> compile('org.springframework.boot:spring-boot-starter-web')
> providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
>
> testCompile('org.springframework.boot:spring-boot-starter-test') }
Change your authorization server config like that
AuthorizationServerConfiguration.java
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
System.out.println("Inside AuthorizationServerConfiguration");
clients.inMemory()
.withClient("my-trusted-client")
.authorizedGrantTypes("password", "authorization_code", "refresh_token", "implicit")
.authorities("ROLE_CLIENT", "ROLE_TRUSTED_CLIENT")
.scopes("read", "write", "trust").resourceIds("my_rest_api")
.secret("secret")
.accessTokenValiditySeconds(120).//Access token is only valid for 2 minutes.
refreshTokenValiditySeconds(600);//Refresh token is only valid for 10 minutes.
}
Here changes is I put a resourceIds after scope and that resource id will be same as Resources server's RESOURCE_ID.
You declared in ResourceServerConfiguration such like that
private static final String RESOURCE_ID = "my_rest_api";
So putting the string in authorization server can solve your problem I believe.
Thanks.

Spring Boot: Oauth2: Access is denied (user is anonymous); redirecting to authentication entry point

I am trying to use spring boot oauth2 to accomplish stateless authentication and authorisation. However, I am struggling to it working.
Here is my code:
#EnableAutoConfiguration
#ComponentScan
//#EnableEurekaClient
//#EnableZuulProxy
#Configuration
public class AuthServiceApp {
public static void main(String[] args) {
SpringApplication.run(AuthServiceApp.class, args);
}
}
Authorisation Config:
#Configuration
#EnableAuthorizationServer
public class Oauth2ServerConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
private AuthenticationManager auth;
#Autowired
private DataSource dataSource;
#Autowired
private CustomUserDetailsService userDetailService;
#Autowired
private ClientDetailsService clientDetailsService;
#Bean
public JdbcTokenStore tokenStore() {
return new JdbcTokenStore(dataSource);
}
#Bean
protected AuthorizationCodeServices authorizationCodeServices() {
return new JdbcAuthorizationCodeServices(dataSource);
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// #OFF
endpoints
.authorizationCodeServices(authorizationCodeServices())
.authenticationManager(auth)
.userDetailsService(userDetailService)
.tokenStore(tokenStore());
// #ON
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// #OFF
clients.jdbc(dataSource)
.withClient("client")
.secret("secret")
.authorizedGrantTypes("password","refresh_token", "client_credentials")
.authorities("USER")
.scopes("read", "write")
.autoApprove(true)
.accessTokenValiditySeconds(60)
.refreshTokenValiditySeconds(300);
// #ON
}
}
Resource Server Config:
#Configuration
#EnableResourceServer
#EnableGlobalMethodSecurity(prePostEnabled = true)
class ResourceServerConfig extends ResourceServerConfigurerAdapter {
#Autowired
private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
#Autowired
private CustomLogoutSuccessHandler customLogoutSuccessHandler;
#Override
public void configure(HttpSecurity http) throws Exception {
// #OFF
http
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.exceptionHandling()
.authenticationEntryPoint(customAuthenticationEntryPoint)
.and()
.logout()
.logoutUrl("/oauth/logout")
.logoutSuccessHandler(customLogoutSuccessHandler)
.and()
.csrf()
// .requireCsrfProtectionMatcher(new AntPathRequestMatcher("/oauth/authorize"))
.disable()
.headers()
.frameOptions().disable()
.and()
.authorizeRequests()
.antMatchers("/identity/**").authenticated();
// #ON
}
}
#Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {
#Autowired
private CustomUserDetailsService userDetailsService;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService);
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #OFF
http
.csrf()
.disable()
.authorizeRequests()
.antMatchers("/login").permitAll()
.anyRequest().authenticated()
.and()
.formLogin().permitAll();
// #ON
}
}
Controller:
#RestController
#RequestMapping("/")
public class AuthController {
#PreAuthorize("#oauth2.hasScope('read')")
#GetMapping("/user")
public Principal getUser(Principal user) {
return user;
}
}
I can get the access token using POSTMAN. I am using the same access token in the header to get the user details as http://localhost:8082/identity/user before it gets expired. However, I get login page html response with following log on console:
2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 301C6EDD36372CF9C553FCFCD4AA47E3; Granted Authorities: ROLE_ANONYMOUS'
2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.security.web.FilterChainProxy : /user at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.security.web.FilterChainProxy : /user at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.security.web.FilterChainProxy : /user at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/user'; against '/login'
2017-05-24 22:55:16.070 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /user; Attributes: [authenticated]
2017-05-24 22:55:16.071 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 301C6EDD36372CF9C553FCFCD4AA47E3; Granted Authorities: ROLE_ANONYMOUS
2017-05-24 22:55:16.071 DEBUG 16899 --- [nio-8082-exec-9] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#55b4f25d, returned: -1
2017-05-24 22:55:16.071 DEBUG 16899 --- [nio-8082-exec-9] 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
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84) ~[spring-security-core-4.2.2.RELEASE.jar:4.2.2.RELEASE]
But it seems like I have been authenticated when making first call to get the access token to oauth/token:
2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /oauth/token; Attributes: [fullyAuthenticated]
2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#50c8f5e8: Principal: org.springframework.security.core.userdetails.User#af12f3cb: Username: client; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#21a2c: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 2F070B741A55BD1E47933621D9127780; Granted Authorities: USER
2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#61f8721f, returned: 1
2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
2017-05-24 22:54:35.966 DEBUG 16899 --- [nio-8082-exec-6] o.s.security.web.FilterChainProxy : /oauth/token reached end of additional filter chain; proceeding with original chain
2017-05-24 22:54:35.967 DEBUG 16899 --- [nio-8082-exec-6] .s.o.p.e.FrameworkEndpointHandlerMapping : Looking up handler method for path /oauth/token
2017-05-24 22:54:35.968 DEBUG 16899 --- [nio-8082-exec-6] .s.o.p.e.FrameworkEndpointHandlerMapping : Returning handler method [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]
2017-05-24 22:54:35.975 DEBUG 16899 --- [nio-8082-exec-6] .o.p.p.ResourceOwnerPasswordTokenGranter : Getting access token for: client
2017-05-24 22:54:35.975 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.authentication.ProviderManager : Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
Hibernate: select user0_.id as id1_1_, user0_.enabled as enabled2_1_, user0_.name as name3_1_, user0_.password as password4_1_, user0_.username as username5_1_ from user user0_ where user0_.username=?
Hibernate: select roles0_.user_id as user_id1_2_0_, roles0_.role_id as role_id2_2_0_, role1_.id as id1_0_1_, role1_.role as role2_0_1_ from user_role roles0_ inner join role role1_ on roles0_.role_id=role1_.id where roles0_.user_id=?
2017-05-24 22:54:36.125 INFO 16899 --- [nio-8082-exec-6] o.s.s.o.p.token.store.JdbcTokenStore : Failed to find access token for token 180c2528-b712-4088-9cce-71e9cc7ccb94
2017-05-24 22:54:36.232 DEBUG 16899 --- [nio-8082-exec-6] o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
2017-05-24 22:54:36.232 DEBUG 16899 --- [nio-8082-exec-6] s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
May be I am configuring something wrong. What am I missing here?
I had a similar issue and found that the OAuth2AuthenticationProcessingFilter was not getting invoked by the filter chain and because of which, user was not getting authenticated and hence treated as anonymous.
Am using Spring-boot 1.5.3 version and I added below line in application.yml to fix the ordering.
security.oauth2.resource.filter-order=3
There must be a log statement present which shows that its getting invoked
DEBUG 34386 --- [nio-8082-exec-1] o.s.security.web.FilterChainProxy : /foo at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
Reference - https://github.com/spring-projects/spring-security-oauth/issues/993
To use
.authorizedGrantTypes("password","refresh_token", "client_credentials")
you need to open access to
/auth/token
in security configuration of your Authorization Server
#Override
protected void configure(HttpSecurity http) throws Exception {
code...
http
.antMatcher("/**")
.authorizeRequests()
.antMatchers("/oauth/token").permitAll()
.anyRequest().authenticated()
code...
}
I was facing the same problem and managed to fix it by explicitly disabling some spring autoconfiguration:
#EnableAutoConfiguration(exclude = [OAuth2AutoConfiguration::class,
SecurityAutoConfiguration::class, SecurityFilterAutoConfiguration::class])
Also check if you are using multiple OAuth2 filters coming from multiple auth-related dependices/libraries.
In my case I was using
<dependency>
<groupId>org.springframework.security.oauth.boot</groupId>
<artifactId>spring-security-oauth2-autoconfigure</artifactId>
<version>2.2.4.RELEASE</version>
</dependency>
Along with another custom OAuth2 library used in my organization, which caused the spring library to attempt to authenticate before the custom (correct) one, and with no credentials fed to it of course throwing this exact exception.
My service calls worked once I removed the Spring OAuth2 dependency.

Spring OAuth: Custom form for authenticating authorization endpoint

How can I set up a custom login form to protect my /oauth/authorize endpoint in an Spring Boot Application that is both a Authorization and Resource Server? I want to achieve that a user has to log in to make requests to /oauth/authorize. All resources, that are not /login and /oauth/** should be handled as secured resources protected by OAuth (requiring a valid access token)
So when a user calls localhost:1234/oauth/authorize?client_id=client&response_type=token&redirect_uri=http://localhost:5678 he is first redirected to the login form and after successfully loggin in redirect to the /oauth/authorize endpoint where the implicit OAuth flow proceeds.
When I try the following it works, using the standard basic authentication popup window
#Configuration
#EnableAuthorizationServer
public class OAuthConfig extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.authenticationManager(authenticationManager);
}
#Override
public void configure(final ClientDetailsServiceConfigurer clients)
throws Exception {
clients.inMemory()
.withClient("client")
.authorizedGrantTypes("implicit", "refresh_token")
.scopes("read");
}
}
The Resource config
#Configuration
#EnableResourceServer
public class ResourceConfiguration
extends ResourceServerConfigurerAdapter
{
#Override
public void configure(final HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests().antMatchers("/login").permitAll().and()
.authorizeRequests().anyRequest().authenticated();
// #formatter:on
}
}
The Web Security config
#Configuration
public class WebSecurityConfiguration
extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/oauth/authorize").authenticated().and()
.authorizeRequests().anyRequest().permitAll().and().httpBasic();
}
}
but as soon as I replace httpBasic() with the following it fails:
#Configuration
public class WebSecurityConfiguration
extends WebSecurityConfigurerAdapter
{
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/oauth/authorize").authenticated().and()
.authorizeRequests().anyRequest().permitAll().and().formLogin().loginPage("/login").and().csrf()
.disable();
}
}
and my POST from the login Page is not redirected, it always just returns to /login
The output from the console is as following
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/css/**'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/js/**'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/images/**'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/**/favicon.ico'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/error'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/oauth/token'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/token_key']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/oauth/token_key'
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/oauth/check_token']
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/oauth/check_token'
o.s.s.web.util.matcher.OrRequestMatcher : No matches found
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfiguration$NotOAuthRequestMatcher#5fe3eb5f
o.s.s.web.util.matcher.OrRequestMatcher : matched
o.s.security.web.FilterChainProxy : /login at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
o.s.security.web.FilterChainProxy : /login at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
o.s.security.web.FilterChainProxy : /login at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
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#51c78264
o.s.security.web.FilterChainProxy : /login at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/logout'
o.s.security.web.FilterChainProxy : /login at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
o.s.s.o.p.a.BearerTokenExtractor : Token not found in headers. Trying request parameters.
o.s.s.o.p.a.BearerTokenExtractor : Token not found in request parameters. Not an OAuth2 request.
p.a.OAuth2AuthenticationProcessingFilter : No token in request, will continue chain.
o.s.security.web.FilterChainProxy : /login at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
o.s.security.web.FilterChainProxy : /login at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
o.s.security.web.FilterChainProxy : /login at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#90541710: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: BDCE2D7EA7252AEA2506633726B8BA19; Granted Authorities: ROLE_ANONYMOUS'
o.s.security.web.FilterChainProxy : /login at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
o.s.security.web.FilterChainProxy : /login at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
o.s.security.web.FilterChainProxy : /login at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/login'; against '/login'
o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /login; Attributes: [#oauth2.throwOnError(permitAll)]
o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#90541710: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#166c8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: BDCE2D7EA7252AEA2506633726B8BA19; Granted Authorities: ROLE_ANONYMOUS
o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#bba9bfc, returned: 1
o.s.s.w.a.i.FilterSecurityInterceptor : Authorization successful
o.s.s.w.a.i.FilterSecurityInterceptor : RunAsManager did not change Authentication object
o.s.security.web.FilterChainProxy : /login reached end of additional filter chain; proceeding with original chain
o.s.s.w.a.ExceptionTranslationFilter : Chain processed normally
s.s.w.c.SecurityContextPersistenceFilter : SecurityContextHolder now cleared, as request processing completed
Adding an #Order(-10) to the WebSecurityConfig resolves the issue. I think this annoation ensures that the WebSecurityConfig is used before the ResourceConfig. My final configuration looks like this:
#Configuration
#Order(-10)
public class WebSecurityConfig
extends WebSecurityConfigurerAdapter
{
#Autowired
private AuthenticationManager authenticationManager;
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.parentAuthenticationManager(authenticationManager);
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http.authorizeRequests().antMatchers("/oauth/authorize").authenticated()
.and()
.authorizeRequests().anyRequest().permitAll()
.and()
.formLogin().loginPage("/login").permitAll()
.and()
.csrf().disable();
// #formatter:on
}
}

Resources