Spring Roles Security REST API Based on URL Parameters

I have a REST API written in Spring Boot with Spring Security and OAuth2. Resources are protected in this way:

@Override
public void configure(HttpSecurity http) throws Exception {
    http
            .authorizeRequests()
            .antMatchers("/api/v1/security/**").hasRole("ADMIN");
}

I would like to introduce a new part of the API in which permissions will have a dimension based on projects. Consider a simple endpoint that prints the configuration of a project.

GET /api/v1/project/{projectId}/config

How to configure the resource server to only allow access for users who have a role ROLE_PROJECT_{projectId}_ADMIN, without having to manually specify all the projects?

Also, if this mechanism has a specific name, let me know in the comments to change the title of the question.

+4
source share
1 answer

.

- .

public class WebSecurity {
  public boolean checkUserHasAccessToProjectId(Authentication authentication, int projectId) {
    // here you can check if the user has the correct role
    // or implement more complex and custom authorization logic if necessary 
  }
}

Java .

http.authorizeRequests()
  .antMatchers("/api/v1/project/{projectId}/config")
  .access("@webSecurity.checkUserHasAccessToProjectId(authentication,#projectId)")
  ...
+6

Source: https://habr.com/ru/post/1666195/


All Articles