Я использую Spring Boot 2.0.0
Для защиты моего REST API я использую Oauth2 с JWT, который отлично работает.
Проблема в:
Я также использую Springfox Swagger, который должен быть защищен BasicAuth. Так что пользователю будет сложно, если он указывает в своем браузере на /swagger-ui.html Поэтому у меня есть два файла конфигурации:
SecurityConfig
@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?
Хорошо, я более-менее нашел ответ на свой вопрос:
SecurityConfig
@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()
}
}
Я использую antMatcher в ResourceServerConfig, чтобы защитить только пути / api / ** с помощью oauth2.
Часть BasicAuth происходит в SecurityConfig. Текущее решение применяет только BasicAuth только к конечной точке /swagger-ui.html. Другие ресурсы swagger доступны для всеобщего обозрения.
Кто-нибудь знает способ еще и защитить / v2 / api-docs?
Все дело в сопоставлении конфигураций безопасности с разными путями контекста приложения. См. Мой ответ на Запустите приложение Spring Boot oAuth2 в качестве сервера ресурсов И обслуживайте веб-контент - надеюсь, это поможет.