首頁  >  文章  >  Spring Security 基於角色的授權問題:403 禁止錯誤

Spring Security 基於角色的授權問題:403 禁止錯誤

PHPz
PHPz轉載
2024-02-09 11:21:08635瀏覽

Spring Security 是一個功能強大的安全框架,用於保護應用程式免受惡意攻擊。在使用 Spring Security 過程中,角色的授權問題可能會引發 403 禁止錯誤。 php小編香蕉為您詳細介紹了這個問題,並提供了解決方案,幫助您順利解決角色授權的困擾。無論您是初學者還是有經驗的開發者,本文都將幫助您深入理解 Spring Security 的角色授權機制,並學會正確地處理 403 禁止錯誤。

問題內容

問題:

#我正在嘗試建立一個基於 spring 的 web 伺服器,並具有基於角色的身份驗證,但我始終收到 403 forbidden 錯誤。我已經實現了自訂 userdetails 類,我懷疑我的配置可能有問題。

程式碼:

自訂 userdetails:

public class customuserdetails implements userdetails {
    private static final long serialversionuid = 1l;
    private final user user;

    public customuserdetails(user user) {
        this.user = user;
    }

    @override
    public collection<? extends grantedauthority> getauthorities() {
        return user.getroles().stream().map(r -> new simplegrantedauthority("role_" + r.getname())).tolist();
    }

    // ... other userdetails methods
}

securityfilterchain 實作:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
    return http
        .csrf(csrf -> csrf.disable())
        .sessionManagement(sess -> sess.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .authorizeHttpRequests(requests -> requests
            .requestMatchers("/api/**").permitAll()
            .requestMatchers("/secret/**").hasAuthority("USER")
            .anyRequest().authenticated())
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults()))
        .addFilterBefore(authorizeFilter, UsernamePasswordAuthenticationFilter.class)
        .build();
}

我已經實作了一個自訂 userdetails 類別並配置了 spring security 以進行基於角色的身份驗證。但是,即使我相信角色已正確分配,我仍然遇到 403 forbidden 錯誤。我嘗試同時使用 hasrolehasauthority,但問題仍然存在。我的配置中缺少什麼?

任何見解或建議將不勝感激。謝謝!

解決方法

對於具有 JWT 的資源伺服器,權限由身份驗證轉換器設定。

預設的身份驗證轉換器是JwtAuthenticarionConverter,它將權限轉換委託給可設定的權限轉換器(預設使用scope 聲明中的條目新增SCOPE_ 前綴)。

您可以提供一個配置有另一個權限轉換器的 JwtAuthenticationConverter (一個使用另一個聲明作為權限來源),或者切換到完全不同的 Converter210850ab350a1f39cb90412976ec7000(oauth2-> oauth2.jwt(Jwt -> jwt.jwtAuthenticationConverter(...))

#您也可以考慮這個額外的啟動器我維護它使用一個可配置的權限轉換器應用程式屬性(除非您在conf中提供自己的權限或身份驗證轉換器)

您可以嘗試開啟spring的TRACE日誌並找出問題發生的位置。這個建議可能無法直接幫助你,但是確實幫助我們找到了遷移到Springboot3.0時API返回403的原因

以上是Spring Security 基於角色的授權問題:403 禁止錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除