将Collection <object>转换为List <string>

时间:2019-01-27 14:48:21

标签: java spring spring-security

我在从String对象中的角色List获得用户角色Collection User时遇到问题。 我想以List的身份获得用户角色,以在UserServiceImlementation的{​​{1}}方法中实现该角色,该方法是将角色名称作为列表传递给loadUserByUsername类,以实现社交登录。将不胜感激。

用户模型

SocialUserDetailsImplementation

UserServiceImpl

@Entity
@Table(uniqueConstraints = @UniqueConstraint(columnNames = "email"))
public class User {

    public static final String ROLE_USER = "ROLE_USER";
    public static final String ROLE_ADMIN = "ROLE_ADMIN";

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name ="user_id", nullable = false)
    private Long userId;

    private String firstName;
    private String lastName;
    private String email;
    private String password;
    private String userName;

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

    @Column(name = "enabled")
    private boolean enabled;


    public User() {
        super();
        this.enabled=false;

    }

    public User(String firstName, String lastName, String email, String password) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
    }

    public User(String firstName, String lastName, String email, String password, Collection<Role> roles) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.roles = roles;
    }

    public User(String firstName, String lastName, String email, String password, String userName, Collection<Role> roles) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
        this.password = password;
        this.userName = userName;
        this.roles = roles;
    }

    public Long getUserId() {
        return userId;
    }

    public void setUserId(Long userId) {
        this.userId = userId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isEnabled() {
        return enabled;
    }

    public void setEnabled(boolean enabled) {
        this.enabled = enabled;
    }

    public Collection<Role> getRoles() {
        return roles;
    }

    public void setRoles(Collection<Role> roles) {
        this.roles = roles;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }


}

SocialUserDetailsImpl

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserRepository userRepository;




    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        User user = userRepository.findByUserName(userName);
        if (user == null) {
            throw new UsernameNotFoundException("Invalid username or password.");
        }


       List<String> roleNames =  (Collectors.toList(user.getRoles()));



        List<GrantedAuthority> grantList = new ArrayList<GrantedAuthority>();
        if (roleNames != null) {
            for (String role : roleNames) {
                GrantedAuthority authority = new SimpleGrantedAuthority(role);
                grantList.add(authority);
            }
        }


        SocialUserDetailsImpl userDetails = new SocialUserDetailsImpl(user,  roleNames);
                return userDetails;
    }

3 个答案:

答案 0 :(得分:0)

在这部分

List<String> roleNames =  (Collectors.toList(user.getRoles()));

您的角色名包含user.getRoles()。toString()的列表,而不是预期的角色名;

尝试

List<String> roleNames =  user.getRoles().stream()
    .map(Role::getName)
    .collect(Collectors.toList());

此外,向ROLE_USER和ROLE_ADMIN字段添加瞬态。

答案 1 :(得分:0)

基本上,您不需要将角色转换为List<String>,您可以通过以下方式构建List<GrantedAuthority>

user.getRoles().stream()
    .map(role -> new SimpleGrantedAuthority(role.getRoleName()))
    .collect(Collectors.toList());

如果您确实需要List<String>,则可以

user.getRoles().stream()
    .map(Role::getRoleName)
    .collect(Collectors.toList());

答案 2 :(得分:-1)

做这样的事情,

List<Object> roleNames =  (Collectors.toList(user.getRoles()));
List<String> roleNamesString= new List<string> ();

for(Object a: roleNames){
   roleNameString.add(String.valueOf(a));
}

根据模型的复杂性,您可能需要重写Role class的toString方法。