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

标签 java spring rest spring-security

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

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

我想介绍 API 的一个新部分,其中权限根据项目细化。让我们考虑一个打印项目配置的简单端点。

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

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

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

最佳答案

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

根据 Path Variables in Web Security Expressions您应该编写自定义授权逻辑。

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)")
  ...

关于java - 基于 URL 参数的 Spring Security REST API 角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41539484/

相关文章:

spring - Spring MVC 中应用程序级别的 Bean 应该放在哪里?

c# - 使用 WebClient 进行 POST 查询和下载文件

python - Python 分布式应用程序中的持久架构

java - 无法以编程方式连接到蓝牙设备

Java Regex BBCode 不会取代,但

使用 this() 的 Java 构造函数链接

java - Spring中的组件如何扫描?是将所有对象初始化为单例还是延迟初始化?

java - MPAndroidChart:为 Y 轴提供一些偏移量

java - spring boot proguard 警告 : there were 184 classes in incorrectly named files

java - 使用JERSEY和JACKSON解析未知结构的POST请求