我在 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();
}
}
当尝试访问其中一个网址 (localhost:8080/test) 时,我收到未经授权的消息。我做错了什么?
最佳答案
我的猜测是,您的 WebConfig
是 not placed in the right 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
// ...
}
}
关于java - Spring Security - 尽管允许所有请求但未经授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65268745/