首页 > 解决方案 > 如何使用 Spring Boot 在 swagger 标头中配置 jwt 令牌

问题描述

我已经在 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");
}

标签: spring-bootjwtswagger

解决方案


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

您的代码已经足以完成这项任务,只是缺少一件事:当您在 UI 中添加令牌时,您还需要在令牌前添加“Bearer”。

  1. 点击添加您的授权: 点击授权
  2. 添加“不记名”+您的令牌: 带有不记名的令牌

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

希望能帮助到你。


推荐阅读