使用 Swagger UI 的基本身份验证

Abh*_*hek 2 java rest spring swagger-ui spring-boot

我正在尝试通过 Swagger UI 使用 API 文档开发基于 spring-boot 的 rest API 服务。我想通过 swagger UI 启用基本身份验证,以便用户只能在他/她使用 swagger UI 上的授权按钮进行身份验证后才能运行 API(通过该按钮将"authorization: Basic XYZ标头添加到 API 调用

在前端(在 Swagger UI 的 .json 文件中,我使用以下代码(根据文档)为所有 API 添加了基本身份验证:

"securityDefinitions": {
        "basic_auth": {
            "type": "basic"
        }
    },
    "security": [
        {
            "basic_auth": []
        }
    ]
Run Code Online (Sandbox Code Playgroud)

我应该如何为上述用例实现后端逻辑(用户只能在他/她使用 swagger UI 上的授权按钮进行身份验证后才能运行 API,否则在运行 API 时会显示 401 错误)

一些文档或相同的示例代码会有所帮助

Sif*_*fis 8

一种选择是使用浏览器弹出授权

  1. 当您为 Spring Boot 应用程序启用基本身份验证时,swagger ui 将自动使用浏览器的弹出窗口,以便将其用于基本身份验证。这意味着浏览器将保留发出请求的凭据,就像您尝试访问安全的 GET 端点一样,直到您关闭它。

现在,假设您不想使用上述内容,并希望像您所说的那样使用swagger-ui 进行基本身份验证,您必须在 swagger-ui 上启用身份验证功能,并在访问 swagger-ui url 时可选择添加安全异常。

  1. 要启用基本身份验证功能来 swagger UI (使用UI 中的“授权按钮”),您必须将安全上下文和方案设置为您的 Swagger Docket(这是一个简化版本):

    @Configuration
    @EnableSwagger2
    public class SwaggerConfig implements WebMvcConfigurer{
    
        @Bean
        public Docket api() {
            return new Docket(DocumentationType.SWAGGER_2)
                    .select()
                    .apis(RequestHandlerSelectors.any())
                    .paths(PathSelectors.any())
                    .build()
                    .securityContexts(Arrays.asList(securityContext()))
                    .securitySchemes(Arrays.asList(basicAuthScheme()));
       }
    
        private SecurityContext securityContext() {
            return SecurityContext.builder()
                    .securityReferences(Arrays.asList(basicAuthReference()))
                    .forPaths(PathSelectors.ant("/api/v1/**"))
                    .build();
        }
    
        private SecurityScheme basicAuthScheme() {
            return new BasicAuth("basicAuth");
        }
    
        private SecurityReference basicAuthReference() {
            return new SecurityReference("basicAuth", new AuthorizationScope[0]);
        }
    
    }
    
    Run Code Online (Sandbox Code Playgroud)

这将启用 ui 中的授权按钮。 在此处输入图片说明

现在您可能希望您的用户自由访问 swagger-ui并使用此按钮进行授权。为此,您必须为应用程序的基本身份验证免除 swagger。此配置的一部分是安全配置,您必须添加以下代码:

public class SecurityConfig extends WebSecurityConfigurerAdapter{

    @Override
    protected void configure(HttpSecurity http) throws Exception {

            http
                .httpBasic()
                .and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)   
                .and().authorizeRequests()
                .antMatchers(
                        "/", "/csrf", 
                        "/v2/api-docs", 
                        "/swagger-resources/**",
                        "/swagger-ui.html",
                        "/webjars/**"
                        ).permitAll()
                .anyRequest().authenticated();

    }
}
Run Code Online (Sandbox Code Playgroud)