我想更改用户的角色。更改用户在数据库中的角色。一切都基于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
我不知道为什么会这样。否则如何更改用户的角色?
最佳答案
您可以通过从现有用户创建一个新的UserDetails对象,然后按如下所示调用UserDetailsManager.updateUser()方法来更新给定用户的角色:
UserDetails oldDetails = userDetailsManager.loadUserByUsername(user);
UserDetails newDetails = new User(user, oldDetails.getPassword(), newRole);
userDetailsManager.updateUser(newDetails);