Swagger/SpringDoc OpenAPI配置全局统一认证

直接上代码:

1、swagger配置方法:

@Configuration
public class SwaggerConfig {

    private static final String TOKEN_HEADER = "token";

    @Bean
    public Docket petApi() {

        List securitySchemes = singletonList(new ApiKey(TOKEN_HEADER, TOKEN_HEADER, "header"));
        List securityContexts = singletonList(
                SecurityContext.builder()
                        .securityReferences(securityReferences())
                        .operationSelector(operationContext -> true)
                        .build()
        );

        ApiInfo apiInfo = new ApiInfoBuilder()
                .title("fly admin api")
                .contact(new Contact("guoxiang", "null", "[email protected]"))
                .version("1.0")
                .build();

        return new Docket(DocumentationType.OAS_30)
                .apiInfo(apiInfo)
                .securitySchemes(securitySchemes)
                .securityContexts(securityContexts)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.fly.admin"))
                .build();
    }

    public List securityReferences() {
        AuthorizationScope[] authorizationScopes =
                new AuthorizationScope[]{new AuthorizationScope("global", "accessEverything")};

        SecurityReference reference = new SecurityReference(TOKEN_HEADER, authorizationScopes);
        return singletonList(reference);
    }

}


配置完成后,可以看到swagger页面出现:


image.png

点击authorize按钮,可以输入token,全局共享


image.png

2、 SpringDoc配置方法

    @Bean
    public OpenAPI customOpenAPI() {
        Contact contact= new Contact();
        contact.setName("eebd");

        OpenAPI openAPI = new OpenAPI().info(new Info().title("Title"));
        // oauth2.0 password
        openAPI.schemaRequirement(HttpHeaders.AUTHORIZATION, this.securityScheme());
        //全局安全校验项,也可以在对应的controller上加注解SecurityRequirement
        openAPI.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));

        return openAPI;
    }

    private SecurityScheme securityScheme() {
        SecurityScheme securityScheme = new SecurityScheme();
        //类型
        securityScheme.setType(SecurityScheme.Type.APIKEY);
        //请求头的name
        securityScheme.setName(HttpHeaders.AUTHORIZATION);
        //token所在未知
        securityScheme.setIn(SecurityScheme.In.HEADER);
        return securityScheme;
    }

或者在Controller层添加注解:

@SecurityRequirement(name = "这里填写你的schemaRequirement名字")

参考:https://springdoc.org/#how-do-i-add-authorization-header-in-requests

你可能感兴趣的:(Swagger/SpringDoc OpenAPI配置全局统一认证)