Spring Security -尽管允许所有请求,但未经授权

oewdyzsn  于 2021-06-30  发布在  Java
关注(0)|答案(3)|浏览(243)

我在spring boot应用程序中有这样一个web配置:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests().anyRequest().permitAll()
        .and()
                .csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
                .httpBasic();
    }
}

尝试访问某个URL时(localhost:8080/test),我没有得到授权。我做错什么了?

ntjbwcob

ntjbwcob1#

我的枪是你的吗 WebConfig 没有放在正确的 Package 中。如果你的 @SpringBootApplication 注解类在 com.example.demo 然后你的 WebConfig 类应该放在 com.example.demo 包(或其他子包,例如: com.example.demo.config ).

package com.example.demo.config; // <-- move it to the (not-default) package

// skipped imports
// ...

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

    @Override
    protected void configure(HttpSecurity http) throws Exception {
      // config same as in the question's snippet
      // ...
    }
}
bvhaajcl

bvhaajcl2#

我的镜头与“.httpbasic();”有关,当您在属性中设置此项时,您似乎希望获得基本身份验证。

n3ipq98p

n3ipq98p3#

如果您获得未授权(401),则意味着身份验证失败,无论您是否有权访问资源。您使用的是basic auth,spring流有两部分,身份验证和授权,首先它进行身份验证,以了解用户是否有效,然后查看他们是否有权访问资源。在这种情况下,给出错误是因为它没有身份验证,更确切地说是401,如果您有身份验证但没有授权,您将收到403禁止

相关问题