mpmp
mpmp

Reputation: 2459

Spring Security: Set GrantedAuthorities

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?

Upvotes: 39

Views: 48340

Answers (2)

ziggear
ziggear

Reputation: 944

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)
);

Upvotes: 49

Spanky Quigman
Spanky Quigman

Reputation: 890

The UserDetails.getAuthorities() method just returns a Collection<GrantedAuthority> object. You can use the appropriate Collection method to add your new authority to that collection.

Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
if (principal instanceof UserDetails) {
    ((UserDetails) principal).getAuthorities().add(New GrantedAuthorityImpl("ROLE_FOO"));
}

Selah.

Upvotes: -5

Related Questions