我使用Spring Security进行基本身份验证来保护我的REST API。
以下是配置代码:
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user")
.password("password")
.roles("admin");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.anyRequest().authenticated();
}
}
我在使用正确的用户名和密码验证自己时遇到了禁止(403)错误。
请建议修改以使其正常工作。
答案 0 :(得分:6)
您尚未启用HTTP基本身份验证,您必须使用HttpSecurity.httpBasic()
@Configuration
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
@Autowired
public void configureGlobalSecurity(AuthenticationManagerBuilder auth) throws Exception{
auth.inMemoryAuthentication().withUser("user").password("password").roles("admin");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.httpBasic()
.authorizeRequests()
.anyRequest().authenticated();
}
}
答案 1 :(得分:0)
已更新
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().httpBasic().and().authorizeRequests().anyRequest().authenticated();
}