Custom Authentication with Spring Security

Asked

Viewed 52 times

1

How do I make a custom login and password authentication using Spring Security? The goal is to verify the login and password in the database.

1 answer

1

As you did not give details there is no way to give a specific answer so the answer will be generic, you will have to implement the interface AuthenticationProvider

Example:

@Component 
public class CustomAuthenticationProvider implements AuthenticationProvider {

    @Override    
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {

      String username = authentication.getName();    
      String password = authentication.getCredentials().toString();    
      if ("user".equals(username) && "password".equals(password)) {    
            return new UsernamePasswordAuthenticationToken(username, password, Collections.emptyList());    
       } else {    
            throw new BadCredentialsException("Authentication failed");    
       }    
    }

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

Source code: https://dzone.com/articles/spring-security-authentication

More references: https://www.baeldung.com/spring-security-authentication-provider

Browser other questions tagged

You are not signed in. Login or sign up in order to post.