Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 772
mpmp Avatar asked Feb 05 '13 16:02

mpmp


People also ask

How do I set authorities in Spring Security?

getAuthorities() method just returns a Collection<GrantedAuthority> object. You can use the appropriate Collection method to add your new authority to that collection. Selah. @Slavak That would really depend on what implementation you're using for UserDetails.

What is GrantedAuthority in Spring Security?

Represents an authority granted to an Authentication object. A GrantedAuthority must either represent itself as a String or be specifically supported by an AccessDecisionManager .

What is Spring Security UserDetails?

Interface UserDetails. Provides core user information. Implementations are not used directly by Spring Security for security purposes. They simply store user information which is later encapsulated into Authentication objects.

How does Spring Security Hasrole work?

By default, Spring Security uses a thread-local copy of this class. This means each request in our application has its security context that contains details of the user making the request. To use it, we simply call the static methods in SecurityContextHolder: Authentication auth = SecurityContextHolder.


1 Answers

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) ); 
like image 76
ziggear Avatar answered Sep 20 '22 17:09

ziggear