我正在使用 Spring Boot 2.5 創建一個 Restful API,并想知道在檢查某些路由的角色時實作驗證的正確方法。此外,對于某些路由,我需要確保只有管理員才能修改資源或其所有者。
@PreAuthorize似乎是解決方案,但@Valid似乎是在實際方法呼叫之前處理的,否則稱為之前執行@PreAuthorize。
請參閱:如何在我的控制器中驗證(@Valid)之前檢查安全訪問(@Secured 或 @PreAuthorize)?
這真的是使用 Spring Boot 和 Spring Security 制作具有驗證和角色的 Restful API的唯一可用且干凈的解決方案嗎?
uj5u.com熱心網友回復:
恐怕這是最干凈的解決方案。要檢查某些路由的角色,您可以配置您HttpSecurity在到達控制器之前檢查角色,如下所示:
@Bean
SecurityFilterChain app(HttpSecurity http) throws Exception {
http.authorizeHttpRequests((requests) -> requests
.antMatchers("/route1").hasAnyRole("ADMIN", "USER")
)
return http.build();
}
因此,通過此配置,您可以確保僅ROLE_USER或ROLE_ADMIN允許請求/route1.
但是現在,ROLE_USER只有當他們是資源所有者時才允許。為此,您必須決議方法引數才能知道您請求的是哪個資源。然后,在 中@PreAuthorize,您可以執行以下操作:
@PreAuthorize("@myBean.isResourceOwner(resourceId, authentication)")
@PutMapping("/{resourceId}")
public void update(@PathVariable Long resourceId) {
...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/366569.html
上一篇:你好,我在做一個學校專案,我試圖在PostgreSQL中使用SpringSecurity,我想從資料庫中獲取用戶,但我不知道出了什么問題
