I am trying to understand some Spring security code. I am new to Spring Security as well and I guess I am missing here something basic.
I have that annotation on one of the classes:
@Controller
@RequestMapping("/download-resource")
@PreAuthorize(value="hasRole('LINKS_ADMIN')")
public class DownloadResourcesController extends BaseHtmlController
{..}
I read about the @PreAuthorize
and it's logic.
I still couldnt understand from where Spring security retrieves that defined role string : 'LINKS_ADMIN'
. Where is it defined?
thanks, ray.
Those roles are the roles (authorities) you assign to the UserDetails when a user logs in. These will be returned by an Authentication implementation.
They are one the form Collection<? extends GrantedAuthority>
, normally SimpleGrantedAuthority
is used.
For instance, in my application everyone is assigned to groups. So when a user logs in, I check all groups that user is a member of and add those to his user details.
for (Group group : groups) {
grantedAuthorities.add(new SimpleGrantedAuthority("ROLE_" + group.getName().toUpperCase()));
}
So if I have groups named "Admin", "User" and "Reporter" I can now check for has_role('ROLE_ADMIN')
, has_role('ROLE_USER')
and has_role('ROLE_REPORTER')
Under the hood it is retrieved from
SecurityContextHolder.getContext().getAuthentication().getAuthorities();
where getAuthentication()
returns the an instance of Authentication I linked to above, and you grab the authorities from that object.