Spring OAuth2 Full authentication is required to access this resource - spring

Before we get started, I have looked at many of the posts regarding this topic, but none of the posts seemed to have anything that could help.
I am trying to configure my Spring Rest API to use OAuth Password Grant authentication.
Here is my current security config. currently i have no limitations on which endpoints are permitAll() or authenticated, but I had it setup previously to permit non authenticated access to /oauth/** but still had the same issue. After reading documentation, this seems like a bad thing to do because the /oauth/token endpoint should be protected with http basic authentication where the username/password are the client ID and client secret. I also tried to have it setup to have anyRequest().authenticated() and got the same issue as I am having.
#Configuration
#EnableWebSecurity
#ComponentScan({ "com.mergg.webapp.security", "com.mergg.common.web" })
#EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private IUserService userService;
#Override
public void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
PasswordEncoder encoder = new BCryptPasswordEncoder();
return encoder;
}
}
Here is my current setup for AuthorizationServerConfig. Please note that I have tried to create an in memory client where the secret was passwordEncoder.encode("secret"). Same problem occurred. Not sure which is best practice to use, but thats a topic for another time.
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private DataSource dataSource;
#Autowired
private BCryptPasswordEncoder passwordEncoder;
public AuthorizationServerConfiguration() {
super();
}
#Bean
public TokenStore tokenStore() {
// return new JdbcTokenStore(dataSource);
return new InMemoryTokenStore();
}
// config
#Override
public void configure(final AuthorizationServerSecurityConfigurer oauthServer) {
oauthServer.passwordEncoder(this.passwordEncoder)
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(final ClientDetailsServiceConfigurer clients) throws Exception {
// clients.jdbc(dataSource)
// .passwordEncoder(passwordEncoder)
// .withClient("mergg_mobile")
// .secret(passwordEncoder.encode("secret"))
// .authorizedGrantTypes("password");
clients.inMemory()
.withClient("test")
.secret("secret")
.authorizedGrantTypes("password", "refresh_token")
.accessTokenValiditySeconds(3600);
}
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
endpoints.tokenStore(tokenStore())
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
}
Here is my ResourceServerConfiguration. I have played around with the http security element the same way that i did with the one in my security configuration. I also toyed with a stateless vs if needed session creation policy. No luck.
#Configuration
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
//#formatter:off
http
.authorizeRequests()
.antMatchers("/roles/**").hasRole("INTERNAL")
.antMatchers("/priveleges/**").hasRole("INTERNAL")
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
//#formatter:on
}
}
Here are a few examples of requests I have made (with curl and postman):
curl -u test:secret -X POST localhost:5000/oauth/token\?grant_type=password\&username=test\&password=password
curl -u test:password -X POST localhost:5000/oauth/token\?grant_type=password\&username=test\&password=password
curl -X POST -vu test:secret http://localhost:5000/oauth/token -H "Accept: application/json" -d "password=password&username=test&grant_type=password&client_secret=secret&client_id=test"
curl -X POST -vu test:password http://localhost:5000/oauth/token -H "Accept: application/json" -d "password=password&username=test&grant_type=password&client_secret=secret&client_id=test"
Note that the oauth client id is test and its secret is secret. One user is test with password password
Here is the console output when I try to request a token:
23:07:36.571 [http-nio-5000-exec-2] INFO o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring DispatcherServlet 'dispatcherServlet'
23:07:36.625 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
23:07:36.627 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
23:07:36.627 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
23:07:36.629 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
23:07:36.629 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', GET]
23:07:36.630 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'POST /oauth/token' doesn't match 'GET /logout'
23:07:36.630 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', POST]
23:07:36.630 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/logout'
23:07:36.630 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', PUT]
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'POST /oauth/token' doesn't match 'PUT /logout'
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', DELETE]
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'POST /oauth/token' doesn't match 'DELETE /logout'
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 5 of 11 in additional filter chain; firing Filter: 'OAuth2AuthenticationProcessingFilter'
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.o.p.a.BearerTokenExtractor - Token not found in headers. Trying request parameters.
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.o.p.a.BearerTokenExtractor - Token not found in request parameters. Not an OAuth2 request.
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.s.o.p.a.OAuth2AuthenticationProcessingFilter - No token in request, will continue chain.
23:07:36.631 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
23:07:36.633 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
23:07:36.635 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
23:07:36.637 [http-nio-5000-exec-2] DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#ad1846c9: 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'
23:07:36.637 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
23:07:36.637 [http-nio-5000-exec-2] DEBUG o.s.s.w.s.SessionManagementFilter - Requested session ID 61EE2368B212EC609873DFB621D5166A is invalid.
23:07:36.637 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
23:07:36.637 [http-nio-5000-exec-2] DEBUG o.s.security.web.FilterChainProxy - /oauth/token?password=password&username=test&grant_type=token at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
23:07:36.638 [http-nio-5000-exec-2] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /oauth/token?password=password&username=test&grant_type=token; Attributes: [#oauth2.throwOnError(authenticated)]
23:07:36.638 [http-nio-5000-exec-2] DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#ad1846c9: 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
23:07:36.645 [http-nio-5000-exec-2] DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#73ac552e, returned: -1
23:07:36.652 [http-nio-5000-exec-2] DEBUG 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)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationProcessingFilter.doFilter(OAuth2AuthenticationProcessingFilter.java:176)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:270)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at com.mergg.webapp.security.SimpleCorsFilter.doFilter(SimpleCorsFilter.java:40)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1135)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:635)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:844)
23:07:36.660 [http-nio-5000-exec-2] DEBUG o.s.s.w.a.ExceptionTranslationFilter - Calling Authentication entry point.
23:07:36.712 [http-nio-5000-exec-2] DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#5bf2a0a6
23:07:36.716 [http-nio-5000-exec-2] DEBUG o.s.s.o.p.e.DefaultOAuth2ExceptionRenderer - Written [error="unauthorized", error_description="Full authentication is required to access this resource"] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter#3b1af7db]
23:07:36.716 [http-nio-5000-exec-2] DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
Here is the response I get in postman:
{
"error": "unauthorized",
"error_description": "Full authentication is required to access this resource"
}

Related

(Spring SAML) - Authentication null (following a successfull login on the IDP)

I am trying to integrate the SAML authentication process into a JSF based application. Basically I am following this great sample project (https://github.com/vdenotaris/spring-boot-security-saml-sample).
web.xml
To accomodate Spring SAML into JSF I have done some changes to web.xml file in the following way:
<listener>
<listener-class>org.apache.webbeans.servlet.WebBeansConfigurationListener</listener-class>
</listener>
[ ... ]
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
[ ... ]
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
<!-- Enable Spring Filter: Spring Security works on the concept of Filters -->
<!-- Declare the Spring filter -->
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>
org.springframework.web.filter.DelegatingFilterProxy
</filter-class>
</filter>
<!-- Defines urls pattern on which the filter is applied -->
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<!-- mandatory to allow the managed bean to forward the request to the filter-->
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
The Problem
I can successfully log into my IDP because I also see that a user is created with the role ROLE_USER among the logs like the following:
SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#45988295: Authentication: org.springframework.security.providers.ExpiringUsernameAuthenticationToken#45988295: Principal: org.springframework.security.core.userdetails.User#475365ab: Username: id_7d4e53c6262ae1c8b824dbc1c1e573d2e9e8d159; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.core.userdetails.User#475365ab: Username: id_7d4e53c6262ae1c8b824dbc1c1e573d2e9e8d159; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Granted Authorities: ROLE_USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#6db3bdf2
But when the moment to redirect to the landing page arrives, I see in the logs something similiar:
SecurityContextHolder now cleared, as request processing completed
and I also noticed this row in the logs (maybe it's a hint of something wrong that I have done with Spring Security?)
Requested session IDRequested session ID ED1A0CF82BDFF1EB103ECC9DCF82BED3 is invalid
and finally when I am going to be redirected to the success page, I can clearly see that the SecurityContextHolder is beign cleared so basically when it arrives at the destination page, there is no more an authenticated user stored in the SecurityContext and that's because I arrive at the destination page with a HTTP Status 403 – Forbidden.
Following is a brief summary of the logs that show the situation:
[ ... Processing the endpoint "/saml/login" ... ]
2020-08-26 09:42:29,625 [http-nio-8091-exec-9] DEBUG org.springframework.security.web.FilterChainProxy - /saml/login?idp=https%3A//idptest.spid.gov.it at position 3 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-08-26 09:42:29,626 [http-nio-8091-exec-9] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession returned null object for SPRING_SECURITY_CONTEXT
2020-08-26 09:42:29,626 [http-nio-8091-exec-9] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: org.apache.catalina.session.StandardSessionFacade#534fe335. A new one will be created.
[ ... ]
2020-08-26 09:42:29,770 [http-nio-8091-exec-9] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
[ ... Processing the endpoint "/saml/SSO" ... ]
2020-08-26 09:42:36,124 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-08-26 09:42:36,124 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.FilterChainProxy - /saml/SSO at position 4 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[ ... ]
2020-08-26 09:42:36,124 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.FilterChainProxy - /saml/SSO at position 1 of 1 in additional filter chain; firing Filter: 'SAMLProcessingFilter'
2020-08-26 09:42:36,124 [http-nio-8091-exec-3] DEBUG org.springframework.security.saml.SAMLProcessingFilter - Request is to process authentication
2020-08-26 09:42:36,223 [http-nio-8091-exec-3] DEBUG org.springframework.security.authentication.ProviderManager - Authentication attempt using it.ifin.rasdm.web.config.CustomSAMLAuthenticationProvider
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.saml.SAMLProcessingFilter - Authentication success. Updating SecurityContextHolder to contain: org.springframework.security.providers.ExpiringUsernameAuthenticationToken#25c6bb32: Principal: org.springframework.security.core.userdetails.User#e71c8265: Username: id_e0bbf9e5b7abe0f472324cdb06e7ffb6dd52233f; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.core.userdetails.User#e71c8265: Username: id_e0bbf9e5b7abe0f472324cdb06e7ffb6dd52233f; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Granted Authorities: ROLE_USER
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler - Using default Url: /dashboard.xhtml
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.DefaultRedirectStrategy - Redirecting to '/DM-WEB/dashboard.xhtml'
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.header.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#6c11f040
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession being created as SecurityContext is non-default
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#25c6bb32: Authentication: org.springframework.security.providers.ExpiringUsernameAuthenticationToken#25c6bb32: Principal: org.springframework.security.core.userdetails.User#e71c8265: Username: id_e0bbf9e5b7abe0f472324cdb06e7ffb6dd52233f; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.core.userdetails.User#e71c8265: Username: id_e0bbf9e5b7abe0f472324cdb06e7ffb6dd52233f; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Granted Authorities: ROLE_USER' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#78325633
2020-08-26 09:42:36,475 [http-nio-8091-exec-3] DEBUG org.springframework.security.web.context.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 1 of 12 in additional filter chain; firing Filter: 'MetadataGeneratorFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 2 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 3 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 4 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 5 of 12 in additional filter chain; firing Filter: 'FilterChainProxy'
[ ... Here I am being redirected to the "dashboard.xhtml" page after successful login ...]
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml has no matching filters
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.savedrequest.HttpSessionRequestCache - saved request doesn't match
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.authentication.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#4b018743: 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'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-08-26 09:42:36,480 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.session.SessionManagementFilter - Requested session ID 71C954116A9C4A6B942532E25469295B is invalid.
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.FilterChainProxy - /dashboard.xhtml at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/javax.faces.resource/**'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/saml/**'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/css/**'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/img/**'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/js/**'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/dashboard.xhtml'; against '/login.xhtml'
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /dashboard.xhtml; Attributes: [authenticated]
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#4b018743: 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
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#32cb62eb, returned: -1
2020-08-26 09:42:36,481 [http-nio-8091-exec-8] DEBUG org.springframework.security.web.access.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-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233) ~[spring-security-core-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:123) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:90) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) ~[spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:118) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:158) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:209) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:209) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:186) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:92) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:77) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) [spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.saml.metadata.MetadataGeneratorFilter.doFilter(MetadataGeneratorFilter.java:87) [spring-security-saml2-core-1.0.10.RELEASE.jar:1.0.10.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178) [spring-security-web-5.3.3.RELEASE.jar:5.3.3.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:358) [spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:271) [spring-web-5.2.8.RELEASE.jar:5.2.8.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.24]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.24]
at it.ifin.common.utils.web.servlet.ResponseHeaderFilter.doFilter(ResponseHeaderFilter.java:70) [utils-0.6.9.1.jar:0.6.9.1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.24]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.24]
at org.apache.catalina.filters.HttpHeaderSecurityFilter.doFilter(HttpHeaderSecurityFilter.java:126) [catalina.jar:9.0.24]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.24]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.24]
at org.apache.logging.log4j.web.Log4jServletFilter.doFilter(Log4jServletFilter.java:71) [log4j-web-2.12.1.jar:2.12.1]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193) [catalina.jar:9.0.24]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166) [catalina.jar:9.0.24]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202) [catalina.jar:9.0.24]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96) [catalina.jar:9.0.24]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:526) [catalina.jar:9.0.24]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139) [catalina.jar:9.0.24]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) [catalina.jar:9.0.24]
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678) [catalina.jar:9.0.24]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74) [catalina.jar:9.0.24]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343) [catalina.jar:9.0.24]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408) [tomcat-coyote.jar:9.0.24]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66) [tomcat-coyote.jar:9.0.24]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860) [tomcat-coyote.jar:9.0.24]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587) [tomcat-coyote.jar:9.0.24]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) [tomcat-coyote.jar:9.0.24]
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) [?:?]
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) [?:?]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) [tomcat-util.jar:9.0.24]
at java.lang.Thread.run(Thread.java:834) [?:?]
My current issue seems something similiar with this one (Spring Saml FilterChainProxy clearing context - null Authentication), but I have already tried out its solution without success.
Any hint (also I am not using Spring Boot)?
Turns out it was correctly working while using Spring Boot and embedded Tomcat, but when I wanted to remove Spring Boot and use the external Tomcat it was giving me this headache because of a cookie setting in the external Tomcat's context.xml file.
Wrong Setting
Originally I had this setting for the sameSite cookies configuration in the previously mentioned file:
<CookieProcessor sameSiteCookies="Strict"/>
This way I was able to login through Spring SAML but at the moment of reaching the relayState in the Web Application it couldn't find the Authentication object in the SecurityContextHolder.
Correct Setting
I changed the sameSiteCookies by setting it the following way:
<CookieProcessor sameSiteCookies="Lax"/>
Now I can correctly do login and logout with Spring SAML without Spring Boot.

Restful LDAP Authentication Service using springboot

I am writing a program that validates the username and password sent over HTTP POST and validate against ldap and sends the response back to the user whether the validation is success or not.
My Websecurity Configurer implementation
package hello;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.password.LdapShaPasswordEncoder;
import org.springframework.boot.autoconfigure.security.SecurityProperties;
#Configuration
#Order(SecurityProperties.IGNORED_ORDER)
public class ApplicationSecurity extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().anyRequest().authenticated();
http.csrf().disable();
}
#SuppressWarnings("deprecation")
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.ldapAuthentication()
.userDnPatterns("uid={0},ou=people")
.groupSearchBase("ou=groups")
.contextSource()
.url("ldap://localhost:8389/dc=springframework,dc=org")
.and()
.passwordCompare()
.passwordEncoder(new LdapShaPasswordEncoder())
.passwordAttribute("userPassword");
}
}
My test-server.ldif
dn: dc=springframework,dc=org
objectclass: top
objectclass: domain
objectclass: extensibleObject
dc: springframework
dn: ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: groups
dn: ou=subgroups,ou=groups,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: subgroups
dn: ou=people,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: people
dn: ou=space cadets,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: space cadets
dn: ou=\"quoted people\",dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: "quoted people"
dn: ou=otherpeople,dc=springframework,dc=org
objectclass: top
objectclass: organizationalUnit
ou: otherpeople
dn: uid=ben,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Ben Alex
sn: Alex
uid: ben
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=
dn: uid=bob,ou=people,dc=springframework,dc=org
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: Bob Hamilton
sn: Hamilton
uid: bob
userPassword: bobspassword
.
.
And I have this defined in my application.properties as well.
spring.ldap.embedded.ldif=classpath:test-server.ldif
I am trying to post the data from the postman and I am getting 403 response for any value.
I cannot figure out why is it giving 403.
Can anyone understand what I am doing wrong. Thanks.
Below is the updated Security logs:
2019-09-03 10:11:56.942 DEBUG 9040 --- [nio-8080-exec-2]
o.s.security.web.FilterChainProxy : /rest/hello at position 1
of 10 in additional filter chain; firing Filter:
'WebAsyncManagerIntegrationFilter' 2019-09-03 10:11:56.944 DEBUG 9040
--- [nio-8080-exec-2] o.s.security.web.FilterChainProxy : /rest/hello at position 2 of 10 in additional filter chain; firing
Filter: 'SecurityContextPersistenceFilter' 2019-09-03 10:11:56.944
DEBUG 9040 --- [nio-8080-exec-2]
w.c.HttpSessionSecurityContextRepository : No HttpSession currently
exists 2019-09-03 10:11:56.945 DEBUG 9040 --- [nio-8080-exec-2]
w.c.HttpSessionSecurityContextRepository : No SecurityContext was
available from the HttpSession: null. A new one will be created.
2019-09-03 10:11:56.947 DEBUG 9040 --- [nio-8080-exec-2]
o.s.security.web.FilterChainProxy : /rest/hello at position 3
of 10 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2019-09-03 10:11:56.948 DEBUG 9040 --- [nio-8080-exec-2]
o.s.security.web.FilterChainProxy : /rest/hello at position 4
of 10 in additional filter chain; firing Filter: 'LogoutFilter'
2019-09-03 10:11:56.948 DEBUG 9040 --- [nio-8080-exec-2]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', GET] 2019-09-03 10:11:56.949 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking
match of request : '/rest/hello'; against '/logout' 2019-09-03
10:11:56.949 DEBUG 9040 --- [nio-8080-exec-2]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', POST] 2019-09-03 10:11:56.949 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request
'GET /rest/hello' doesn't match 'POST /logout' 2019-09-03 10:11:56.949
DEBUG 9040 --- [nio-8080-exec-2]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', PUT] 2019-09-03 10:11:56.950 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request
'GET /rest/hello' doesn't match 'PUT /logout' 2019-09-03 10:11:56.950
DEBUG 9040 --- [nio-8080-exec-2]
o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant
[pattern='/logout', DELETE] 2019-09-03 10:11:56.950 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.u.matcher.AntPathRequestMatcher : Request
'GET /rest/hello' doesn't match 'DELETE /logout' 2019-09-03
10:11:56.950 DEBUG 9040 --- [nio-8080-exec-2]
o.s.s.web.util.matcher.OrRequestMatcher : No matches found 2019-09-03
10:11:56.951 DEBUG 9040 --- [nio-8080-exec-2]
o.s.security.web.FilterChainProxy : /rest/hello at position 5
of 10 in additional filter chain; firing Filter:
'RequestCacheAwareFilter' 2019-09-03 10:11:56.951 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.s.HttpSessionRequestCache : saved
request doesn't match 2019-09-03 10:11:56.951 DEBUG 9040 ---
[nio-8080-exec-2] o.s.security.web.FilterChainProxy :
/rest/hello at position 6 of 10 in additional filter chain; firing
Filter: 'SecurityContextHolderAwareRequestFilter' 2019-09-03
10:11:56.953 DEBUG 9040 --- [nio-8080-exec-2]
o.s.security.web.FilterChainProxy : /rest/hello at position 7
of 10 in additional filter chain; firing Filter:
'AnonymousAuthenticationFilter' 2019-09-03 10:11:56.958 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.a.AnonymousAuthenticationFilter : Populated
SecurityContextHolder with anonymous token:
'org.springframework.security.authentication.AnonymousAuthenticationToken#938ad544:
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-03 10:11:56.958 DEBUG 9040 ---
[nio-8080-exec-2] o.s.security.web.FilterChainProxy :
/rest/hello at position 8 of 10 in additional filter chain; firing
Filter: 'SessionManagementFilter' 2019-09-03 10:11:56.958 DEBUG 9040
--- [nio-8080-exec-2] o.s.s.w.session.SessionManagementFilter : Requested session ID 84F3D9D1165FFEE7008EDB2FA99B0D88 is invalid.
2019-09-03 10:11:56.958 DEBUG 9040 --- [nio-8080-exec-2]
o.s.security.web.FilterChainProxy : /rest/hello at position 9
of 10 in additional filter chain; firing Filter:
'ExceptionTranslationFilter' 2019-09-03 10:11:56.959 DEBUG 9040 ---
[nio-8080-exec-2] o.s.security.web.FilterChainProxy :
/rest/hello at position 10 of 10 in additional filter chain; firing
Filter: 'FilterSecurityInterceptor' 2019-09-03 10:11:56.960 DEBUG 9040
--- [nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /rest/hello; Attributes:
[authenticated] 2019-09-03 10:11:56.960 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.w.a.i.FilterSecurityInterceptor :
Previously Authenticated:
org.springframework.security.authentication.AnonymousAuthenticationToken#938ad544:
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-03 10:11:56.972 DEBUG 9040 ---
[nio-8080-exec-2] o.s.s.access.vote.AffirmativeBased : Voter:
org.springframework.security.web.access.expression.WebExpressionVoter#136951e,
returned: -1 2019-09-03 10:11:56.983 DEBUG 9040 --- [nio-8080-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
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:84)
~[spring-security-core-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:233)
~[spring-security-core-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:124)
~[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:91)
~[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:119)
~[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:137)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:111)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:170)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:116)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:74)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)
[spring-web-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:105)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:56)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:109)
[spring-web-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:334)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:215)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:178)
[spring-security-web-5.1.5.RELEASE.jar!/:5.1.5.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:357)
[spring-web-5.1.8.RELEASE.jar!/:5.1.8.RELEASE]
It's not possible to provide a definite answer without any logs and possibly more code. But I have a few hints:
the sample credentials don't match the sample ldif that you are showing. Maybe there's an error?
it seems like you're using your own entry point. It is not clear how it is supposed to work, but POSTing a JSON body with the credentials to what seems to be the secured application URL does not seem right. It might lead to sending credentials to endpoints that should not receive sensitive information. Maybe you'd be better of using standard authentication mechanisms
password comparison isn't as secure and flexible as using LDAP bind authentication. It only supports limited password hashing algorithms that are no longer considered secure, and in case of salted password, requires to retrieve the password from the LDAP entry. LDAP bind supports any hashing algorithms that the LDAP server supports and the existing password never needs to leave the LDAP server
Maybe addressing these issues already helps with solving the underlying problem. Otherwise add code for the RESTAuthenticationEntryPoint and logs to the question.

Getting 404 after oauth2 authentication success and an anonymous token

I am using oauth2 with springboot 1.5.6.RELEASE and I am using jdbc authentication with oauth2.
I added the property: security.oauth2.resource.filter-order = 3
1- AuthorizationServerConfigurerAdapter:
#Configuration
#EnableAuthorizationServer
public class OAuth2Config extends AuthorizationServerConfigurerAdapter {
#Autowired
#Qualifier("authenticationManagerBean")
#Lazy
private AuthenticationManager authenticationManager;
#Autowired
private Environment env;
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
// endpoints.tokenStore(tokenStore()).authenticationManager(authenticationManager);
endpoints.authenticationManager(authenticationManager);
}
#Bean
public TokenStore tokenStore() {
return new JdbcTokenStore(dataSource());
}
#Override
public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
security.tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
}
#Override
public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
clients.jdbc(dataSource());
}
#Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
}
2- ResourceServerConfigurerAdapter
#EnableResourceServer
public class OAuth2ResourceServer extends ResourceServerConfigurerAdapter {
#Override
public void configure(HttpSecurity http) throws Exception {
http.antMatcher("/ws/**").authorizeRequests().anyRequest().authenticated();
}
}
3- SecurityConfig
#Configuration
#EnableWebSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private UserDetailsService userDetailsService;
#Autowired
private CustomAuthenticationSuccessHandler successHandler;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
http.authorizeRequests()
.antMatchers("/", "/registerCompany", "/registerEmployee", "/jobs", "/returnPassword", "/resetPassword",
"/faces/public/**", "/resources/**", "/template/**", "/faces/fonts/*",
"/faces/javax.faces.resource/**", "/ws/**", "/login", "/oauth/**", "/error")
.permitAll().antMatchers("/admin/**", "/faces/admin/**").hasAuthority("ROLE_ADMIN")
.antMatchers("/employeeProfile", "/employeeMainPage", "/employeeAskJob").hasAuthority("ROLE_EMPLOYEE")
.antMatchers("/companyProfile", "/companyMainPage", "/companyPostJob", "/companySearch",
"/branchProfile")
.hasAnyAuthority("ROLE_COMPANY,ROLE_BRANCH,ROLE_ADMIN").anyRequest().fullyAuthenticated().and()
.formLogin().loginPage("/login").permitAll().successHandler(successHandler).failureUrl("/login?error")
.usernameParameter("username").passwordParameter("password").and().logout().deleteCookies("JSESSIONID")
.logoutUrl("/logout").deleteCookies("remember-me").logoutSuccessUrl("/").permitAll().and().rememberMe();
// http.sessionManagement().invalidSessionUrl("/login?invalidSession");
// cache resources
http.headers().addHeaderWriter(new DelegatingRequestMatcherHeaderWriter(
new AntPathRequestMatcher("/javax.faces.resource/**"), new HeaderWriter() {
#Override
public void writeHeaders(HttpServletRequest request, HttpServletResponse response) {
response.addHeader("Cache-Control", "private, max-age=86400");
}
})).defaultsDisabled();
}
#Override
#Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
}
I am trying to generate a token using postman with a post request to url http://localhost:8082/dawam2/oauth/token?grant_type=password
and I use basic authentication and set the username=myclient_id and password=myclient_secret. So the header (Authorization : Basic Basic bXljbGllbnRfaWQ6bXljbGllbnRfc2VjcmV0) was generated
and I set the header Content-Type: application/x-www-form-urlencoded; charset=utf-8.
The response I am getting instead of a generated token :
!doctype html><html lang="en"><head><title>HTTP Status 404 – Not Found</title><style type="text/css">h1 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:22px;} h2 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:16px;} h3 {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;font-size:14px;} body {font-family:Tahoma,Arial,sans-serif;color:black;background-color:white;} b {font-family:Tahoma,Arial,sans-serif;color:white;background-color:#525D76;} p {font-family:Tahoma,Arial,sans-serif;background:white;color:black;font-size:12px;} a {color:black;} a.name {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 404 – Not Found</h1><hr class="line" /><p><b>Type</b> Status Report</p><p><b>Message</b> Not Found</p><p><b>Description</b> The origin server did not find a current representation for the target resource or is not willing to disclose that one exists.</p><hr class="line" /><h3>Apache Tomcat/9.0.0.M18</h3></body></html>
Here are the debugging info:
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token']
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/oauth/token'
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - matched
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-09-26 15:32:16,833 DEBUG o.s.s.w.h.writers.HstsHeaderWriter - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#1d47c7a
2017-09-26 15:32:16,833 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2017-09-26 15:32:16,833 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', GET]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/logout'
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', POST]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /oauth/token' doesn't match 'POST /logout
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', PUT]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /oauth/token' doesn't match 'PUT /logout
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', DELETE]
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /oauth/token' doesn't match 'DELETE /logout
2017-09-26 15:32:16,834 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
2017-09-26 15:32:16,834 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
2017-09-26 15:32:16,834 DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Basic Authentication Authorization header found for user 'myclient_id'
2017-09-26 15:32:16,834 DEBUG o.s.s.a.ProviderManager - Authentication attempt using org.springframework.security.authentication.dao.DaoAuthenticationProvider
2017-09-26 15:32:16,849 DEBUG o.s.s.w.a.w.BasicAuthenticationFilter - Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#d9cf8114: Principal: org.springframework.security.core.userdetails.User#6a9879e3: Username: myclient_id; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_EMPLOYEE; 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_EMPLOYEE
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#d9cf8114: Principal: org.springframework.security.core.userdetails.User#6a9879e3: Username: myclient_id; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_EMPLOYEE; 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_EMPLOYEE'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.s.CompositeSessionAuthenticationStrategy - Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#15d6aaa
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-09-26 15:32:16,850 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/oauth/token'; against '/oauth/token'
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /oauth/token?grant_type=password; Attributes: [fullyAuthenticated]
2017-09-26 15:32:16,850 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#d9cf8114: Principal: org.springframework.security.core.userdetails.User#6a9879e3: Username: myclient_id; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_EMPLOYEE; 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_EMPLOYEE
2017-09-26 15:32:16,851 DEBUG o.s.s.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#14cb584, returned: 1
2017-09-26 15:32:16,851 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - Authorization successful
2017-09-26 15:32:16,851 DEBUG o.s.s.w.a.i.FilterSecurityInterceptor - RunAsManager did not change Authentication object
2017-09-26 15:32:16,851 DEBUG o.s.security.web.FilterChainProxy - /oauth/token?grant_type=password reached end of additional filter chain; proceeding with original chain
2017-09-26 15:32:16,853 DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
2017-09-26 15:32:16,853 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token']
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/oauth/token'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/token_key']
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/oauth/token_key'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/oauth/check_token']
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/oauth/check_token'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No HttpSession currently exists
2017-09-26 15:32:16,854 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2017-09-26 15:32:16,854 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', GET]
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Checking match of request : '/error'; against '/logout'
2017-09-26 15:32:16,854 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', POST]
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'POST /logout
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', PUT]
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'PUT /logout
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - Trying to match using Ant [pattern='/logout', DELETE]
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'DELETE /logout
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.matcher.OrRequestMatcher - No matches found
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.s.w.u.m.AntPathRequestMatcher - Request 'GET /error' doesn't match 'POST /login
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.s.w.a.AnonymousAuthenticationFilter - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2017-09-26 15:32:16,855 DEBUG o.s.security.web.FilterChainProxy - /error?grant_type=password reached end of additional filter chain; proceeding with original chain
2017-09-26 15:32:16,856 DEBUG o.s.s.w.c.HttpSessionSecurityContextRepository - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2017-09-26 15:32:16,856 DEBUG o.s.s.w.a.ExceptionTranslationFilter - Chain processed normally
2017-09-26 15:32:16,856 DEBUG o.s.s.w.c.SecurityContextPersistenceFilter - SecurityContextHolder now cleared, as request processing completed
How can I fix this issue?
The issue was related to Jersey configuration, it was stealing requests from oauth2, i had to reconfigure it with #ApplicationPath("/ws")
so the configuration now looks like :
#Configuration
#ApplicationPath("/ws")
public class JerseyConfig extends ResourceConfig {
public JerseyConfig() {
register(DawamService.class);
}
}
and my webservice implementation class like :
#Component
#Path("/dawam")
public class DawamService extends DawamServiceBase {
#GET
#Produces({ MediaType.TEXT_HTML })
#Path("/test")
public String getHTML() {
System.out.println("##### Welcome to test webservice #########");
return "Welcome to test webservice";
}
}
I have the same problem and I can fixed it.
In my case the reason was in the following:
My servlet-mapping for dispather servlet in web.xml
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/api/*</url-pattern>
</servlet-mapping>
It means the all http requests for access to your resources should be started with '/api' (ex. /api/user/2 or /api/login) even if #RequestMapping points as '/user/{id}' or /login. When you request a token by oauth2/token URL, spring or other filters handle it, but dispatcherServlet could not find any controller corresponding to your request and we have 404 error.
To resolve this, I just added the one method to endpoints in AuthorizationServerConfiguration class.
#Configuration
#EnableAuthorizationServer
public class AuthorizationServerConfiguration extends AuthorizationServerConfigurerAdapter
...
#Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints.tokenStore(tokenStore)
.prefix("/api") //<---- PREFIX WAS ADDED
.userApprovalHandler(userApprovalHandler)
.authenticationManager(authenticationManager);
}
...
}
I think the
.pathMapping("/oauth/token", "/api/oauth/token")
code instead of .prefix("/api") also can resolve the problem.
It changes request for getting the tokens.
After made change I get the tokens by URL
/api/oauth/token
Of course I can mistake but it works for me. Thanks.

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

Redirecting to login page instead of returning a token

I am implementing OAuth 2 using Spring Security 3.2 and Spring Security OAuth 1.0.5. It worked with an xml-based configuration. Now I try to migrate to java-based configuration and I'm facing the problem that instead of returning a token, it redirected me to login page! Below are the configurations:
SecurityInitializer.java
public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer {
/**
* This class configure spring security
*
* #author tuan.dang
*
*/
#Configuration
#EnableWebMvcSecurity
#Order
public static class SecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private DBAuthenticationProvider dbAuthenticationProvider;
#Autowired
private MyWebAuthenticationDetailsSource myWebAuthenticationDetailsSource;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(dbAuthenticationProvider);
}
#Bean(name = "org.springframework.security.authenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
#Override
public void configure(WebSecurity web) throws Exception {
// #formatter:off
web.ignoring()
.antMatchers("/oauth/cache_approvals")
.antMatchers("/oauth/uncache_approvals");
// #formatter:on
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.loginProcessingUrl("/login-processing-url")
.usernameParameter("j_username")
.passwordParameter("j_password")
.authenticationDetailsSource(myWebAuthenticationDetailsSource)
.defaultSuccessUrl("/welcome")
.permitAll()
.and()
.logout()
.invalidateHttpSession(true)
.deleteCookies()
.logoutRequestMatcher(new AntPathRequestMatcher("/logout", RequestMethod.GET.name()))
.logoutSuccessUrl("/login")
.permitAll();
// #formatter:on
}
}
/**
*
* #author tuan.dang
*
*/
#Configuration
#EnableWebMvcSecurity
#Order(10)
public static class AuthorizeServer extends WebSecurityConfigurerAdapter {
#Autowired
ClientDetailsService clientDetails;
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(new ClientDetailsUserDetailsService(clientDetails));
}
#Override
protected void configure(HttpSecurity http) throws Exception {
// #formatter:off
http
.requestMatchers()
.antMatchers("/oauth/token")
.and()
.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/oauth/token").authenticated()
.and()
.anonymous().disable()
.httpBasic()
.authenticationEntryPoint(getClientAuthenticationEntryPoint())
.and()
.addFilterAfter(getClientCredentialsTokenEndpointFilter(), BasicAuthenticationFilter.class)
.addFilterBefore(new RequestContextFilter(), BasicAuthenticationFilter.class)
.exceptionHandling()
.accessDeniedHandler(new OAuth2AccessDeniedHandler());
// #formatter:on
}
#Bean(name = "clientAuthenticationManager")
#Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
private Filter getClientCredentialsTokenEndpointFilter() throws Exception {
AbstractAuthenticationProcessingFilter filter = new ClientCredentialsTokenEndpointFilter();
filter.setAuthenticationManager(authenticationManagerBean());
return filter;
}
private AuthenticationEntryPoint getClientAuthenticationEntryPoint() {
OAuth2AuthenticationEntryPoint entryPoint = new OAuth2AuthenticationEntryPoint();
entryPoint.setTypeName("Basic");
entryPoint.setRealmName("AuthorizationServer");
return entryPoint;
}
}
}
WebInitializer.java
public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
#Override
protected Class<?>[] getRootConfigClasses() {
return new Class[] { AppConfig.class };
}
#Override
protected Class<?>[] getServletConfigClasses() {
return new Class[] { WebAppConfig.class };
}
#Override
protected String[] getServletMappings() {
return new String[] { "/" };
}
/**
* This class replaces dispatcher-servlet.xml file
*
* #author tuan.dang
*
*/
#Configuration
#EnableWebMvc
#ImportResource("classpath:oauth2/oauth2-config.xml")
#ComponentScan(basePackages = { "net.dntuan.training.spring" })
public static class WebAppConfig extends WebMvcConfigurerAdapter {
/**
* Configure an internalResouceViewResolver. This resolver is required to use Spring MVC with jsp view
*
* #return InternalResourceViewResolver
*/
#Bean
public InternalResourceViewResolver configureInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/jsp/");
resolver.setSuffix(".jsp");
return resolver;
}
#Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
configurer.enable();
}
}
}
I tried to turn up logging, I got the following:
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/oauth/token'; against '/oauth/token' (AntPathRequestMatcher.java:145)
[DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Secure object: FilterInvocation: URL: /oauth/token?client_id=epos-frontend&grant_type=password&username=user&password=bypass&app_id=3; Attributes: [authenticated] (AbstractSecurityInterceptor.java:194)
[DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fea1daa6: Principal: org.springframework.security.core.userdetails.User#89854e50: Username: epos-frontend; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_APP_CLIENT; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_APP_CLIENT (AbstractSecurityInterceptor.java:310)
[DEBUG] [org.springframework.security.access.vote.AffirmativeBased] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#2868d4f8, returned: 1 (AffirmativeBased.java:65)
[DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Authorization successful (AbstractSecurityInterceptor.java:215)
[DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - RunAsManager did not change Authentication object (AbstractSecurityInterceptor.java:227)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - /oauth/token?client_id=epos-frontend&grant_type=password&username=user&password=bypass&app_id=3 reached end of additional filter chain; proceeding with original chain (FilterChainProxy.java:323)
[DEBUG] [org.springframework.web.servlet.DispatcherServlet] - DispatcherServlet with name 'dispatcher' processing GET request for [/javabased-oauth2/oauth/token] (DispatcherServlet.java:843)
[DEBUG] [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Looking up handler method for path /oauth/token (AbstractHandlerMethodMapping.java:222)
[DEBUG] [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping] - Returning handler method [public org.springframework.http.ResponseEntity<org.springframework.security.oauth2.common.OAuth2AccessToken> org.springframework.security.oauth2.provider.endpoint.TokenEndpoint.getAccessToken(java.security.Principal,java.lang.String,java.util.Map<java.lang.String, java.lang.String>)] (AbstractHandlerMethodMapping.java:229)
[DEBUG] [org.springframework.beans.factory.support.DefaultListableBeanFactory] - Returning cached instance of singleton bean 'oauth2TokenEndpoint' (AbstractBeanFactory.java:249)
[DEBUG] [org.springframework.web.servlet.DispatcherServlet] - Last-Modified value for [/javabased-oauth2/oauth/token] is: -1 (DispatcherServlet.java:932)
[DEBUG] [org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter] - Getting access token for: epos-frontend (AbstractTokenGranter.java:59)
[DEBUG] [org.springframework.security.authentication.ProviderManager] - Authentication attempt using net.dntuan.training.spring.security.DBAuthenticationProvider (ProviderManager.java:152)
[DEBUG] [net.dntuan.training.spring.security.DBAuthenticationProvider] - entered username: user (DBAuthenticationProvider.java:40)
[DEBUG] [net.dntuan.training.spring.security.DBAuthenticationProvider] - entered password: bypass (DBAuthenticationProvider.java:41)
[DEBUG] [net.dntuan.training.spring.security.DBAuthenticationProvider] - appId: 3 (DBAuthenticationProvider.java:42)
[DEBUG] [org.springframework.web.servlet.mvc.method.annotation.HttpEntityMethodProcessor] - Written [409d7529-2f54-4ec0-8439-3f2730e89e3c] as "application/json;charset=UTF-8" using [org.springframework.http.converter.json.MappingJacksonHttpMessageConverter#510b6523] (AbstractMessageConverterMethodProcessor.java:150)
[DEBUG] [org.springframework.web.servlet.DispatcherServlet] - Null ModelAndView returned to DispatcherServlet with name 'dispatcher': assuming HandlerAdapter completed request handling (DispatcherServlet.java:1019)
[DEBUG] [org.springframework.web.servlet.DispatcherServlet] - Successfully completed request (FrameworkServlet.java:961)
[DEBUG] [org.springframework.security.web.access.ExceptionTranslationFilter] - Chain processed normally (ExceptionTranslationFilter.java:115)
[DEBUG] [org.springframework.web.filter.RequestContextFilter] - Cleared thread-bound request context: FirewalledRequest[ org.apache.catalina.connector.RequestFacade#14738593] (RequestContextFilter.java:104)
[DEBUG] [org.springframework.security.web.context.SecurityContextPersistenceFilter] - SecurityContextHolder now cleared, as request processing completed (SecurityContextPersistenceFilter.java:97)
<!-- continue with new filter chain -->
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/oauth/cache_approvals' (AntPathRequestMatcher.java:145)
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/oauth/uncache_approvals' (AntPathRequestMatcher.java:145)
[DEBUG] [org.springframework.security.web.util.matcher.OrRequestMatcher] - Trying to match using Ant [pattern='/oauth/token'] (OrRequestMatcher.java:65)
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/oauth/token' (AntPathRequestMatcher.java:145)
[DEBUG] [org.springframework.security.web.util.matcher.OrRequestMatcher] - No matches found (OrRequestMatcher.java:72)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No HttpSession currently exists (HttpSessionSecurityContextRepository.java:136)
[DEBUG] [org.springframework.security.web.context.HttpSessionSecurityContextRepository] - No SecurityContext was available from the HttpSession: null. A new one will be created. (HttpSessionSecurityContextRepository.java:90)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.header.writers.HstsHeaderWriter] - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#5688e4ae (HstsHeaderWriter.java:129)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/logout' (AntPathRequestMatcher.java:145)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Request 'GET /' doesn't match 'POST /login-processing-url (AntPathRequestMatcher.java:127)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.authentication.AnonymousAuthenticationFilter] - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS' (AnonymousAuthenticationFilter.java:102)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.FilterChainProxy] - / at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor' (FilterChainProxy.java:337)
[DEBUG] [org.springframework.security.web.util.matcher.AntPathRequestMatcher] - Checking match of request : '/'; against '/logout' (AntPathRequestMatcher.java:145)
[DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Secure object: FilterInvocation: URL: /; Attributes: [authenticated] (AbstractSecurityInterceptor.java:194)
[DEBUG] [org.springframework.security.web.access.intercept.FilterSecurityInterceptor] - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055e4a6: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS (AbstractSecurityInterceptor.java:310)
[DEBUG] [org.springframework.security.access.vote.AffirmativeBased] - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#f84a51b, returned: -1 (AffirmativeBased.java:65)
[DEBUG] [org.springframework.security.web.access.ExceptionTranslationFilter] - Access is denied (user is anonymous); redirecting to authentication entry point (ExceptionTranslationFilter.java:165)
org.springframework.security.access.AccessDeniedException: Access is denied
at org.springframework.security.access.vote.AffirmativeBased.decide(AffirmativeBased.java:83)
at org.springframework.security.access.intercept.AbstractSecurityInterceptor.beforeInvocation(AbstractSecurityInterceptor.java:206)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:115)
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:103)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:154)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:199)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:110)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:85)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:57)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:50)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:108)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:342)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:192)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:160)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
I see that the token is generated Written [409d7529-2f54-4ec0-8439-3f2730e89e3c] as "application/json;charset=UTF-8" but why it redirects to login page instead of returning json?
Anyone please let me know what I'm wrong? Any help would be appreciated!
Update: the problem seems that a new filter chain is started as you can see in logs. But what is the cause???

Resources