gpt4 book ai didi

java - 将 Swagger Basic AUTH 添加到 Spring Boot 应用程序

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:45 25 4
gpt4 key购买 nike

要求:

  • 使用 Springfox 的 Spring Boot 应用程序
  • 为 Swagger 添加 BASIC 身份验证
  • 传递所有其他请求

代码:实现

@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/securityswagger-resources/configuration/ui返回 401:

您应该替换 /swagger-resources/*对于 /swagger-resources/** .

更新2

在配置的末尾添加以下内容以允许所有不匹配的请求:

.authorizeRequests()
.anyRequest()
.permitAll();

关于java - 将 Swagger Basic AUTH 添加到 Spring Boot 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50024317/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com