簡體   English   中英

基於URL參數的Spring Security REST API角色

[英]Spring Security REST API roles based on URL parameters

我有一個使用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角色的用戶訪問,而無需手動指定所有項目?

此外,如果此機制具有特定名稱,請在評論中告訴我,我可以更改問題標題。

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

根據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 
  }
}

然后在Java安全配置中,您可以引用此方法並將相關路徑片段的值傳遞給它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM