02 March 2019

Spring security multiple authentication provider


In your WebSecurityConfigurerAdapter you will need to add more than auth

@Override

protected void configure(AuthenticationManagerBuilder auth) throws Exception {

    auth.authenticationProvider(new MyFirstAuthenticationProvider(userRepository, bCryptPasswordEncoder()));

    auth.authenticationProvider(new MySecondAuthenticationProvider(userRepository, bCryptPasswordEncoder()));

}

Then Create MyFirstAuthenticationProvider and MySecondAuthenticationProvider like:

public class MyFirstAuthenticationProvider extends DaoAuthenticationProvider {

    public MyFirstAuthenticationProvider(UserRepository userRepository,
                                              BCryptPasswordEncoder bCryptPasswordEncoder) {

        super.setPasswordEncoder(bCryptPasswordEncoder);
        super.setUserDetailsService(......)
        );
    }

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


public class MyFirstAuthenticationToken extends UsernamePasswordAuthenticationToken {

    public MyFirstAuthenticationToken(UserEntity principal, Object credentials,
                                                   Collection<? extends GrantedAuthority> authorities) {
        super(principal, credentials, authorities);
    }
}
And the same for MySecondAuthenticationProvider.

You will need to use the authentication providers/token in the authenticaiton/authorization filters.


No comments: