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

标签 java spring spring-boot spring-security unauthorized

我在 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) 时,我收到未经授权的消息。我做错了什么?

最佳答案

我的猜测是,您的 WebConfignot 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/

相关文章:

java - 如何检索多个选择值?

java - Hibernate更新实体不知道主键

用于类的特定属性的 Spring/Grails 自定义属性编辑器

java - 如何从 JPA 中的父实体检索子数据

java - 重载包含不同路径变量类型的 RestController 方法

Java JTabbedPane 和 stateChanged 事件,getTabCount() 有错误?

java - 如何从java数组中删除和添加元素

json - Spring @ResponseBody 为原始类型生成无效的 JSON

java - JPA实体和DTO属于Service层还是Spring Repository层

java - MongoDB 存储不正确的 DOB