Spring boot 返回 401-未经授权,即使我已经允许了

问题描述 投票:0回答:2

我正在尝试通过 Postman 访问我的 API。在配置中,我已将 /authenticate 设置为允许,但我总是收到 401 未经授权。

相关功能:

@Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity
                // dont authenticate this particular request
                .authorizeRequests().antMatchers("/authenticate").permitAll().
                // all other requests need to be authenticated
                        anyRequest().authenticated().and().
                // make sure we use stateless session; session won't be used to
                // store user's state.
                        exceptionHandling().authenticationEntryPoint(jwtAuthenticationEntryPoint).and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        // Add a filter to validate the tokens with every request
        httpSecurity.addFilterBefore(jwtRequestFilter, UsernamePasswordAuthenticationFilter.class);
    }

我的依赖项

<dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
        <version>2.3.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>io.jsonwebtoken</groupId>
        <artifactId>jjwt</artifactId>
        <version>0.9.1</version>
    </dependency>
</dependencies>

如有任何帮助,我们将不胜感激

java spring spring-boot authentication postman
2个回答
0
投票

这里的问题是,即使您将 Spring Security 配置为允许每个用户,您的请求也会通过与其他请求相同的安全链。我猜测您对身份验证端点的调用在授权标头中不包含任何内容,或者换句话说,您的令牌为空,因此您会得到 401。在这种情况下,一种解决方案可以是对 spring 说安全性,对于用于身份验证的 URL,请求不会通过安全链。您可以在 Spring Security 配置中使用以下代码来实现这一点。

@Override
public void configure(WebSecurity web) throws Exception {
    web.ignoring().antMatchers("/authenticate");
}

我希望这可以解决您的问题。


0
投票

当向不需要身份验证的端点发送请求时,在 Postman 或 Insomnia 的身份验证类型中选择“无身份验证”。

© www.soinside.com 2019 - 2024. All rights reserved.