簡體   English   中英

Spring Boot HttpSecurity - @PreAuthorize - 如何設置 AuthenticationFilter?

[英]Spring Boot HttpSecurity - @PreAuthorize - How to set AuthenticationFilter?

我目前正在開發 API 授權。 所以基本上我有一個過濾器JwtAuthorizationFilter 在我的 RestController 中,我想注釋應該通過@PreAuthorize("hasRole('ADMIN')")過濾的請求,例如。 所以我現在的問題是:我如何設置WebSecurityConfigureAdapter (或任何其他東西)以將注釋與 JwtAuthorizationFilter 鏈接起來?

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Basically permit every request, but if needed (through @PreAuthorize) check via JwtAuthorizationFilter)
    }
}

謝謝! 最好的問候塞巴斯蒂安

JwtAuthorizationFilter的目的應該是設置Authentication的授予權限。 然后,Spring Security 的默認方法 security 就足夠了。

你有幾個選擇:

使用 Spring Security 內置的 JWT 支持

如果 JWT 是由授權服務器創建的,那么Spring 安全的默認 JWT 支持可能就足夠了。 Spring 安全性隨附BearerTokenAuthenticationFilterJwtAuthenticationProvider 過濾器將解析Authorization header 以獲取令牌,提供者將驗證令牌並構建基於scopescp聲明的Authentication 在這種情況下,您會執行類似@PreAuthorize("hasAuthority('SCOPE_ADMIN')")

如果您需要自定義如何將 JWT 聲明轉換為GrantedAuthority ,那么您可以發布一個JwtAuthenticationConverter @Bean

有關完整的設置詳細信息,請查看Spring Security 的 OAuth 2.0 資源服務器示例 不過,基本上,您的配置如下所示:

http
    .authorizeRequests((authz) -> authz
        .anyRequest().authenticated()
    )
    .oauth2ResourceServer((oauth2) -> oauth2
        .jwt(Customizer.withDefaults())
    );

在沒有授權服務器的情況下使用 Spring Security 的內置 JWT 支持

Spring 安全的現有支持在設計時考慮了授權服務器,但這不是必需的。

您可以改為讓您的應用程序生成自簽名令牌

自己動手

您可以保留JwtAuthorizationFilter ,但不清楚為什么 Spring Security 的現有支持不足。 要添加過濾器,您只需執行addFilterBefore(myFilter, BearerTokenAuthenticationFilter.class) 您可以查看BearerTokenAuthenicationFilter作為創建您自己的過濾器時應考慮的一些事項的示例。

暫無
暫無

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

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