1

I would like to change the role of the user. Changing role of the user in the database. Everything is based on Spring Security.

My code:

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

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

userDetailsManager.updateUser(user);

Error:

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

I don't know why is this error. How can otherwise change the role for the user?

mkjasinski
  • 3,115
  • 2
  • 22
  • 21

2 Answers2

1

You can update the role of a given user by creating a new UserDetails object from their existing one, then calling UserDetailsManager.updateUser() method as follows:

    UserDetails oldDetails = userDetailsManager.loadUserByUsername(user);
    UserDetails newDetails = new User(user, oldDetails.getPassword(),  newRole);
    userDetailsManager.updateUser(newDetails);
Hamid
  • 90
  • 1
  • 7
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
Community
  • 1
  • 1
hahn
  • 3,588
  • 20
  • 31