簡體   English   中英

為什么我在使用 Spring Security 6、permitAll 和禁用 CSRF 后得到 401?

[英]Why am I getting a 401 when using Spring Security 6, permitAll and after disabiling CSRF?

有一些類似的問題,所以我已盡力表示差異,但我已經審查過它們,但它們似乎與我的問題不符。

我有一些簡單的用例......

Given I am a user 
And I am not authenticated
When I use a GET request
Then I get a 200 response

Given I am a user 
And I am not authenticated
When I User a POST request
Then I get a 401 response

我嘗試像這樣使用 spring 安全性來讓它工作......

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize
                .requestMatchers(HttpMethod.GET).permitAll()
                .anyRequest().authenticated()
        ).csrf().disable();
        return http.build();
    }

但是當我運行並嘗試使用 GET 請求http://localhost:8080時,我仍然得到 401。如果我從 POM 中刪除所有依賴項,那么它會返回給我一個 200。

我錯過了什么我需要什么才能在沒有令牌的情況下允許請求通過?

我也試過這個...

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests((authorize) -> authorize
                .anyRequest().permitAll()
        ).oauth2ResourceServer( OAuth2ResourceServerConfigurer::jwt );
        return http.build();
    }

但這也提供了一個 401

您提供的第一個安全配置旨在匹配“每個 GET 請求”。 方法簽名是requestMatchers(HttpMethod method, String... patterns) 您的用法省略了模式,因此匹配“沒有請求是 GET”。

注意:我真的很驚訝該方法允許您不為patterns參數傳遞任何參數。 也許這是一個有價值的增強建議。

在您的示例中,您可以這樣做:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeHttpRequests((authorize) -> authorize
                .requestMatchers(HttpMethod.GET, "/**").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
        return http.build();
    }

}

注意:您確實需要至少指定一種身份驗證機制,而您的配置缺少這種機制。

這似乎工作...

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers("/").permitAll()
                        .anyRequest().authenticated()
                )
                .oauth2ResourceServer(oauth2 -> oauth2
                        .jwt(Customizer.withDefaults())
                );
        return http.build();
    }

暫無
暫無

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

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