简体   繁体   中英

Role based authorization in spring boot

I am new to Spring boot. I need to implement role based authorization in spring boot. I am having different roles and multiple users will be mapped to each role. I will be setting different access (read, add, delete, edit) Whenever an api gets called, need to check the access and allow permission. I am planning to use interceptor to call method having the query to get the access from DB and deny or access the api. Is there any other better way I can use for the same?

If you are using Spring Security you can handle it with method security annotations like @PreAuthorize , @PostAuthorize .. even combine them to new annotations.

First your User need to implements UserDetails then you should implement getAuthorities() method according to your Role and Authority structure Spring Security basically checks what getAuthority() method returns if returned value prefixed with "ROLE_" like "ROLE_ADMIN" it will be processed as ROLE if it does not prefixed with "ROLE_" it will be processed as Authority you can use method annotation for checking authority and role like following example:

@PreAuthorize("hasRole('ROLE_ADMIN') and hasAuthority("READ")") 

and Spring Security will check your granted Authorities by getAuthorities() implementation of your User then, according to your annotation it will be checked automatically by Spring Security behalf of you.

For clarity you can check https://www.baeldung.com/spring-security-granted-authority-vs-role

For quick working implementation you can check article below(I would not directly use it but you can understand the idea. Also you can use permissions but simple solution probably the solution below.):

https://www.baeldung.com/role-and-privilege-for-spring-security-registration

For authorization, there can be these two ways as well:

  1. OAuth (Reference - https://medium.com/@bvulaj/mapping-your-users-and-roles-with-spring-boot-oauth2-a7ac3bbe8e7f )
  2. Spring Security Roles and Privileges(Reference- https://www.baeldung.com/role-and-privilege-for-spring-security-registration )

You can create a custom annotation to handle request for each role. I you can read this article for more details about how to implement.

And in api will have format:

@GetMapping(...)
@YouCustomAnnotation("roleName")
public void doSomeThing(){
}

This api will be called if role of user matched with role define in annotation and server will return 404 code if user's role not match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM