首页 > 解决方案 > HttpSecurity Spring Boot 配置

问题描述

我需要配置 3 个端点,2 个带身份验证,1 个不带。问题是我得到了所有带有 401 Unauthorized 错误的端点。

我正在使用依赖项:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

我实现了这个类:

@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
            .inMemoryAuthentication()
                .withUser("admin")
                    .password("pwd")
                    .roles("USER", "ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http
            .httpBasic()
                .and()
            .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/users").hasAnyRole("ADMIN", "USER")
                .anyRequest().permitAll()
                .and()
            .authorizeRequests()
                .anyRequest().hasAnyRole("ADMIN", "USER");
    }
}

标签: spring-bootspring-security

解决方案


根据您的要求,您只需要简单的 http 配置,所有用户都可以作为公共 url 访问 GET 用户,而其他需要基本身份验证的 ..below 将为您工作。

@Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .authorizeRequests()
                .antMatchers(HttpMethod.GET, "/users").permitAll()
                .anyRequest().authenticated()
                .and()
                .httpBasic();

    }

推荐阅读