Custom AuthenticationProvider

If needs be, we can write a custom AuthenticationProvider by implementing the AuthenticationProvider interface. We will have to implement two methods, namely authenticate (Authentication) and supports(Class<?> aClass):

@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);
}
}

Our authenticate method is quite simple. We just compare the username and password with a static value. We can write any logic here and authenticate the user. If there is an error, it throws an exception, AuthenticationException.

On the book's GitHub page, navigate to the jetty-in-memory-basic-custom-authentication project to see the full source code of this class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.81.154