Spring Security - Custom AuthenticationProvider

Spring Security provides many AuthenticationProvider for you to use. You can provide your own customized AuthenticationProvider if the provided AuthenticationProvider doesn’t satisfy your Authentication need.

AuthenticationProvider Interface

AuthenticationProvider Interface

1
2
3
4
5
6
public interface AuthenticationProvider {
Authentication authenticate(Authentication authentication)
throws AuthenticationException;

boolean supports(Class<?> authentication);
}

AuthenticationProvider interface is one of the most important class in Spring Security. DaoAuthenticationProvider is the most used AuthenticationProvider. It retrieves UserDetails using UserDetailsService and then compares the password with the saved password in UserDetails.

Custom AuthenticationProvider

We can create a custom AuthenticationProvider by implementing AuthenticationProvider interface and override authenticate and supports method.

CustomAuthenticationProvider.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Component
public class CustomAuthenticationProvider implements AuthenticationProvider {
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String name = authentication.getName();
String password = authentication.getCredentials().toString();
if(name.equals("user") && password.equals("password")) {
return new UsernamePasswordAuthenticationToken(name, password, new ArrayList<>());
}
throw new UsernameNotFoundException(name+ " not found.");
}

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

This is a very simple AuthenticationProvider that authenticates user with username equals “user” and password “password”.

SecurityConfiguration.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationProvider authProvider;

@Bean
public PasswordEncoder passwordEncoder() {
return PasswordEncoderFactories.createDelegatingPasswordEncoder();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
http.formLogin()
.and()
.authorizeRequests().anyRequest().authenticated();
}

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

In Spring Security configuration, use AuthenticationManagerBuilder.authenticationProvider() method to set the custom AuthenticationProvider.

Reference