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 に答える