Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Security REST API roles based on URL parameters

I have a REST API written in Spring Boot with Spring Security and OAuth2. The resources are secured this way:

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

I'd like to introduce a new part of the API where the permissions are fine grained, based on projects. Let's consider a simple endpoint that prints the project configuration.

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

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

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

like image 791
MartinTeeVarga Avatar asked Jan 05 '23 19:01

MartinTeeVarga


1 Answers

You can use path values in authorization expressions.

According to Path Variables in Web Security Expressions you should write your custom authorization logic.

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 
  }
}

Then in your Java security configuration you can refer to this method and pass it the value of the relevant path fragment.

http.authorizeRequests()
  .antMatchers("/api/v1/project/{projectId}/config")
  .access("@webSecurity.checkUserHasAccessToProjectId(authentication,#projectId)")
  ...
like image 159
cjungel Avatar answered Jan 13 '23 09:01

cjungel