Cor*_*ndt 6 java spring swagger spring-boot springfox
要求:
代码:已实现
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-resources/*", "*.html", "/api/v1/swagger.json")
.hasAuthority("SWAGGER")
.anyRequest().permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("admin").authorities("SWAGGER");
}
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码不起作用 - 您可以在没有任何身份验证的情况下自由浏览 /swagger-ui.html#/。
问题是 - 为什么 BASIC auth 和 user 不适用于 swagger ui 端点?
您应该使用.authenticated()代替.permitAll():
.authorizeRequests()
.antMatchers("/swagger-resources/*", "*.html", "/api/v1/swagger.json")
.hasRole("SWAGGER")
.anyRequest()
.authenticated()
Run Code Online (Sandbox Code Playgroud)
这会:
限制对所有匹配资源的访问/swagger-resources/*,*.html以及/api/v1/swagger.json
允许未经身份验证访问所有其他资源
为了澄清为什么您的配置不起作用,这是因为您没有像您应该阅读的那样阅读 spring-security 。
您的旧配置如下所示:
.authorizeRequests() // allow requests
.antMatchers(...) // that matches this
.hasAuthority("SWAGGER") // with SWAGGER authority
.anyRequest() // All requests above
.permitAll() // grant full access
Run Code Online (Sandbox Code Playgroud)
换句话说,您授予具有SWAGGER权限的用户完全访问权限,但您忽略了默认情况下,他们已经可以访问它。更准确地说,除非您另有说明,否则每个人都可以访问它。
通过使用.authenticated(). 您告诉 Spring 您希望所有匹配的请求仅限于具有正确role或authority.
新配置:
.authorizeRequests() // allow requests
.antMatchers(...) // that matches this
.hasRole("SWAGGER") // with role SWAGGER
.anyRequest() // all requests above
.authenticated() // needs authentication
Run Code Online (Sandbox Code Playgroud)
关于您的问题/swagger-resources,/swagger-resources/configuration/security并swagger-resources/configuration/ui返回 401:
你应该替换/swagger-resources/*为/swagger-resources/**.
在配置末尾添加以下内容以允许所有不匹配的请求:
.authorizeRequests()
.anyRequest()
.permitAll();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14063 次 |
| 最近记录: |