本文介绍了使用@PreAuthorize的多个角色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

要检查多个角色是否具有方法级别的访问权限

To check multiple roles has the method level access

我已经使用@PreAuthorize批注来检查角色

I have used @PreAuthorize annotation to check the role

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

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

如何使用@PreAuthorize注释检查多个角色?

How to check multiple roles using @PreAuthorize annotaion?

推荐答案

您可以创建自定义批注来验证许多角色和条件. P.e.:

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);

此注释验证用户是否以角色AGENT或ADMIN身份登录.如果用户具有CUSTOMER角色,请验证userId参数是否等于登录的用户

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

这篇关于使用@PreAuthorize的多个角色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 11:47