【问题标题】:How to fix the HTTP 401 error even though all requests are permitted in Spring Boot?即使在 Spring Boot 中允许所有请求,如何修复 HTTP 401 错误?
【发布时间】:2019-09-12 23:23:43
【问题描述】:

我是 Spring Boot 新手,一直致力于 Spring Security。我有一些暴露的 REST API 端点,在 Postman 上进行测试时可以达到这些端点。但是,一旦我添加了 spring-security 和 enablewebsecurity,我就无法访问端点,因为我收到 401 错误。

我尝试使用 web.ignore.antMatcher(HttpMethods.GET) 函数覆盖配置函数,但问题仍然存在。

@EnableWebSecurity
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter
{

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception
    {
        httpSecurity
                    .authorizeRequests()
                    .anyRequest()
                    .permitAll()
                    .and()
                    .httpBasic();

        httpSecurity.csrf().disable();

    }
}

预期结果:点击“/welcome”时返回的字符串。这在从依赖项中删除 spring security 并删除带有上述代码的配置文件时有效。

实际结果:401 错误。消息:未经授权。错误:未经授权

【问题讨论】:

  • 你确定SecurityConfiguration可以被spring扫描到吗?
  • 你能在 Github 上做一个最小的概念验证项目吗?
  • httpBasic() 是做什么的? ;)
  • @AlexanderPavlov httpBasic 允许使用基本身份验证,因此它允许我们发送用户名和密码来对我们进行身份验证。基本身份验证是 base64 编码

标签: spring-boot spring-security


【解决方案1】:

只需将 config 包和它的内容移动到 com.example.demo 包,因为现在它不在 Spring Boot 的扫描范围内。请参阅Structuring Your Code 文档。

这是一个典型的布局:

com
 +- example
     +- myapplication
         +- Application.java
         |
         +- customer
         |   +- Customer.java
         |   +- CustomerController.java
         |   +- CustomerService.java
         |   +- CustomerRepository.java
         |
         +- order
             +- Order.java
             +- OrderController.java
             +- OrderService.java
             +- OrderRepository.java

如您所见,主类和要扫描的包处于同一级别。

【讨论】:

  • 谢谢先生!这是一个愚蠢的错误,我应该更加警惕!无论如何,非常感谢!和平:)
猜你喜欢
  • 1970-01-01
  • 2017-08-07
  • 2016-01-31
  • 2021-11-15
  • 2020-12-09
  • 1970-01-01
  • 2019-05-30
  • 2019-05-25
  • 2018-09-07
相关资源
最近更新 更多