从Principal访问用户电子邮件

时间:2018-10-29 13:26:29

标签: spring-boot spring-security spring-security-oauth2

我有一个身份验证应用程序和一个资源应用程序一起工作。 在资源服务器中,我需要访问一些其他信息,例如电子邮件。

在身份验证方面,我有 用户实体:

1

还有一个扩展UserDetails的CustomUserDetails类

@Entity
@Table(name = "users")
public class User {

    @Id
    @Column(name = "userid")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long userId;

    @Column(name = "username", nullable = false, length = 32)
    private String userName;

    @Column(name = "password", nullable = false, length = 255)
    private String password;

    @Column(name = "email", nullable = false, length = 32)
    private String email;

    @Column(name = "enabled", nullable = false)
    private boolean enabled = false;

    @ManyToMany(fetch = FetchType.EAGER)
    @JoinTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id"))
    private Collection<Role> roles;
...
}

然后是CustomUserDetailsS​​ervice,它扩展了UserDetailsS​​ervice并实现了loadUserByUsername

public class CustomUserDetails extends User implements UserDetails {

    private static final long serialVersionUID = 1L;
    private List<String> userRoles;

    public CustomUserDetails(User user, List<String> userRoles) {
        super(user);
        this.userRoles = userRoles;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {

        String roles = StringUtils.collectionToCommaDelimitedString(userRoles);
        return AuthorityUtils.commaSeparatedStringToAuthorityList(roles);
    }

    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    @Override
    public boolean isEnabled() {
        return true;
    }

    @Override
    public String getUsername() {
        return super.getUserName();
    }

在此步骤中,如果我检查“新的CustomUserDetails(user,userRoles)”,则在电子邮件字段中确实有来自DB的用户电子邮件。

然后在我的资源应用程序中,在WS上,我尝试访问连接的用户信息:

@Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUserName(username);

        if (null == user) {
            throw new UsernameNotFoundException("No user present with username: " + username);
        } else {
            List<String> userRoles = getPrivileges(user.getRoles());
            return new CustomUserDetails(user, userRoles);
        }
    }

但是,当我使用调试检查身份验证时,我无法找到电子邮件信息,我所拥有的只是Principal中的userName值。

我错过了什么吗?我应该怎么做才能获得有关已连接用户的更多信息?

0 个答案:

没有答案