基于URL参数的Spring Security REST API角色

Mar*_*rga 4 java rest spring spring-security

我有一个使用Spring Security和OAuth2在Spring Boot中编写的REST API.资源以这种方式保护:

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

我想基于项目介绍API的新部分,其中权限是细粒度的.让我们考虑一个打印项目配置的简单端点.

GET /api/v1/project/{projectId}/config
Run Code Online (Sandbox Code Playgroud)

如何将资源服务器配置为仅允许具有该角色的用户访问ROLE_PROJECT_{projectId}_ADMIN而无需手动指定所有项目?

此外,如果此机制具有特定名称,请在评论中告诉我,我可以更改问题标题.

cju*_*gel 8

您可以在授权表达式中使用路径值.

根据Web安全性表达式中的路径变量,您应该编写自定义授权逻辑.

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 
  }
}
Run Code Online (Sandbox Code Playgroud)

然后在Java安全配置中,您可以引用此方法并将相关路径片段的值传递给它.

http.authorizeRequests()
  .antMatchers("/api/v1/project/{projectId}/config")
  .access("@webSecurity.checkUserHasAccessToProjectId(authentication,#projectId)")
  ...
Run Code Online (Sandbox Code Playgroud)