Skip to content

Instantly share code, notes, and snippets.

@sandipchitale
Last active November 4, 2023 12:22
Show Gist options
  • Save sandipchitale/f1c0f5b5bb22297ad0c15408a26a340d to your computer and use it in GitHub Desktop.
Save sandipchitale/f1c0f5b5bb22297ad0c15408a26a340d to your computer and use it in GitHub Desktop.
Multiple Authentication Provider Security Config #spring-security
@Configuration
@EnableWebSecurity()
static class SecurityConfig {
public static class CustomAuthenticationProvider implements AuthenticationProvider {
private final String username;
private final String password;
private final String role;
CustomAuthenticationProvider(String username, String password, String role) {
this.username = username;
this.password = password;
this.role = role;
}
@Override
public Authentication authenticate(Authentication auth)
throws AuthenticationException {
String u = auth.getName();
String p = auth.getCredentials().toString();
if (username.equals(u) && password.equals(p)) {
return new UsernamePasswordAuthenticationToken
(username, password, Collections.singletonList(new SimpleGrantedAuthority(role)));
} else {
throw new
BadCredentialsException("External system authentication failed");
}
}
@Override
public boolean supports(Class<?> auth) {
return auth.equals(UsernamePasswordAuthenticationToken.class);
}
}
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity httpSecurity) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder =
httpSecurity.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.authenticationProvider(new CustomAuthenticationProvider("user", "password", "USER"));
authenticationManagerBuilder.authenticationProvider(new CustomAuthenticationProvider("user1", "password", "USER"));
authenticationManagerBuilder.authenticationProvider(new CustomAuthenticationProvider("admin", "password", "ADMIN"));
authenticationManagerBuilder.authenticationProvider(new CustomAuthenticationProvider("admin1", "password", "ADMIN"));
httpSecurity.authenticationManager(authenticationManagerBuilder.build());
httpSecurity
.authorizeHttpRequests(auth -> {
auth.requestMatchers(EndpointRequest.toAnyEndpoint()).permitAll();
auth.anyRequest().fullyAuthenticated();
});
httpSecurity.logout(new LogoutCustomizer());
httpSecurity.formLogin(withDefaults());
return httpSecurity.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return NoOpPasswordEncoder.getInstance();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment