在 Springfox Swagger 中为 OAuth2 身份验证添加自定义 header

Add a custom header to OAuth2 authentication in Springfox Swagger

我正在尝试向 OAuth 安全方案 (Springfox Swagger 2.8.0) 添加自定义 header。 有什么想法可以实现吗?

我当前的配置(使用 OAuth 和 ImplicitGrant,服务器端是 keycloak)如下所示:

@Bean
public SecurityContext securityContext() {
    return SecurityContext.builder().securityReferences(defaultAuth()).build();
}

private List<SecurityReference> defaultAuth() {
    return Arrays.asList(new SecurityReference(SECURITY_SCHEME_OAUTH2, defaultScope().toArray(new AuthorizationScope[] {})));
}
private Predicate<String> postPaths() {
    return regex("/.*");
}

private Predicate<String> springBootActuatorJmxPaths() {
    return regex("^/(?!env|restart|pause|resume|refresh).*$");
}

private List<AuthorizationScope> defaultScope() {
    AuthorizationScope authorizationScope = new AuthorizationScope("openid", "Basic Open ID Connect Scope");
    List<AuthorizationScope> authorizationScopes = new ArrayList<>();
    authorizationScopes.add(authorizationScope);
    return authorizationScopes;
}

@Bean
public Docket postsApi(List<SecurityContext> securityContexts) {
    return new Docket(DocumentationType.SWAGGER_2).groupName("public-api")
            .apiInfo(apiInfo()).select().paths(postPaths())
            .apis(RequestHandlerSelectors.basePackage("com.example"))
            .paths(springBootActuatorJmxPaths())
            .build()
            .securitySchemes(Collections.singletonList(oauth()))
            .securityContexts(securityContexts)
            ;
}
@Bean
List<GrantType> grantTypes() {
    List<GrantType> grantTypes = new ArrayList<>();
    grantTypes.add(
            new ImplicitGrant(
                    new LoginEndpoint(oAuthServerUri + "/realms/" + REALM_NAME + "/protocol/openid-connect/auth"),
                    "access_token"
            )
    );
    return grantTypes;
}

@Bean
SecurityScheme oauth() {
    return new OAuthBuilder()
            .name(SECURITY_SCHEME_OAUTH2)
            .scopes(defaultScope())
            .grantTypes(grantTypes())
            .build();
}

@Bean
public SecurityConfiguration securityInfo() {
    return SecurityConfigurationBuilder.builder()
            .clientId(clientId)
            .realm(REALM_NAME)
            .appName(serviceName)
            .scopeSeparator(" ")
            .build();
}

目前在 Springfox Swagger 中是不可能的,更多细节在这里:https://github.com/springfox/springfox/issues/2266