我有一个在 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/