Spring Security - Custom Authentication
Join the DZone community and get the full member experience.
Join For FreeIn this post I will explain how to authenticate a user using spring security.
public class CustomAuthenticationProvider implements AuthenticationProvider {
private static Logger logger = LoggerFactory.getLogger(CustomAuthenticationProvider.class);
public Authentication authenticate(Authentication authentication ) throws AuthenticationException {
String userName = authentication.getName().trim();
String password = authentication.getCredentials().toString().trim();
Authentication auth = null;
CustomLogin login = new CustomLogin();
//Authenticate the user based on your custom logic
String role = login.getApplicationRole(userName, password, "ADMIN","DEVELOPER");
if (role != null)
{
Collection<GrantedAuthority> grantedAuths = new SimpleGrantedAuthority(role.trim());
ApplicationUser appUser = new ApplicationUser(userName,password, true, true, true, true,grantedAuths,"TestEmail");
auth = new UsernamePasswordAuthenticationToken(appUser, password, grantedAuths);
return auth;
}
else
{
return null;
}
}
@Override
public boolean supports(Class<? extends Object> authentication) {
return (UsernamePasswordAuthenticationToken.class.isAssignableFrom(authentication));
}
public class ApplicationUser extends User {
private static final long serialVersionUID = 1L;
private final String email;
public ApplicationUser(String username, String password, boolean enabled,
boolean accountNonExpired, boolean credentialsNonExpired,
boolean accountNonLocked,
Collection<GrantedAuthority> authorities,
String email) {
super(username, password, enabled, accountNonExpired,
credentialsNonExpired, accountNonLocked, authorities);
this.email = email;
}
public String getEmail() {
return email;
}
}
Add this to the spring security config file
<authentication-manager>
<authentication-provider ref="CustomAuthenticationProvider"/>
</authentication-manager>
<bean id="CustomAuthenticationProvider" class="com.custom.security.CustomAuthenticationProvider">
</bean>
Opinions expressed by DZone contributors are their own.
Comments