无法使用 Spring Boot REST API 设置基本身份验证

Sti*_*cky 1 spring spring-security spring-boot

我正在尝试使用 Spring Boot 设置 RESTful API,并且我正在尝试启用基本身份验证。为什么我一直遇到 403 Access Denied 错误?我将我的凭据作为 Postman 中的标头发送(见附图)。如果我删除.anyRequest.authenticated(),它工作正常。我不想删除它,因为我希望每个端点都进行基本身份验证。我究竟做错了什么?

Application.java

@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}
Run Code Online (Sandbox Code Playgroud)

SecurityConfiguration.java

@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/h2-console/*").permitAll()
                .anyRequest().authenticated();

        http.csrf().disable();
        http.headers().frameOptions().disable();
    }

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .inMemoryAuthentication()
                .withUser("user").password("password").roles("USER");
    }
}
Run Code Online (Sandbox Code Playgroud)

Controller.java

@RestController
public class Controller {

    @RequestMapping("/test")
    public String index() {
        return "Greetings from Spring Boot!";
    }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Sti*_*cky 7

在 Spring 文档中挖掘之后,我似乎理解每个链式方法调用的用途。

无论如何,简单的答案是我需要.and().httpBasic()通过我的 REST API 启用基本 HTTP 身份验证。

.anyRequest().authenticated()只是强制要求每个请求都经过身份验证,但没有指定使用什么方法。添加基本​​身份验证意味着我们可以使用基本身份验证来验证用户。

查看更多。