通过userDetailsManager更改用户角色

时间:2014-05-17 16:31:44

标签: java spring spring-security roles

我想改变用户的角色。更改用户在数据库中的角色。一切都基于Spring Security。

我的代码:

UserDetails user = userDetailsManager.loadUserByUsername(userData.getUser().getUsername());

user.getAuthorities().add(new SimpleGrantedAuthority(role));

userDetailsManager.updateUser(user);

错误:

Error:(99, 30) java: method add in interface java.util.Collection<E> cannot be applied to
given types;
  required: capture#1 of ? extends org.springframework.security.core.GrantedAuthority
  found: org.springframework.security.core.authority.SimpleGrantedAuthority
  reason: actual argument    
org.springframework.security.core.authority.SimpleGrantedAuthority cannot be converted to   
capture#1 of ? extends org.springframework.security.core.GrantedAuthority by method   
invocation conversion

我不知道为什么会出现这个错误。如何以其他方式改变用户的角色?

2 个答案:

答案 0 :(得分:1)

您可以通过从现有用户创建新的UserDetails对象,然后调用UserDetailsManager.updateUser()方法来更新给定用户的角色,如下所示:

    UserDetails oldDetails = userDetailsManager.loadUserByUsername(user);
    UserDetails newDetails = new User(user, oldDetails.getPassword(),  newRole);
    userDetailsManager.updateUser(newDetails);

答案 1 :(得分:1)

  1. the issue is that you can't add a known type into a list that holds an unknown type. (see https://stackoverflow.com/a/3716945/755183)
  2. User is immutable, so in order to modify you should clone existing user and use new roles