要求:
代码:已实施
@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");
}
}
但是此代码不起作用 - 您可以自由浏览 /swagger-ui.html#/ 而不需要任何身份验证。
问题是 - 为什么 BASIC 身份验证和用户不适用于 swagger ui 端点?
您应该使用
.authenticated()
而不是 .permitAll()
:
.authorizeRequests()
.antMatchers("/swagger-resources/*", "*.html", "/api/v1/swagger.json")
.hasRole("SWAGGER")
.anyRequest()
.authenticated()
这将:
限制对所有匹配
/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
换句话说,您向具有
SWAGGER
权限的用户授予完全访问权限,但您忽略的是,默认情况下,他们已经拥有访问权限。更准确地说,除非您另外指定,否则每个人都可以访问它。
通过使用.authenticated()
。您告诉 Spring 您希望所有匹配的请求仅限于具有正确
role
或
authority
的人。新配置:
.authorizeRequests() // allow requests
.antMatchers(...) // that matches this
.hasRole("SWAGGER") // with role SWAGGER
.anyRequest() // all requests above
.authenticated() // needs authentication
更新
/swagger-resources
、
/swagger-resources/configuration/security
和
swagger-resources/configuration/ui
返回 401 的问题:您应该将
/swagger-resources/*
替换为
/swagger-resources/**
。更新2
end处添加以下内容以允许所有不匹配的请求:
.authorizeRequests()
.anyRequest()
.permitAll();
大摇大摆
private List<SecurityScheme> basicScheme() {
List<SecurityScheme> schemeList = new ArrayList<>();
schemeList.add(new BasicAuth("basicAuth"));
return schemeList;
}
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.
.
.
.securitySchemes(basicScheme());
}
安全配置
public void configureGlobal(final AuthenticationManagerBuilder auth)
throws Exception {
auth.inMemoryAuthentication()
.withUser("USER")
.password("PASSWORD")
.roles("ADMIN");
}
.
.
.
@Override
protected void configure(final HttpSecurity httpSecurity) throws Exception {
httpSecurity.csrf().disable().authorizeRequests()
.anyRequest().authenticated().and().sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and().httpBasic();
}
.
.
.
@Override
public void configure(final WebSecurity web) throws Exception {
web.ignoring().antMatchers("/v2/api-docs",
"/configuration/ui",
"/swagger-resources/**",
"/webjars/**",
"/configuration/security",
"/swagger-ui.html");
}
控制器
@PutMapping("/registration/{id}")
@ApiOperation(value = "Update registration detail",
authorizations = { @Authorization(value="basicAuth") })
public ResponseEntity<RegistrationModel> updateRegistration(
聚甲醛
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
基本上就是这样。
public static void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.antMatcher("/swagger-ui.html")
.authorizeRequests()
.anyRequest().hasAnyRole("SWAGGER")
.and()
.httpBasic();
}
这确保了对
swagger-ui.html
路径的授权(具有
SWAGGER
角色)。
参考- Spring Boot 3 + 基本身份验证安全 + Swagger 示例
您遇到的问题可能是由于 Swagger UI HTML 文件及其关联资源是从与 API 端点不同的上下文提供的。默认情况下,Spring Security 不会将相同的安全规则应用于 HTML 文件等静态资源,除非明确配置这样做。
导入 org.springframework.beans.factory.annotation.Autowired; 导入 org.springframework.context.annotation.Configuration; 导入 org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; 导入 org.springframework.security.config.annotation.web.builders.HttpSecurity; 导入 org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 导入 org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
@EnableWebSecurity
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/swagger-ui.html", "/swagger-ui/**", "/v2/api-docs", "/swagger-resources/**", "/webjars/**")
.hasAuthority("SWAGGER")
.anyRequest().permitAll()
.and()
.httpBasic()
.and()
.csrf().disable();
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("{noop}admin").authorities("SWAGGER");
}
}