I have built my custom Authenticaton Manager for Spring Security which goes something like this
public class AccountAuthenticationProvider implements AuthenticationProvider{
@Autowired
private AuthenticationService authService;
@Override
public Authentication authenticate(Authentication authentication) throws AuthenticationException {
String userName = authentication.getName();
String password = (String)authentication.getCredentials();
if(authService.isValid(userName,password)){
List<GrantedAuthority> grantedAuthorityList = new ArrayList<GrantedAuthority>();
grantedAuthorityList.add(new SimpleGrantedAuthority("ROLE_USER"));
SecurityContext securityContext = new SecurityContextImpl();
return new UsernamePasswordAuthenticationToken(userName,password);
}
return null;
}
public void setAuthService(AuthenticationService authService) {
this.authService = authService;
}
@Override
public boolean supports(Class<?> authentication) {
return true;
}
}
but how do I create my own custom UserDetail object? I'll use that to store account related values
you need to implement UserDetailsService and override loadUserByUsername method to return your customized UserDetails class. Like this-
public class UserServiceImpl implements UserDetailsService {`
@Autowired
UserDaoImpl userDao;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
System.out.println(username);
Users user = (Users) userDao.findByUserName(username);
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRoles());
System.out.println("after....");
return buildUserForAuthentication(user, authorities);
}
private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
for(UserRole userRole : userRoles){
System.out.println("called buildUserAuthority(Set<UserRole> userRoles) method.....");
setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
}
List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>(setAuths);
return grantedAuthorities;
}
private User buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) {
//accountNonExpired, credentialsNonExpired, accountNonLocked, authorities properties
System.out.println("called buildUserForAuthentication(Users user, List<GrantedAuthority> authorities) method....");
return new User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, authorities);
}}
you need to implement UserDetailsService and override loadUserByUsername method to return your customized UserDetails class.
check below links:
http://www.javaroots.com/2013/03/how-to-use-custom-dao-classe-in-spring.html http://www.javacodegeeks.com/2012/08/spring-security-implementing-custom.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With