Anjana
Anjana

Reputation: 11

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?

Upvotes: 0

Views: 12145

Answers (3)

Nguyen Minh Thanh
Nguyen Minh Thanh

Reputation: 27

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.

Upvotes: 0

Caffeine Coder
Caffeine Coder

Reputation: 1196

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)

Upvotes: 1

argmnt
argmnt

Reputation: 89

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

Upvotes: 4

Related Questions