User is not authenticated

I am trying to configure the AuthenticationProvider client using Spring Security, but have not managed to get it working. I am using the Java configuration , so I probably missed something simple, but since most of the tutorials are based on the XML configuration, it doesn't jump on me.

This uses Spring v4.0.1.RELEASE, but with Spring Security v3.2.2.RELEASE. Perhaps a column with a version number?

As far as I could tell, all I had to do was create my provider:

public class KBServicesAuthProvider implements AuthenticationProvider { @Autowired private ApplicationConfig applicationConfig; @Autowired private SessionServiceClient sessionServiceClient; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String email = (String) authentication.getPrincipal(); String password = (String) authentication.getCredentials(); try { KBSessionInfo sessionInfo = sessionServiceClient.login(applicationConfig.getKbServicesPresenceId(), email, password); List<GrantedAuthority> grantedRoles = new ArrayList<>(); for (KBRoleMembership role : sessionInfo.getAuthenticatedUser().getRoleMemberships()) { grantedRoles.add(new SimpleGrantedAuthority(role.getRoleId())); } return new UsernamePasswordAuthenticationToken(email, password, grantedRoles); } catch (InvalidSessionException e) { throw new AuthenticationCredentialsNotFoundException("Username or password was not accepted", e); } } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } 

And then set up the class to describe my security setting. This class refers to my provider:

 @Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired(required = true) SessionServiceClient sessionServiceClient; @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().antMatchers("/").permitAll().anyRequest().authenticated(); http.formLogin().loginPage("/login").permitAll().and().logout().permitAll(); } @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(getKBServicesAuthenticationProvider()); } @Bean protected AuthenticationProvider getKBServicesAuthenticationProvider() { return new KBServicesAuthProvider(); } } 

But I don’t see anything in the logs, and not one of my debugging points hits. The application acts as insecure (so I can get to different URLs, etc.).

Any ideas on what I should check?

+14
java spring spring-security
source share
9 answers

This may not be the full answer, as I'm struggling a bit with that. I use my own authentication provider and custom user data service. I see the same behavior as you - breakpoints fall into my user data service, but not in my authentication provider. This is what my entire configuration class looks like:

 @Configuration @EnableWebMvcSecurity @EnableGlobalMethodSecurity(prePostEnabled = true) public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private CustomUserDetailsService userDetailsService; @Autowired private CustomAuthenticationProvider customAuthenticationProvider; @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService); } @Override protected void configure(HttpSecurity http) throws Exception { AuthenticationProvider rememberMeAuthenticationProvider = rememberMeAuthenticationProvider(); TokenBasedRememberMeServices tokenBasedRememberMeServices = tokenBasedRememberMeServices(); List<AuthenticationProvider> authenticationProviders = new ArrayList<AuthenticationProvider>(2); authenticationProviders.add(rememberMeAuthenticationProvider); authenticationProviders.add(customAuthenticationProvider); AuthenticationManager authenticationManager = authenticationManager(authenticationProviders); http .csrf().disable() .headers().disable() .addFilter(new RememberMeAuthenticationFilter(authenticationManager, tokenBasedRememberMeServices)) .rememberMe().rememberMeServices(tokenBasedRememberMeServices) .and() .authorizeRequests() .antMatchers("/js/**", "/css/**", "/img/**", "/login", "/processLogin").permitAll() .antMatchers("/index.jsp", "/index.html", "/index").hasRole("USER") .antMatchers("/admin", "/admin.html", "/admin.jsp", "/js/saic/jswe/admin/**").hasRole("ADMIN") .and() .formLogin().loginProcessingUrl("/processLogin").loginPage("/login").usernameParameter("username").passwordParameter("password").permitAll() .and() .exceptionHandling().accessDeniedPage("/login") .and() .logout().permitAll(); } @Override public void configure(WebSecurity web) throws Exception { web.ignoring().antMatchers("/js/**", "/css/**", "/img/**"); } @Bean public BCryptPasswordEncoder bCryptPasswordEncoder(){ return new BCryptPasswordEncoder(); } @Bean public AuthenticationManager authenticationManager(List<AuthenticationProvider> authenticationProviders) { return new ProviderManager(authenticationProviders); } @Bean public TokenBasedRememberMeServices tokenBasedRememberMeServices() { return new TokenBasedRememberMeServices("testKey", userDetailsService); } @Bean public AuthenticationProvider rememberMeAuthenticationProvider() { return new org.springframework.security.authentication.RememberMeAuthenticationProvider("testKey"); } protected void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(bCryptPasswordEncoder()); } } 

I just found that if I specifically add my authentication provider to the HttpSecurity object, my breakpoints will start to hit:

 http .csrf().disable() .headers().disable() .authenticationProvider(customAuthenticationProvider) 

My goal is to work with BCryptPasswordEncoder, which does not work with this config - everything returns as bad credentials. In any case, I just thought that I would share.

+7
source share

I ran into the same problem. The problem is your method, which will always return false.

 @Override public boolean supports(Class<?> authentication) { return authentication.equals (UsernamePasswordAuthenticationToken.class); } 

Change the above method below and the problem will be solved.

 @Override public boolean supports(Class<?> authentication) { return (UsernamePasswordAuthenticationToken.class .isAssignableFrom(authentication)); } 
+6
source share

You forgot the @Autowired annotation.

 @Autowired @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(getKBServicesAuthenticationProvider()); } 

You can also remove .antMatchers("/").permitAll() .

 @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests().anyRequest().authenticated(); http.formLogin().loginPage("/login").permitAll().and().logout().permitAll(); } 
+3
source share

I had the same problem (my custom auth provider didn’t hit) and solved the problem by entering springSecurityFilterChain , reading Why Spring Security works in Tomcat, but not when deploying to Weblogic? So my problem might have been with WebServer, but I had a problem with an answering machine on Tomcat and now my work on setting up Tomcat has been verified.

I am using Spring boot version 1.4.1 which contains Spring 4.3.3 and Spring Security 4.1.3 and after Traditional deployment

I tested my configuration against Tomcat v9.0 as well as WebLogic 12c R2 and checked if it works on both. hope this helps at least someone who uses Tomcat.

Below my configuration is launched from the main class.

Application.java

 public class Application { public static void main( String[] args ) { SpringApplication.run(new Class[] {AppConfig.class, Initializer.class, SecurityInitializer.class}, args); } } 

Initializer.java

 public class Initializer extends SpringBootServletInitializer implements WebApplicationInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(AppConfig.class); } @Override public void onStartup(ServletContext container) throws ServletException { AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext(); rootContext.register(AppConfig.class); // Manage the lifecycle of the root application context container.addListener(new ContextLoaderListener(rootContext)); // Create the dispatcher servlet Spring application context AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext(); dispatcherContext.register(WebConfig.class); // Register and map the dispatcher servlet ServletRegistration.Dynamic dispatcher = container.addServlet("my-servlet", new DispatcherServlet(dispatcherContext)); dispatcher.setLoadOnStartup(1); dispatcher.addMapping("/*"); } } 

Here AbstractSecurityWebApplicationInitializer creates the SpringSecurityFilterChain from the onStartup method. I have not implemented anything since I am trying to use the default configuration.

SecurityInitializer.java

 public class SecurityInitializer extends AbstractSecurityWebApplicationInitializer { } 

Appconfig.java

 @Configuration @EnableAutoConfiguration @EnableScheduling @EnableMBeanExport @EnableAsync @EnableAspectJAutoProxy @ComponentScan("com.my.package") public class AppConfig { } 

SecurityConfig.java

 @Configuration @EnableWebSecurity @ComponentScan("com.my.package") public class SecurityConfig extends WebSecurityConfigurerAdapter { @Autowired private RestfulRemoteAuthenticationProvider restfulRemoteAuthenticationProvider; @Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(restfulRemoteAuthenticationProvider); } @Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable(); http.authorizeRequests().anyRequest().authenticated().and().httpBasic(); } } 

Webconfig.java

 @Configuration @EnableWebMvc @ComponentScan(basePackages = "com.my.controller.package") public class WebConfig extends WebMvcConfigurerAdapter { @Bean public InternalResourceViewResolver internalViewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setPrefix("/WEB-INF/jsp/"); viewResolver.setSuffix(".jsp"); viewResolver.setOrder(1); return viewResolver; } } 

This is my custom auth provider for receiving authentication information from another component via Restful request

RestfulRemoteAuthenticationProvider.java

 @Component public class RestfulRemoteAuthenticationProvider implements AuthenticationProvider { @Autowired private ManagementClientAdapterFactory managementClientAdapterFactory; @Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String username = authentication.getName(); String password = authentication.getCredentials().toString(); // my logic to get and configure authSource which is my environment specific thing, also same for RemoteAuthRequestResult RemoteAuthRequestResult result = (RemoteAuthRequestResult)authSource.sendRequest(); if(result.isAuthenticated()) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); grantedAuths.add(new SimpleGrantedAuthority("ROLE_USER")); return new UsernamePasswordAuthenticationToken(username, password, grantedAuths); } throw new BadCredentialsException("User not found by given credential"); } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); } } 
+2
source share
  Something like should be present in java config @Configuration @EnableGlobalMethodSecurity(prePostEnabled=true) public class HelloMethodSecurityConfig { } 
+1
source share

@EnableWebMvcSecurity will be deprecated in 4.0 https://jira.spring.io/browse/SEC-2790

You might want to consider the configuration.

+1
source share
 <security:global-method-security pre-post-annotations="enabled"/> 
0
source share

I had a similar problem, and that was because I was using the @ Autowire-ed AuthenticationManager instance that was created by spring loading and just did not contain my custom AuthenticationProvider .

After two days of debugging spring giblets, I finally understand that this is not the same instance as the manager from org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter#authenticationManager() which I configured in my custom WebSecurityConfigurerAdapter via WebSecurityConfigurerAdapter#configure(AuthenticationManagerBuilder) .

Now I just get this instance from WebSecurityConfigurerAdapter#authenticationManager() and GenericFilterBean it in my GenericFilterBean , which handles my authentication logic. Works great.

0
source share

Also make sure that you submit the username and password with the correct headers.

Check the curl below and check if the class has been called

curl -X GET \ http: // localhost: 8080 \ -H 'Authorization: Basic cmdlbGxtYW5AYnIuaWJtLmNvbTphYmM =' \ - H 'X-Requested-With: XMLHttpRequest' \ - H 'cache control: no cache'

0
source share

All Articles