Summary
- The authority in Spring Security is represented by
GrantedAuthorityinterface. - The
GrantedAuthorityhas only one method,#getAuthority(), which returns representation of authority as aString. GrantedAuthorityis stored inAuthenticationinstance by theAuthenticationManager, then used by theAccessDesicionManagerwhen making authorization decisions.- When the authority is complicated enough to represented as a
String,#getAuthority()should returnnull. - Then,
AuthorizationManagershould deal with the specialized authority. - There’s only one
GrantedAuthoritythat Spring Security provide:SimpleGrantedAuthority. - By default, role-based authorization rules include
ROLE_as a prefix. AuthorizationManageris responsible for both pre-authorization and post-authorization to secure objects.- The method authorization process in Spring Security is done by the interceptors, typically
AuthorizationManagerBeforeMethodInteceptorandAuthorizationManagerAfterMethodInterceptor, which utilizeAuthorizationManagerto control the access and secure the object. AuthorityAuthorizationManageris the most commonAuthorizationManager, which makes authority decision by checking whether there’re any matching authority stored inAuthenticationobject.- If you need a hierarchical role, use
RoleHierarchyto define role hierarchy as following:
@Bean
static RoleHierarchy roleHierarchy() {
return RoleHierarchyImpl.withDefaultRolePrefix()
.role("ADMIN").implies("STAFF")
.role("STAFF").implies("USER")
.role("USER").implies("GUEST")
.build();
}
// and, if using pre-post method security also add
@Bean
static MethodSecurityExpressionHandler methodSecurityExpressionHandler(RoleHierarchy roleHierarchy) {
DefaultMethodSecurityExpressionHandler expressionHandler = new DefaultMethodSecurityExpressionHandler();
expressionHandler.setRoleHierarchy(roleHierarchy);
return expressionHandler;
}