2017-03-16 677 views
1

我正在尝试使用Spring Boot设置RESTful API,并试图启用基本身份验证。我怎么一直打403访问被拒绝的错误?我在Postman中发送我的凭证作为标题(请参阅附图)。如果我删除.anyRequest.authenticated(),它工作正常。我不想删除,因为我想为每个端点进行基本认证。我究竟做错了什么?无法使用Spring Boot REST API设置基本身份验证

Application.java ​​

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"); 
    } 
} 

Controller.java
@RestController 
public class Controller { 

    @RequestMapping("/test") 
    public String index() { 
     return "Greetings from Spring Boot!"; 
    } 
} 

enter image description here

回答

3

在Spring文档中挖掘完毕后,似乎我明白每个链式方法调用都适用于什么。

无论如何,简单的答案是我需要.and().httpBasic()来启用基于我的REST API的基本HTTP认证。

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

See more.

相关问题