Multiple roles using @PreAuthorize

后端 未结 3 1721
长发绾君心
长发绾君心 2021-01-13 13:37

To check multiple roles has the method level access

I have used @PreAuthorize annotation to check the role

@PreAuthorize(\"hasRole(\\\"\" + AuthoritiesCons

相关标签:
3条回答
  • 2021-01-13 13:55

    Simply combine roles by using && or || in SpEL expressions

    @PreAuthorize("hasRole('" + AuthoritiesConstants.USER + "')" +
                  " && hasRole('" + AuthoritiesConstants.ADMIN + "')" )
    
    0 讨论(0)
  • 2021-01-13 14:03

    @PreAuthorize("hasAnyRole('ROLE_ADMIN', 'ROLE_USER')")

    0 讨论(0)
  • 2021-01-13 14:06

    You can create a custom annotation to validate many roles and conditions. P.e.:

    @Retention(RetentionPolicy.RUNTIME)
    @PreAuthorize("hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_AGENT) " +
            "|| hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_ADMIN)" +
            "|| (hasRole(T(com.bs.dmsbox.api.constants.RoleConstants).ROLE_CUSTOMER) && #userId == principal.username)")
    public @interface IsAuthenticatedAsAgentOrCustomerIsUserId {
    }
    

    Then, you can use this annotation as below:

    @IsAuthenticatedAsAgentOrCustomerIsUserId
    Folder findByUserIdAndType(@Param("userId") String userId, @Param("typeId") FolderType id);
    

    This annotation validate that user logged as role AGENT or ADMIN. If user has role CUSTOMER validate if userId parameter is equals to user logged

    0 讨论(0)
提交回复
热议问题