2017-01-09 41 views
4

我有一個使用Spring Security和OAuth2在Spring Boot中編寫的REST API。該資源被固定這樣:基於URL參數的Spring Security 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用戶的訪問,而無需手動指定所有項目?

此外,如果此機制有一個特定的名稱,請讓我知道在評論中,我可以改變問題標題。

+0

如果您使用的是Spring MVC,那麼在控制器方法中放置'@ PreAuthorize'註釋通常是處理細粒度權限的最佳方式。 – chrylis

回答

6

您可以在授權表達式中使用路徑值。

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