如何使用Spring Boot在Swagger标头中配置JWT令牌

时间:2020-03-31 09:24:08

标签: spring-boot jwt swagger

我已经在Spring Boot应用程序中配置了swagger,但是我不知道如何验证jwt授权令牌,而swagger版本是2.4.0

@Bean
public Docket newsApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .select()
            .apis(RequestHandlerSelectors.any())
            .paths(PathSelectors.any())
            .build()
            .securitySchemes(Lists.newArrayList(apiKey()))
            .securityContexts(Lists.newArrayList(securityContext()));

}

@Bean
SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.any())
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope
            = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Lists.newArrayList(
            new SecurityReference("JWT", authorizationScopes));
}

private ApiKey apiKey() {
    return new ApiKey("JWT", "Authorization", "header");
}

1 个答案:

答案 0 :(得分:0)

我今天在这个问题上苦苦挣扎,发现实际上还没有办法

您的代码已经足够完成此任务,只缺少一件事:在UI中添加令牌时,还需要在令牌之前添加“承载者”。

  1. 单击以添加您的授权: click to authorize
  2. 添加“承载者” +您的令牌: token with bearer

我还尝试将“ Bearer”添加到ApiKey,但是它也不起作用(因为它会生成双倍的“:”。

希望有帮助。