【问题标题】:Spring Security REST API roles based on URL parameters基于 URL 参数的 Spring Security REST API 角色
【发布时间】:2017-05-23 05:02:56
【问题描述】:

我有一个使用 Spring Security 和 OAuth2 用 Spring Boot 编写的 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 角色的用户访问,而无需手动指定所有项目?

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

【问题讨论】:

  • 如果您使用 Spring MVC,在控制器方法上添加 @PreAuthorize 注释通常是处理细粒度权限的最佳方式。

标签: java spring rest spring-security


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-19
    • 2012-04-11
    • 2016-07-08
    • 2016-10-14
    • 2020-12-18
    • 2016-07-01
    • 2019-08-08
    • 2018-11-28
    相关资源
    最近更新 更多