I want to add additional information to userdetails like user's Ip address. Is there any way to achieve this? I tried to create a new CustomSpringUser class but the problem is how can i get this information from Authentication object. Is there any other way to store additional information for authenticated user?
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
My custom user class;
public class CustomSpringUser extends org.springframework.security.core.userdetails.User {
public String ip;
public CustomSpringUser(String username, String password, Collection<? extends GrantedAuthority> authorities) {
super(username, password, authorities);
}
public CustomSpringUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String ip) {
super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
this.ip= ip;
}
}
Edit: I found that we can add additional information for Authentication but I couldn't found how to do that. http://docs.spring.io/spring-security/site/docs/3.0.x/apidocs/org/springframework/security/core/Authentication.html#getDetails()
@Override
public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
try {
AppUser appUser = new AppUser();
appUser.setUsername(userName);
AppUser domainUser = genericDao.getByTemplate(appUser).get(0);
boolean enabled = true;
boolean accountNonExpired = true;
boolean credentialsNonExpired = true;
boolean accountNonLocked = true;
List<String> roles = new ArrayList<String>();
roles.add(domainUser.getRole().getName());
return new CustomSpringUser(
domainUser.getUsername(),
domainUser.getPassword().toLowerCase(),
enabled,
accountNonExpired,
credentialsNonExpired,
accountNonLocked,
getGrantedAuthorities(roles),
***domainUser.getAccount().getIdentificationId())*** ;
} catch (Exception e) {
genericLogger.saveLog(Logger.Status.ERROR, "Couldn't login", e);
throw new RuntimeException(e);
}
}