0

我已经能够对用户进行身份验证,并且可以让他们登录的用户名显示在他们的页面上。但我想使用用户名而不是用户名。

为此的汇编程序:

@Service("assembler")
public class Assembler {

    @Transactional(readOnly = true)
    public UserDetails buildUserFromUser(UserEntity userEntity) {

        String username = userEntity.getUsername();
        String password = userEntity.getPassword();
        //String name = userEntity.getName();
        boolean enabled = userEntity.getActive();
        boolean accountNonExpired = enabled;
        boolean credentialsNonExpired = enabled;
        boolean accountNonLocked = enabled;

        Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        for(Role role : userEntity.getRoles()) {
            authorities.add(new SimpleGrantedAuthority(role.getName()));
        }

        User user = new 
        User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);

        return user;
    }
}

我使用的 UserDetails 仅限于 set 构造函数,因此我无法通过它获取名称。还有其他方法可以做到这一点吗?

4

1 回答 1

2

您可以扩展User该类并使用户拥有您想要的附加信息并从buildUserFromUser方法中返回该信息。像这样的东西:

public class CustomUser extends User {
    private String name;

    public CustomUser(String username, String password, boolean enabled, boolean accountNonExpired, boolean credentialsNonExpired, boolean accountNonLocked, Collection<? extends GrantedAuthority> authorities, String name) {
        super(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

在您的方法中实例化此用户,并从对象buildUserFromUser中传递名称:userEntity

@Service("assembler")
public class Assembler {

@Transactional(readOnly = true)
public UserDetails buildUserFromUser(UserEntity userEntity) {

    String username = userEntity.getUsername();
    String password = userEntity.getPassword();
    String name = userEntity.getName();
    boolean enabled = userEntity.getActive();
    boolean accountNonExpired = enabled;
    boolean credentialsNonExpired = enabled;
    boolean accountNonLocked = enabled;

    Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
    for(Role role : userEntity.getRoles()) {
        authorities.add(new SimpleGrantedAuthority(role.getName()));
    }

    return new CustomUser(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities, name);
}

然后您可以像这样从 Spring 安全上下文中获取自定义用户:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
String name = ((CustomUser)authentication.getPrincipal()).getName();
于 2013-05-04T04:34:53.713 回答