Token based remember me cookie is not working at the time of autologin redirection - spring

I am using spring security 4.1.1 and spring boot for authentication its working totally good. Now I started to implement remember me below is my configuration code
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
CustomAuthenticationProvider customAuthenticationProvider;
// UserDetailsService userDetailsService;
#Autowired
UserDetailsService userDetailsService;
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/", "/login", "/signup","/logout", "/loginProcess","/public/**","/forgotpassword","/forgot-password*","/isUserExists","/emailForgot","/verify-user*").permitAll()
.anyRequest().authenticated()
.and()
.csrf().disable()
.rememberMe().key("tokenkey").rememberMeParameter("_spring_security_remember_me").rememberMeCookieName("myremembermecookie").tokenValiditySeconds(1209600).alwaysRemember(true).userDetailsService(userDetailsService)
.and()
.formLogin().loginPage("/login").loginProcessingUrl("/loginProcess").defaultSuccessUrl("/home")
.failureUrl("/login?error").usernameParameter("userName").passwordParameter("userPassword").permitAll()
.and().logout().logoutUrl("/logout").logoutSuccessUrl("/login?logout").deleteCookies("JSESSIONID")
.invalidateHttpSession(true).permitAll().and().headers().defaultsDisabled().cacheControl();
}
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider);
auth.userDetailsService(userDetailsService);
}
}
This is my custom authentication provider code
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider{
public static final Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
#Autowired
WyzbeeGatewayService sdkService;
#Autowired
UserData userData;
#Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
logger.info("###############################################################################################");
logger.info(authentication.getName()+" "+authentication.getCredentials());
logger.info("###############################################################################################");
try {
final String userToken = sdkService.login(authentication.getName(), authentication.getCredentials().toString());
final LoginResponse responseValidate = sdkService.validateUser(authentication.getName(), authentication.getCredentials().toString());
userData.setUserTenantList(responseValidate.getUserTenantList());
List<GrantedAuthority> grantedAuths = new ArrayList<GrantedAuthority>();
userData.setUserName(authentication.getName());
userData.setPasswrod(authentication.getCredentials().toString());
userData.setGrantedAuths(grantedAuths);
userData.setUserToken(userToken);
UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(authentication.getName(), authentication.getCredentials().toString(), grantedAuths);
logger.info("checking for authentication "+usernamePasswordAuthenticationToken.isAuthenticated());
//UserDetails user = new User(authentication.getName(), authentication.getCredentials().toString(), true, true, true, true, grantedAuths);
//SecurityContextHolder.getContext().setAuthentication(new RememberMeAuthenticationToken("tokenkey", authentication.getName(), grantedAuths));
/* UserService userService = new UserService();
userService.setUserDetails(user);*/
return usernamePasswordAuthenticationToken;
} catch (final WyzbeeException e) {
throw new UsernameNotFoundException("Username " + authentication.getName() + " not found");
}
}
#Override
public boolean supports(Class<?> arg0) {
return true;
}
As I don't have direct access to the database we have a rest call for login and logout so I was not able to use directly UserDetailsServiceI used AuthenticationProvider to check the credentials but, spring document says if you want to use in-built remember me mechanisms we should have UserDetailsService so I implemented in this way
#Service
public class UserService implements UserDetailsService {
UserDetails user= null;
public static final Logger logger = LoggerFactory.getLogger(UserService.class);
#Autowired
WyzbeeGatewayService sdkService;
#Autowired
UserData userData;
#Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
/*logger.info("###############################################################################################");
logger.info("User Service "+userData.getUserName());
logger.info("###############################################################################################");*/
return new User(userData.getUserName(), userData.getPasswrod(), true, true, true, true, userData.getGrantedAuths());
}
public void setUserDetails(UserDetails user){
this.user = user;
}
}
The problem is the cookie is generating and storing in browser when I login for first time after login I am closing the browser without logout when I again access my URL it is again moving to login page. I dent mention anything in index.jsp just maintained to redirect to login page.
Debugged content
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/login'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/signup'
2016-09-27 11:51:24 DEBUG DispatcherServlet:1044 - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/logout'
2016-09-27 11:51:24 DEBUG DispatcherServlet:1000 - Successfully completed request
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/loginProcess'
2016-09-27 11:51:24 DEBUG ExceptionTranslationFilter:117 - Chain processed normally
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/style.css'; against '/public/**'
2016-09-27 11:51:24 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /public/css/style.css; Attributes: [permitAll]
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:104 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#4954e173
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities
2016-09-27 11:51:24 DEBUG AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5de2ed51, returned: 1
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:243 - Authorization successful
2016-09-27 11:51:24 DEBUG FilterSecurityInterceptor:256 - RunAsManager did not change Authentication object
2016-09-27 11:51:24 DEBUG FilterChainProxy:310 - /public/css/style.css reached end of additional filter chain; proceeding with original chain
2016-09-27 11:51:24 DEBUG DispatcherServlet:865 - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/virtual/public/css/style.css]
2016-09-27 11:51:24 DEBUG SimpleUrlHandlerMapping:190 - Matching patterns for request [/public/css/style.css] are [/public/**, /**]
2016-09-27 11:51:24 DEBUG SimpleUrlHandlerMapping:219 - URI Template variables for request [/public/css/style.css] are {}
2016-09-27 11:51:24 DEBUG SimpleUrlHandlerMapping:140 - Mapping [/public/css/style.css] to HandlerExecutionChain with handler [ResourceHttpRequestHandler [locations=[class path resource [static/public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver#1c026d4e]]] and 1 interceptor
2016-09-27 11:51:24 DEBUG DispatcherServlet:951 - Last-Modified value for [/virtual/public/css/style.css] is: -1
2016-09-27 11:51:24 DEBUG DispatcherServlet:1044 - Null ModelAndView returned to DispatcherServlet with name 'dispatcherServlet': assuming HandlerAdapter completed request handling
2016-09-27 11:51:24 DEBUG DispatcherServlet:1000 - Successfully completed request
2016-09-27 11:51:24 DEBUG ExceptionTranslationFilter:117 - Chain processed normally
2016-09-27 11:51:24 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:104 - Cleared thread-bound request context: org.apache.catalina.connector.RequestFacade#634ebe6
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:114 - Bound request context to thread: org.apache.catalina.connector.RequestFacade#634ebe6
2016-09-27 11:51:24 DEBUG OrderedRequestContextFilter:114 - Bound request context to thread: org.apache.catalina.connector.RequestFacade#4954e173
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2016-09-27 11:51:24 DEBUG HttpSessionSecurityContextRepository:207 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#7a88a3ec: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG HttpSessionSecurityContextRepository:207 - Obtained a valid SecurityContext from SPRING_SECURITY_CONTEXT: 'org.springframework.security.core.context.SecurityContextImpl#7a88a3ec: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 4 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', GET]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/fonts/eau_sans_bold-webfont.woff'; against '/logout'
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'POST /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'PUT /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'DELETE /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:72 - No matches found
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:157 - Checking match of request : '/public/css/fonts/eau_sans_book-webfont.woff'; against '/logout'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_bold-webfont.woff' doesn't match 'POST /loginProcess
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', POST]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'POST /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', PUT]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'PUT /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:65 - Trying to match using Ant [pattern='/logout', DELETE]
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'DELETE /logout
2016-09-27 11:51:24 DEBUG OrRequestMatcher:72 - No matches found
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 5 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
2016-09-27 11:51:24 DEBUG AntPathRequestMatcher:137 - Request 'GET /public/css/fonts/eau_sans_book-webfont.woff' doesn't match 'POST /loginProcess
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 6 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 7 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 8 of 12 in additional filter chain; firing Filter: 'RememberMeAuthenticationFilter'
2016-09-27 11:51:24 DEBUG RememberMeAuthenticationFilter:154 - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG RememberMeAuthenticationFilter:154 - SecurityContextHolder not populated with remember-me token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_book-webfont.woff at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-09-27 11:51:24 DEBUG FilterChainProxy:325 - /public/css/fonts/eau_sans_bold-webfont.woff at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2016-09-27 11:51:24 DEBUG AnonymousAuthenticationFilter:106 - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#7a88a3ec: Principal: swapnil1472; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#380f4: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 3B315D5D7EF75385D93713710B62079C; Not granted any authorities'

Related

Spring Security applying HttpSecurity filter before building user principal

I have a springboot application that is using Keycloak to handle JWT authentication. If I use #PreAuthorize on my controller method, everything works as expected, but the URL antMatcher pattern based HttpSecurity is not. From what I can tell, Spring is applying the security filter BEFORE building the user principal. In the logs, I see it testing against Anonymous, even though a valid Bearer token was passed, and I'm able to see the AuthenticationPrincipal inside the controller method.
Basically, HttpSecurity is running its rules against Anonymous, even though later a valid Principal is created and can be used by #PreAuthorize checks.
#Configuration
#EnableWebSecurity
#EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
#Autowired
public void configureGlobal(
AuthenticationManagerBuilder auth) throws Exception {
KeycloakAuthenticationProvider keycloakAuthenticationProvider
= keycloakAuthenticationProvider();
keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
#Bean
public KeycloakConfigResolver KeycloakConfigResolver() {
return new KeycloakConfigResolver() {
#Override
public KeycloakDeployment resolve(HttpFacade.Request request) {
KeycloakDeployment deployment = null;
AdapterConfig adapterConfig = new AdapterConfig();
adapterConfig.setAuthServerUrl(System.getProperty("keycloak.auth-server-url"));
adapterConfig.setRealm(System.getProperty("keycloak.realm"));
adapterConfig.setResource(System.getProperty("keycloak.resource"));
// adapterConfig.setUseResourceRoleMappings(true);
adapterConfig.setSslRequired("external");
adapterConfig.setPublicClient(true);
deployment = KeycloakDeploymentBuilder.build(adapterConfig);
return deployment;
}
};
}
#Bean
#Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
return new RegisterSessionAuthenticationStrategy(
new SessionRegistryImpl());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.cors().configurationSource(request -> new CorsConfiguration().applyPermitDefaultValues())
.and().csrf().disable()
.authorizeRequests()
.antMatchers("/api/public/*").permitAll()
.antMatchers("/api/admin/*").hasRole("admin")
.antMatchers("/api/*").authenticated()
;
}
}
The spring security logs look like
2020-11-28 10:00:45.659 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
2020-11-28 10:00:45.659 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
2020-11-28 10:00:45.660 DEBUG 25655 --- [nio-8180-exec-1] w.c.HttpSessionSecurityContextRepository : No HttpSession currently exists
2020-11-28 10:00:45.660 DEBUG 25655 --- [nio-8180-exec-1] w.c.HttpSessionSecurityContextRepository : No SecurityContext was available from the HttpSession: null. A new one will be created.
2020-11-28 10:00:45.662 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
2020-11-28 10:00:45.663 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 4 of 11 in additional filter chain; firing Filter: 'CorsFilter'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 5 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', GET]
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/admin/condition' doesn't match 'GET /logout'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', POST]
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/admin/condition'; against '/logout'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', PUT]
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/admin/condition' doesn't match 'PUT /logout'
2020-11-28 10:00:45.664 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : Trying to match using Ant [pattern='/logout', DELETE]
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Request 'POST /api/admin/condition' doesn't match 'DELETE /logout'
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.web.util.matcher.OrRequestMatcher : No matches found
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.s.HttpSessionRequestCache : saved request doesn't match
2020-11-28 10:00:45.665 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-11-28 10:00:45.666 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-11-28 10:00:45.667 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.AnonymousAuthenticationFilter : Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#2aa3a4a: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS'
2020-11-28 10:00:45.667 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/medical-condition at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-11-28 10:00:45.668 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.session.SessionManagementFilter : Requested session ID 8C6524CDA3CD92F69B885542B2E5DF1C is invalid.
2020-11-28 10:00:45.668 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-11-28 10:00:45.668 DEBUG 25655 --- [nio-8180-exec-1] o.s.security.web.FilterChainProxy : /api/admin/condition at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/admin/condition'; against '/api/public/*'
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.u.matcher.AntPathRequestMatcher : Checking match of request : '/api/admin/condition'; against '/api/admin/*'
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Secure object: FilterInvocation: URL: /api/admin/condition; Attributes: [hasRole('ROLE_admin')]
2020-11-28 10:00:45.669 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.i.FilterSecurityInterceptor : Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#2aa3a4a: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
2020-11-28 10:00:45.673 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.access.vote.AffirmativeBased : Voter: org.springframework.security.web.access.expression.WebExpressionVoter#4e7d07d7, returned: -1
2020-11-28 10:00:45.679 DEBUG 25655 --- [nio-8180-exec-1] o.s.s.w.a.ExceptionTranslationFilter : Access is denied (user is anonymous); redirecting to authentication entry point
Before you configure your own specific configuration, you need to call the Keycloak-configuration
#Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http); // <----
http.... //
}
The configure method needs to called first and better option user principal would be to add an interceptor rather than filters..and please add super.configure(http);
Thanks!

CustomAuthenticationProvider doesn't get called spring-security 5.2

I have converted an app to use spring and spring security I am using version 5.2. When I try and login my CustomAuthProvider doesn't get called. It does hit the security endpoint 'login' in the jsp and has an anonymous role. Below are the relevant configs.
#ComponentScan(basePackages = {"com.example"})
#Import({com.example.Configuration.class, WebSecurityConfig.class})
public class AppConfig {
servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy("springSecurityFilterChain"))
.addMappingForUrlPatterns(null, false, "/mvc/*");
Register the DelegatingFilterProxy
public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer {
}
The WebSecurity class
#Configuration
#EnableWebSecurity(debug = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Autowired
private CustomAuthenticationProvider customAuthenticationProvider;
#Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(customAuthenticationProvider)
.userDetailsService(new UserDetails());
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.IF_REQUIRED).and().
authorizeRequests(a ->
a.antMatchers(
"/resources/js/**",
"/resources/scripts/**",
"/login",
"/resources/styles/**",
"/resources/images/**",
"/resources/loginPage.jsp",
"/resources/forgotUserName.jsp",
"/resources/forgotPassword.jsp",
"/mvc/jsonInitialResponse/**")
.permitAll()
.antMatchers(
"/resources/resetPassword.jsp",
"/mvc/jsonResponse/**",
"/mvc/download/**",
"/resources/**"
).authenticated())
.formLogin()
.loginPage("/resources/loginPage.jsp")
.successHandler(new CustomeAuthenticationSuccessHandler())
.failureUrl("/resources/loginPage.jsp?error=true")
.and().anonymous()
.and()
.logout()
.logoutSuccessUrl("/resources/loginPage.jsp")
.permitAll()
.and()
.csrf().disable().cors().disable();
}
}
#Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
#Override
public Authentication authenticate(final Authentication authentication) {......}
#Override
public boolean supports(Class<?> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
Any thoughts on what I may be missing? The CustomAuthenticationProvider isn't being called and either is the supports() method.
2020-10-06 12:26:29 DEBUG DefaultSavedRequest:359 - pathInfo: both null (property equals)
2020-10-06 12:26:29 DEBUG DefaultSavedRequest:359 - queryString: both null (property equals)
2020-10-06 12:26:29 DEBUG DefaultSavedRequest:383 - requestURI: arg1=/reinsurance-service-ui-war/resources/login; arg2=/reinsurance-service-ui-war/resources/images/icn-lock.png (property not equals)
2020-10-06 12:26:29 DEBUG HttpSessionRequestCache:95 - saved request doesn't match
2020-10-06 12:26:29 DEBUG FilterChainProxy:328 - /resources/images/icn-lock.png at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
2020-10-06 12:26:29 DEBUG FilterChainProxy:328 - /resources/images/icn-lock.png at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
2020-10-06 12:26:29 DEBUG AnonymousAuthenticationFilter:100 - Populated SecurityContextHolder with anonymous token: 'org.springframework.security.authentication.AnonymousAuthenticationToken#418e8a7d: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffbcba8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 4503EBEA550D56CD4AF5506BC88E7576; Granted Authorities: ROLE_ANONYMOUS'
2020-10-06 12:26:29 DEBUG FilterChainProxy:328 - /resources/images/icn-lock.png at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
2020-10-06 12:26:29 DEBUG FilterChainProxy:328 - /resources/images/icn-lock.png at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
2020-10-06 12:26:29 DEBUG FilterChainProxy:328 - /resources/images/icn-lock.png at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
2020-10-06 12:26:29 DEBUG AntPathRequestMatcher:177 - Checking match of request : '/resources/images/icn-lock.png'; against '/resources/js/**'
2020-10-06 12:26:29 DEBUG AntPathRequestMatcher:177 - Checking match of request : '/resources/images/icn-lock.png'; against '/resources/scripts/**'
2020-10-06 12:26:29 DEBUG AntPathRequestMatcher:177 - Checking match of request : '/resources/images/icn-lock.png'; against '/resources/styles/**'
2020-10-06 12:26:29 DEBUG AntPathRequestMatcher:177 - Checking match of request : '/resources/images/icn-lock.png'; against '/resources/images/**'
2020-10-06 12:26:29 DEBUG FilterSecurityInterceptor:219 - Secure object: FilterInvocation: URL: /resources/images/icn-lock.png; Attributes: [anonymous]
2020-10-06 12:26:29 DEBUG FilterChainProxy:313 - /resources/images/icn-pencil.png reached end of additional filter chain; proceeding with original chain
2020-10-06 12:26:29 DEBUG FilterSecurityInterceptor:348 - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#418e8a7d: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#fffbcba8: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: 4503EBEA550D56CD4AF5506BC88E7576; Granted Authorities: ROLE_ANONYMOUS
2020-10-06 12:26:29 DEBUG HstsHeaderWriter:169 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#51ca55f0
2020-10-06 12:26:29 DEBUG HttpSessionSecurityContextRepository:351 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-10-06 12:26:29 DEBUG ExceptionTranslationFilter:120 - Chain processed normally
2020-10-06 12:26:29 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed
2020-10-06 12:26:29 DEBUG AffirmativeBased:66 - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#3fe8aa9d, returned: 1
2020-10-06 12:26:29 DEBUG FilterSecurityInterceptor:243 - Authorization successful
2020-10-06 12:26:29 DEBUG FilterSecurityInterceptor:256 - RunAsManager did not change Authentication object
2020-10-06 12:26:29 DEBUG FilterChainProxy:313 - /resources/images/icn-lock.png reached end of additional filter chain; proceeding with original chain
2020-10-06 12:26:29 DEBUG HstsHeaderWriter:169 - Not injecting HSTS header since it did not match the requestMatcher org.springframework.security.web.header.writers.HstsHeaderWriter$SecureRequestMatcher#51ca55f0
2020-10-06 12:26:29 DEBUG HttpSessionSecurityContextRepository:351 - SecurityContext is empty or contents are anonymous - context will not be stored in HttpSession.
2020-10-06 12:26:29 DEBUG ExceptionTranslationFilter:120 - Chain processed normally
2020-10-06 12:26:29 DEBUG SecurityContextPersistenceFilter:119 - SecurityContextHolder now cleared, as request processing completed```

Client Loading More times in token end point

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

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.

Why is formlogin with second precedence not working when configured with httpbasic with first precedence in spring boot? [duplicate]

This question already has answers here:
Spring Security : Multiple HTTP Config not working
(2 answers)
Closed 6 years ago.
I have an application that exposes "api" services and "web" pages. So, I've configured httpbasic and formlogin as per Spring's documentation (and from various other SO posts)
http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#multiple-httpsecurity
Spring Security HTTP Basic for RESTFul and FormLogin (Cookies) for web - Annotations
Below is my custom web security configurer code
#EnableWebSecurity
public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Autowired
private MyAuthenticationProvider myAuthenticationProvider;
#Autowired
#Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(myAuthenticationProvider);
}
#Configuration
#Order(1)
public static class BasicAuthentication extends WebSecurityConfigurerAdapter{
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/myapp/api/**").authenticated()
.and() // Permit access for all to login REST service
.httpBasic()
.authenticationEntryPoint(new MyAuthenticationFailurePoint());
}
}
#Configuration
#Order(2)
public static class FormAuthentication extends WebSecurityConfigurerAdapter{
private final Logger log = LoggerFactory.getLogger(this.getClass());
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/myapp/web/**").authenticated()
.and()
.formLogin()
.loginPage("/myapp/web/login")
.permitAll()
.and()
.logout()
.logoutUrl("/myapp/web/logout")
.permitAll();
}
}
}
With this code, when I consume (GET) "http:/ /localhost:8083/myapp/api/getIds", the logic works as expected and my custom authentication provider gets called. Please find below the
logs for your reference
[DEBUG] 2016-12-21 04:36:08.878 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[DEBUG] 2016-12-21 04:36:08.904 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[DEBUG] 2016-12-21 04:36:08.928 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[DEBUG] 2016-12-21 04:36:08.928 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[DEBUG] 2016-12-21 04:36:09.029 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[DEBUG] 2016-12-21 04:36:09.030 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#3b41e91a
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/api/getids'; against '/logout'
[DEBUG] 2016-12-21 04:36:09.030 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
[DEBUG] 2016-12-21 04:36:09.089 org.springframework.security.web.authentication.www.BasicAuthenticationFilter - Basic Authentication Authorization header found for user 'testuser'
[DEBUG] 2016-12-21 04:36:09.166 org.springframework.security.authentication.ProviderManager - Authentication attempt using com.myapp.inf.authenticator.MyAuthenticationProvider
[TRACE] 2016-12-21 04:36:33.498 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Publishing event in org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13330ac6: org.springframework.security.authentication.event.AuthenticationSuccessEvent[source=org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities]
[DEBUG] 2016-12-21 04:36:33.498 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
[DEBUG] 2016-12-21 04:36:33.499 org.springframework.security.web.authentication.www.BasicAuthenticationFilter - Authentication success: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
[DEBUG] 2016-12-21 04:36:33.499 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[DEBUG] 2016-12-21 04:36:33.499 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.authentication.AnonymousAuthenticationFilter - SecurityContextHolder not populated with anonymous token, as it already contained: 'org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
[DEBUG] 2016-12-21 04:36:33.551 org.springframework.security.web.authentication.session.CompositeSessionAuthenticationStrategy - Delegating to org.springframework.security.web.authentication.session.ChangeSessionIdAuthenticationStrategy#46bf4560
[DEBUG] 2016-12-21 04:36:33.583 org.springframework.security.web.context.HttpSessionSecurityContextRepository - HttpSession being created as SecurityContext is non-default
[DEBUG] 2016-12-21 04:36:33.835 org.springframework.security.web.context.HttpSessionSecurityContextRepository - SecurityContext 'org.springframework.security.core.context.SecurityContextImpl#fa787cf9: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities' stored to HttpSession: 'org.apache.catalina.session.StandardSessionFacade#2c175127
[DEBUG] 2016-12-21 04:36:33.835 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[DEBUG] 2016-12-21 04:36:33.835 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[DEBUG] 2016-12-21 04:36:33.860 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/api/getids'; against '/myapp/api/**'
[DEBUG] 2016-12-21 04:36:33.860 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /myapp/api/getIds; Attributes: [authenticated]
[DEBUG] 2016-12-21 04:36:33.860 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.UsernamePasswordAuthenticationToken#fa787cf9: Principal: testuser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#957e: RemoteIpAddress: 127.0.0.1; SessionId: null; Not granted any authorities
[DEBUG] 2016-12-21 04:36:34.082 org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#5169d120, returned: 1
[DEBUG] 2016-12-21 04:36:34.082 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Authorization successful
[DEBUG] 2016-12-21 04:36:34.082 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - RunAsManager did not change Authentication object
[DEBUG] 2016-12-21 04:36:34.083 org.springframework.security.web.FilterChainProxy - /myapp/api/getIds reached end of additional filter chain; proceeding with original chain
Now, when I hit (from browser) "http:/ /localhost:8083/myapp/web/MainConsole", I'm not being prompted for a login page. Please find below the logs for this hit. They indicate that spring boot
is using "httpbasic" config for this hit
[DEBUG] 2016-12-21 04:41:30.179 [http-nio-8083-exec-3] org.springframework.boot.context.web.OrderedRequestContextFilter - Bound request context to thread: org.apache.catalina.connector.RequestFacade#26ff703a
[DEBUG] 2016-12-21 04:41:30.179 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 1 of 11 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[DEBUG] 2016-12-21 04:41:30.179 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 2 of 11 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 3 of 11 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] 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#3b41e91a
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 4 of 11 in additional filter chain; firing Filter: 'LogoutFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/web/mainconsole'; against '/logout'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 5 of 11 in additional filter chain; firing Filter: 'BasicAuthenticationFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 6 of 11 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 7 of 11 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[DEBUG] 2016-12-21 04:41:30.187 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 8 of 11 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[DEBUG] 2016-12-21 04:41:30.188 [http-nio-8083-exec-3] org.springframework.security.web.authentication.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'
[DEBUG] 2016-12-21 04:41:30.188 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 9 of 11 in additional filter chain; firing Filter: 'SessionManagementFilter'
[DEBUG] 2016-12-21 04:41:30.188 [http-nio-8083-exec-3] org.springframework.security.web.session.SessionManagementFilter - Requested session ID 2E28DB9D6699424055855E4F28D7AF9A is invalid.
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 10 of 11 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 11 of 11 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/web/mainconsole'; against '/myapp/api/**'
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Public object - authentication not attempted
[TRACE] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Publishing event in org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13330ac6: org.springframework.security.access.event.PublicInvocationEvent[source=FilterInvocation: URL: /myapp/web/MainConsole]
[DEBUG] 2016-12-21 04:41:30.189 [http-nio-8083-exec-3] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
[DEBUG] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole reached end of additional filter chain; proceeding with original chain
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Bound request context to thread: SecurityContextHolderAwareRequestWrapper[ org.springframework.security.web.context.HttpSessionSecurityContextRepository$Servlet3SaveToSessionRequestWrapper#1274a368]
[DEBUG] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'dispatcherServlet' processing GET request for [/myapp/web/MainConsole]
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping#219e6d9f] in DispatcherServlet with name 'dispatcherServlet'
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - No handler mapping found for [/myapp/web/MainConsole]
[TRACE] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#5afb11fb] in DispatcherServlet with name 'dispatcherServlet'
[DEBUG] 2016-12-21 04:41:30.190 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /myapp/web/MainConsole
[TRACE] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Found 1 matching mapping(s) for [/myapp/web/MainConsole] : [{[/myapp/web/MainConsole]}]
[DEBUG] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public java.lang.String com.myapp.core.controllers.web.MainConsole.showMainConsole()]
[DEBUG] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'mainConsole'
[TRACE] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Testing handler adapter [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter#718cb880]
[DEBUG] 2016-12-21 04:41:30.191 [http-nio-8083-exec-3] org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/myapp/web/MainConsole] is: -1
[TRACE] 2016-12-21 04:41:30.193 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Invoking [MainConsole.showMainConsole] method with arguments []
[TRACE] 2016-12-21 04:41:30.194 [http-nio-8083-exec-3] org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod - Method [showMainConsole] returned [home]
[DEBUG] 2016-12-21 04:41:30.230 [http-nio-8083-exec-3] org.springframework.web.servlet.view.ContentNegotiatingViewResolver - Requested media types are [text/html, application/xhtml+xml, image/webp, application/xml;q=0.9, */*;q=0.8] based on Accept header types and producible media types [*/*])
[DEBUG] 2016-12-21 04:41:30.230 [http-nio-8083-exec-3] org.springframework.web.servlet.view.BeanNameViewResolver - No matching bean found for view name 'home'
Then, I swaped the order on "httpbasic" and "formlogin" and re-executed "http:/ /localhost:8083/myapp/web/MainConsole". Now, the correct filter - UsernamePasswordAuthenticationFilter - gets called. BUt,
the "api" hits aren't working now.
[DEBUG] 2016-12-21 04:52:56.357 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 1 of 12 in additional filter chain; firing Filter: 'WebAsyncManagerIntegrationFilter'
[DEBUG] 2016-12-21 04:52:56.383 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 2 of 12 in additional filter chain; firing Filter: 'SecurityContextPersistenceFilter'
[DEBUG] 2016-12-21 04:52:56.409 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No HttpSession currently exists
[DEBUG] 2016-12-21 04:52:56.410 org.springframework.security.web.context.HttpSessionSecurityContextRepository - No SecurityContext was available from the HttpSession: null. A new one will be created.
[DEBUG] 2016-12-21 04:52:56.514 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 3 of 12 in additional filter chain; firing Filter: 'HeaderWriterFilter'
[DEBUG] 2016-12-21 04:52:56.515 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#32c4de26
[DEBUG] 2016-12-21 04:52:56.515 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 4 of 12 in additional filter chain; firing Filter: 'CsrfFilter'
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 5 of 12 in additional filter chain; firing Filter: 'LogoutFilter'
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request 'GET /myapp/web/mainconsole' doesn't match 'POST /myapp/logout
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 6 of 12 in additional filter chain; firing Filter: 'UsernamePasswordAuthenticationFilter'
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request 'GET /myapp/web/mainconsole' doesn't match 'POST /myapp/login
[DEBUG] 2016-12-21 04:52:56.567 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 7 of 12 in additional filter chain; firing Filter: 'RequestCacheAwareFilter'
[DEBUG] 2016-12-21 04:52:56.568 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 8 of 12 in additional filter chain; firing Filter: 'SecurityContextHolderAwareRequestFilter'
[DEBUG] 2016-12-21 04:52:56.623 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 9 of 12 in additional filter chain; firing Filter: 'AnonymousAuthenticationFilter'
[DEBUG] 2016-12-21 04:52:56.702 org.springframework.security.web.authentication.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'
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 10 of 12 in additional filter chain; firing Filter: 'SessionManagementFilter'
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.session.SessionManagementFilter - Requested session ID 2E28DB9D6699424055855E4F28D7AF9A is invalid.
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 11 of 12 in additional filter chain; firing Filter: 'ExceptionTranslationFilter'
[DEBUG] 2016-12-21 04:52:56.703 org.springframework.security.web.FilterChainProxy - /myapp/web/MainConsole at position 12 of 12 in additional filter chain; firing Filter: 'FilterSecurityInterceptor'
[DEBUG] 2016-12-21 04:52:56.728 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Request 'GET /myapp/web/mainconsole' doesn't match 'POST /myapp/logout
[DEBUG] 2016-12-21 04:52:56.728 org.springframework.security.web.util.matcher.AntPathRequestMatcher - Checking match of request : '/myapp/web/mainconsole'; against '/myapp/web/**'
[DEBUG] 2016-12-21 04:52:56.729 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Secure object: FilterInvocation: URL: /myapp/web/MainConsole; Attributes: [authenticated]
[DEBUG] 2016-12-21 04:52:56.729 org.springframework.security.web.access.intercept.FilterSecurityInterceptor - Previously Authenticated: org.springframework.security.authentication.AnonymousAuthenticationToken#9055c2bc: Principal: anonymousUser; Credentials: [PROTECTED]; Authenticated: true; Details: org.springframework.security.web.authentication.WebAuthenticationDetails#b364: RemoteIpAddress: 0:0:0:0:0:0:0:1; SessionId: null; Granted Authorities: ROLE_ANONYMOUS
[DEBUG] 2016-12-21 04:52:56.930 org.springframework.security.access.vote.AffirmativeBased - Voter: org.springframework.security.web.access.expression.WebExpressionVoter#9d78e5c, returned: -1
[TRACE] 2016-12-21 04:52:56.931 org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext - Publishing event in org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#13330ac6: org.springframework.security.access.event.AuthorizationFailureEvent[source=FilterInvocation: URL: /myapp/web/MainConsole]
[DEBUG] 2016-12-21 04:52:56.931 org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'delegatingApplicationListener'
[DEBUG] 2016-12-21 04:52:56.932 org.springframework.security.web.access.ExceptionTranslationFilter - Access is denied (user is anonymous); redirecting to authentication entry point
Why is httpsbasic is ALWAYS taking first precedence, regardless of a URL pattern that matches for formlogin?
Because you set the api order to 1, so it will always in API filter chain.Change the api config to this. This will match the request path first.
http.antMatcher("/myapp/api/**")
.csrf().disable().authorizeRequests()
.antMatchers("/**").authenticated().and() // Permit access for all to login REST service
.httpBasic()
.authenticationEntryPoint(new MyAuthenticationFailurePoint());

Resources