java Spring Security在基本身份验证后抛出403

eqqqjvef  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(125)

我使用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)错误验证自己使用正确的用户名和密码.

请提出修改意见,使它工作。

up9lanfz

up9lanfz1#

您尚未启用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()
                .and()
                .authorizeRequests()
                    .anyRequest().authenticated();
    }

}
neekobn8

neekobn82#

更新

@Override
protected void configure(HttpSecurity http) throws Exception {
  http.csrf().disable().httpBasic().and().authorizeRequests().anyRequest().authenticated();
}

相关问题