Spring: 同时使用 Oauth2 和 HttpBasicAuth

Spring: Using Oauth2 and HttpBasicAuth together

我正在使用 Spring Boot 2.0.0

为了保护我的 REST API 我将 Oauth2 与 JWT 结合使用,效果非常好。

问题是:

我也在使用 Springfox Swagger,它应该受到 BasicAuth 的保护。这样,如果用户将浏览器指向 /swagger-ui.html,就会受到挑战 因此我得到了两个配置文件:

安全配置

@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Throws(Exception::class)
    override fun configure(web: WebSecurity) {
        web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**")
    }

    @Throws(Exception::class)
    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.inMemoryAuthentication()
                //user: "user", password: "Passw0rd!"
                .withUser("user")
                .password("$2a$04$DDYoNw1VAYt64.zU.NsUpOdvjZ3OVrGXJAyARkraaS00h322eL2iy")
                .roles("ADMIN")
    }
}

ResourceServerConfig

@Configuration
@EnableResourceServer
class ResourceServerConfig : ResourceServerConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        super.configure(http)
        http.httpBasic().and().cors().and().csrf().disable()
                .authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .antMatcher("/swagger-ui.html**")
                .authorizeRequests().anyRequest().hasRole("ADMIN")

    }
}

我认为这里不需要 OAuth2AuthorizationServerConfig

显示的配置(当然)不起作用,所以问题是: 是否可以混合使用 BasicAuth 和 Oauth2?

好的,我或多或少找到了问题的答案:

安全配置

@Configuration
@EnableWebSecurity
class SecurityConfig : WebSecurityConfigurerAdapter() {

    @Throws(Exception::class)
    override fun configure(auth: AuthenticationManagerBuilder) {
        auth.inMemoryAuthentication()
                //user: "user", password: "Passw0rd!"
                .withUser("user")
                .password("...")
                .roles("ADMIN")
    }

    override fun configure(http: HttpSecurity) {
        http.csrf()
                .and()
                .httpBasic()
                .and()
                .authorizeRequests()
                .antMatchers(
                        "/swagger-ui.html**").hasRole("ADMIN")
                .antMatchers(
                        "/v2/api-docs",
                        "/swagger-resources/**",
                        "/configuration/security", "/webjars/**"
                ).permitAll()
    }
}

ResourceServerConfig

@Configuration
@EnableResourceServer
class ResourceServerConfig : ResourceServerConfigurerAdapter() {

    override fun configure(http: HttpSecurity) {
        http.cors().and()
                .antMatcher("/api")
                .authorizeRequests().antMatchers("/api/**").authenticated()
    }
}

我在 ResourceServerConfig 中使用 antMatcher 来使用 oauth2 仅保护 /api/** 路径。

BasicAuth 部分发生在 SecurityConfig 中。 当前解决方案仅将 BasicAuth 应用于 /swagger-ui.html 端点。其他 swagger 资源 public 可见。

有谁知道同时保护 /v2/api-docs 的方法吗?

这都是关于将安全配置匹配到不同的应用程序上下文路径。请在 Run a Spring Boot oAuth2 application as resource server AND serving web content 查看我的回答 - 希望对您有所帮助。