3

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

1 回答 1

2

要从对象/实例中获取,请使用该UserDetails方法。该方法用于获取有关用户的附加信息(通常是 的实例)。AuthenticationgetPrincipal()getDetails()WebAuthenticationDetails

链接

  1. 身份验证javadoc
  2. Authentication.getDetails() javadoc
  3. Authentication.getPrincipal() javadoc
于 2013-09-13T13:27:16.230 回答