Swagger2 非全局、无需重复输入的Head参数(Token)配置

Swagger2 非全局、无需重复输入的Head参数(Token)配置

网络上关于Swagger2的教程多如牛毛,作为关于Swagger加入全局head参数(如token)的文章也很多。例如:

Swagger2 添加HTTP head参数

Swagger2 添加HTTP head参数,解决用户是token信息保留

但上述方案存在2个不足之处:

  1. 需要在每个接口下单独输入参数
  2. 全局配置了参数,如果某些接口(如login等)不需要参数,则必须在改接口中通过annotation现实声明,较为麻烦

综上,选择优化方案如下:

1.通过Swagger2的securitySchemes配置全局参数:如下列代码所示,securitySchemes的ApiKey中增加一个名为“Authorization”,type为“header”的参数。

 

1

2

3

4

 

private List<ApiKey> securitySchemes() {

return newArrayList(

new ApiKey("Authorization", "Authorization", "header"));

}

2.在Swagger2的securityContexts中通过正则表达式,设置需要使用参数的接口(或者说,是去除掉不需要使用参数的接口),如下列代码所示,通过PathSelectors.regex(“^(?!auth).*$”),所有包含”auth”的接口不需要使用securitySchemes。即不需要使用上文中设置的名为“Authorization”,type为“header”的参数。

 

1

2

3

4

5

6

7

8

 

private List<SecurityContext> securityContexts() {

return newArrayList(

SecurityContext.builder()

.securityReferences(defaultAuth())

.forPaths(PathSelectors.regex("^(?!auth).*$"))

.build()

);

}

设置完成后进入SwaggerUI,右上角出现“Authorization”按钮,点击即可输入我们配置的参数。
对于不需要输入参数的接口(上文所述的包含auth的接口),在未输入Authorization参数就可以访问。
其他接口则将返回401错误。点击右上角“Authorization”按钮,输入配置的参数后即可访问。参数输入后全局有效,无需每个接口单独输入。
image.png
至此,完成Swagger2 非全局、无需重复输入的Head参数配置。
Swagger2的相关完整代码如下(工程基于Springboot):

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

 

@Configuration

@EnableSwagger2

public class Swagger {

@Bean

public Docket api() {

return new Docket(DocumentationType.SWAGGER_2).

useDefaultResponseMessages(false)

.select()

.apis(RequestHandlerSelectors.any())

.paths(PathSelectors.regex("^(?!auth).*$"))

.build()

.securitySchemes(securitySchemes())

.securityContexts(securityContexts())

;

}

private List<ApiKey> securitySchemes() {

return newArrayList(

new ApiKey("Authorization", "Authorization", "header"));

}

private List<SecurityContext> securityContexts() {

return newArrayList(

SecurityContext.builder()

.securityReferences(defaultAuth())

.forPaths(PathSelectors.regex("^(?!auth).*$"))

.build()

);

}

List<SecurityReference> defaultAuth() {

AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");

AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];

authorizationScopes[0] = authorizationScope;

return newArrayList(

new SecurityReference("Authorization", authorizationScopes));

}

}

坚持原创技术分享,您的支持将鼓励我继续创作!

猜你喜欢

转载自blog.csdn.net/andyliulin/article/details/82049484
今日推荐