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

标签 java spring spring-security basic-authentication

我使用 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) 错误。

enter image description here

请建议修改以使其正常工作。

最佳答案

您还没有启用 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();
    }

}

关于java - 基本身份验证后 Spring Security 抛出 403,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41567640/

相关文章:

java - springframework.core.io.Resource 总是抛出 java.io.FileNotFoundException

java - 使用 @PreAuthorize 注释 setter 会不会太残酷?

java - java中的Stringbuilder追加方法 queryStr.append(\\%AMP AMP\\$);

java - 有哪些使用 Spring 和 Hibernate 的优秀示例应用程序?

javascript - Spring、Thymeleaf 和异步数据加载

spring - 自定义Spring Security过滤器链返回404

java - 如何使用 Spring 安全性和 Restful Web 服务验证数据库中的凭据?

java - 有没有比 Await 更好的使用 CountUpDownLatch 的方法?

Java 8 流并从调用 boolean 方法设置属性

java - is not abstract and does not override abstract method 错误