-2

While adding authentication provider to Spring Security caught Null pointer exception. attaching the stacktrace and also my code

Error:

java.lang.NullPointerException
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:164)
org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:199)
org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:94)
org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:212)
org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:331)
...

And in my code i was trying to configure custom authentication. and the code given below

WebSecurityConfiguration:

@Configuration
@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter 
{

    // @Autowired
    private CustomAuthenticationProvider customAuthenticationProvider;

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

    @Override
    protected void configure(final HttpSecurity http) throws Exception
    {
        http.csrf().disable()
    //  .authenticationProvider(customAuthenticationProvider);
        .authorizeRequests()
            .antMatchers("/resources/**", "/", "/login")
                .permitAll()
            .antMatchers("/config/*", "/app/admin/*")
                .hasRole("ADMIN")
            .antMatchers("/app/user/*")
                .hasAnyRole("ADMIN", "USER")
        .and().exceptionHandling()
            .accessDeniedPage("/403")
        .and().formLogin()
            .loginPage("/login")
            .usernameParameter("userName").passwordParameter("password")
            .defaultSuccessUrl("/app/user/dashboard")
            .failureUrl("/login?error=true")
        .and().logout()
            .logoutSuccessHandler(new CustomLogoutSuccessHandler())
            .invalidateHttpSession(true);
    }

    @Bean
    public PasswordEncoder passwordEncoder() 
    {
        return new BCryptPasswordEncoder();
    }
}

CustomAuthenticationProvider:

// @Component
public class CustomAuthenticationProvider implements AuthenticationProvider 
{
    @Autowired
    private final CustomUserDetailsService userDetailsService;


    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException 
    {
        String username = authentication.getName().toLowerCase();
        String password = (String) authentication.getCredentials();

        userDetailsService.setPassword(password);
        User user = userDetailsService.loadUserByUsername(username);

        if (user == null) 
        {
             throw new BadCredentialsException("Username not found.");
        }

        if (!password.equals(user.getPassword())) 
        {
             throw new BadCredentialsException("Wrong password.");
        }

        userDetailsService.setAuthorized(username);
        Collection<?extends GrantedAuthority> authorities = user.getAuthorities();

        return new UsernamePasswordAuthenticationToken(user, password, authorities);
    }

    @Override
    public boolean supports(Class<?> aClass) 
    {
        return true;
    }
}

Help me to find out my mistake.
Thanks

PraveenKumar Lalasangi
  • 3,255
  • 1
  • 23
  • 47
Zhasulan Berdibekov
  • 1,077
  • 3
  • 19
  • 39
  • 2
    The code you posted has no way of getting an instance of `CustomAuthenticationProvider`. So you must be creating it somewhere as a non-spring managed bean. Post the actual code instead of only the configuration. – M. Deinum Oct 24 '16 at 07:36

2 Answers2

1

I also got the same exception. You will get this exception if you are not passing any authentication provider.

If you are not providing authentication provider or if you pass null

1.
You might have missed to inject authenticationProvider dependency
.authenticationProvider(customAuthenticationProvider)
Or
commented line
//.authenticationProvider(customAuthenticationProvider)
Or.
You might have missed @Component for CustomAuthenticationProvider
OP has done the same mistake.

  1. In my case Missed @Autowired
    (I was configured authorization and also authentication also but null was passed)
//Missed autowired annotation
private CustomAuthenticationProvider customAuthenticationProvider;

And trying to inject null

  @Override
  protected void configure(AuthenticationManagerBuilder auth) throws Exception 
  {
      auth.authenticationProvider(customAuthenticationProvider); // Null passed here
  }

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
          .antMatchers("/**").hasRole("ADMIN")
          .anyRequest()
          .authenticated()
          .and()
          .formLogin();
  }

For your information above code block is equivalent to

@Override
  protected void configure(HttpSecurity http) throws Exception {
      http.authorizeRequests()
          .antMatchers("/**").hasRole("ADMIN")
          .anyRequest()
          .authenticated()
          .and()
          .formLogin()
          .authenticationProvider(customAuthenticationProvider);
  }
PraveenKumar Lalasangi
  • 3,255
  • 1
  • 23
  • 47
0

If you are using spring boot you can do

@configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter{

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

//customAuthenticationProvider() method creates your bean

}

//edit after added code in question

Ok so the problem is not with the instatiation of auth provider but with your own code. NPE shows that something is not initialized in your custom implementation. Is the provided autowired correctly, does it have all deps? See What is a NullPointerException, and how do I fix it?

Community
  • 1
  • 1
Nadir
  • 1,369
  • 1
  • 15
  • 28