Custom Authentication Manager with Spring Security and Java Configuration

Take a look at my sample below. You have to return an UsernamePasswordAuthenticationToken. It contains the principal and the GrantedAuthorities. Hope I could help 🙂

public Authentication authenticate(Authentication authentication) throws AuthenticationException {
    String username = authentication.getPrincipal() + "";
    String password = authentication.getCredentials() + "";

    User user = userRepo.findOne(username);
    if (user == null) {
        throw new BadCredentialsException("1000");
    if (!encoder.matches(password, user.getPassword())) {
        throw new BadCredentialsException("1000");
    if (user.isDisabled()) {
        throw new DisabledException("1001");
    List<Right> userRights = rightRepo.getUserRights(username);
    return new UsernamePasswordAuthenticationToken(username, null, -> new SimpleGrantedAuthority(x.getName())).collect(Collectors.toList()));

PS: userRepo and rightRepo are Spring-Data-JPA Repositories which access my custom User-DB

SpringSecurity JavaConfig:

public class MySecurityConfiguration extends WebSecurityConfigurerAdapter {

public MySecurityConfiguration() {

protected AuthenticationManager authenticationManager() throws Exception {
    return new ProviderManager(Arrays.asList((AuthenticationProvider) new AuthProvider()));


Leave a Comment