Spring Security: Set GrantedAuthorities

33,243

you can do it with following code:

Collection<SimpleGrantedAuthority> oldAuthorities = (Collection<SimpleGrantedAuthority>)SecurityContextHolder.getContext().getAuthentication().getAuthorities();
SimpleGrantedAuthority authority = new SimpleGrantedAuthority("ROLE_ANOTHER");
List<SimpleGrantedAuthority> updatedAuthorities = new ArrayList<SimpleGrantedAuthority>();
updatedAuthorities.add(authority);
updatedAuthorities.addAll(oldAuthorities);

SecurityContextHolder.getContext().setAuthentication(
        new UsernamePasswordAuthenticationToken(
                SecurityContextHolder.getContext().getAuthentication().getPrincipal(),
                SecurityContextHolder.getContext().getAuthentication().getCredentials(),
                updatedAuthorities)
);
Share:
33,243
mpmp
Author by

mpmp

Updated on July 04, 2020

Comments

  • mpmp
    mpmp almost 4 years

    Is there anyway to set the List<GrantedAuthority> in the Authentication/UserDetailsImpl object? In my application, I have two layers of security, one for logging in (which uses my custom login authenticator, in the class I set the Authentication object using the UsernamePasswordAuthenticationToken) and one for a "challenge question" where the user is prompted to answer a particular question.

    What I want to do is add a GrantedAuthority to the current List<GrantedAuthority>, which was created during the login process, after the user answers the challenge question.

    Is this possible?

  • Slavak
    Slavak almost 11 years
    Can't add to the collection -> UnmodifiableCollection
  • Spanky Quigman
    Spanky Quigman almost 11 years
    @Slavak That would really depend on what implementation you're using for UserDetails. We don't use the User class from org.springframework.security.core.userdetails in our implementation. Obviously if you need to set or modify the authorities, using an implementation where the collection is immutable and there's no setAuthorities() method (which is not promised on the UserDetails interface) would mean that the answer to the question is just no. No, that is not possible. Otherwise, you have to provide your own implementation of UserDetails, which is what most flexible apps need to do anyway.
  • John B
    John B almost 6 years
    The thing that sucks, is that it only works if you know the Authentication type that exists in the security context, in this case a UsernamePasswordAuthenticationToken.
  • gerard
    gerard over 4 years
    This only changes the authorities in the context, but not in the context's principal, if you try to get the authorities via SecurityContextHolder. getContext (). getAuthentication (). getPrincipal (). getAuthorities (), there won't be your updatedAuthorities, you have to set those into a new principal as well an then use it in the constructor of the authentication you're setting