我想在用户详细信息中添加其他信息,例如用户的IP地址。有没有办法实现这个目标?我试图创建一个新的CustomSpringUser类,但问题是如何从Authentication对象获取此信息。是否有其他方法可以为经过身份验证的用户存储其他信息?
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
我的自定义用户类;
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;
}
}
编辑:我发现我们可以为身份验证添加其他信息,但我找不到如何执行此操作。 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);
}
}