Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.7k views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...