Difference between @Secured vs @RolesAllowed in Spring? And the concept of Role Based Security?

后端 未结 2 594
被撕碎了的回忆
被撕碎了的回忆 2021-02-07 11:44

I am studying Spring Security and I have the following doubts related the difference between the use of the @Secured annotation and the @RolesAllowed

2条回答
  •  逝去的感伤
    2021-02-07 12:26

    @Secured and @RolesAllowed are the same. They do the same operation in Spring.

    But

    • @RolesAllowed - Standard annotation of Java.

      Java has defined Java Specification Request, basically change requests for the Java language, libraries and other components. For the development of annotations, they have provided JSR 250. @RolesAllowed is included in it. This link contains further info in JSR 250

    • @Secured - Spring security annotation

    ROLE_MEMBER is the role which is set to the security user details.

    Refer this example from my current project. Here I'm using the user data object and mapping the roles given to the user to the security user details.

    public class CustomUserDetails implements UserDetails {
    ...
    ...
    ... 
    
        @Override
        public Collection getAuthorities() {
            Collection grantedAuthorities = new ArrayList();
            for (Role role : this.user.getRoles()){
                grantedAuthorities.add(new SimpleGrantedAuthority(role.getRole()));
            }
            return grantedAuthorities;
        }
    }
    

    These roles are then set for the security approvals using the @Secured or @RolesAllowed or @PreAuthorize("hasRole('ROLE_USER')") for the methods.

    By design it's good to put the security in the Service layer. So when I'm securing my service actions, I check for the roles, not for the users.

    This way, we can focus on the business logic and the security for the business logic via small security units called roles.

    Then I assign the roles to the user. Users can have multiple roles. So you have to see the relationship here. Users are given the roles. And roles are given the access to the business logic. Users are given the access to the business logic via the roles. This concept is called, Role Based Access Control.

    And in complex situations we can also manage hierarchical roles. Where one role has many other roles. But in the UserDetails, we have to flatten the role hierarchy and provide the list of roles to the Spring framework to process.

提交回复
热议问题