请求头authorization_Swagger2添加Authorization请求头

  • Post author:
  • Post category:其他


Swagger中添加Authorization请求头需要配置securitySchemes和securityContexts。

@Configuration@EnableSwagger2public class Swagger2Config {    @Bean    public Docket docket() {        return new Docket(DocumentationType.SWAGGER_2)                .groupName("demo")                .apiInfo(apiInfo())                .select()                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))                .paths(PathSelectors.regex("/api/.*"))                .build()                # 增加Authorization请求头                .securitySchemes(securitySchemes())                .securityContexts(securityContexts());    }    private List securitySchemes() {        List apiKeys = new ArrayList<>();        apiKeys.add(new ApiKey("Authorization", "Authorization", "header"));        return apiKeys;    }    private List securityContexts() {        List securityContexts = new ArrayList<>();        securityContexts.add(SecurityContext.builder()                .securityReferences(defaultAuth())                .forPaths(PathSelectors.regex("^(?!auth).*$")).build());        return securityContexts;    }    private List defaultAuth() {        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];        authorizationScopes[0] = authorizationScope;        List securityReferences = new ArrayList<>();        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));        return securityReferences;    }}
1a0dfce4ef1dd0eec55f98b21c27ff3d.png
1a033bc062a3cde6bce5aa0302663820.png



版权声明:本文为weixin_35656580原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。