Multiple roles using @PreAuthorize

浪尽此生 提交于 2020-12-10 07:54:12

问题


To check multiple roles has the method level access

I have used @PreAuthorize annotation to check the role

@PreAuthorize("hasRole(\"" + AuthoritiesConstants.USER + "\",)" )

How to check multiple roles using @PreAuthorize annotaion?


回答1:


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




回答2:


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

@PreAuthorize("hasRole('" + AuthoritiesConstants.USER + "')" +
              " && hasRole('" + AuthoritiesConstants.ADMIN + "')" )



回答3:


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



来源:https://stackoverflow.com/questions/57247649/multiple-roles-using-preauthorize

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!