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



我在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(时,我得到了Unauthorized。我做错了什么?

我认为您的WebConfig没有放在正确的包中。如果您的@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
// ...
}
}

我的镜头与"有关。httpBasic((&";,当您在属性中设置此项时,看起来您正在期待一个基本的身份验证。

如果您获得Unauthorize(401(,则意味着身份验证失败,无论您是否有权访问资源。您使用的是基本的auth,spring流有两个部分,身份验证和授权,首先它进行身份验证,以了解用户是否有效,然后查看他们是否有权访问资源。在这种情况下,错误是因为它没有身份验证,更广为人知的是401,如果你有身份验证但没有授权,你会收到403禁止

在我的情况下,我需要从属性文件中删除上下文路径。我删除了这个:

server.servlet.context-path=/api

在我去掉那个值之后,一切都很顺利。但是,我仍然不知道为什么它不适用于上下文路径。

相关内容

最新更新