【问题标题】:Swagger and JWT Token AuthenticationSwagger 和 JWT 令牌认证
【发布时间】:2020-01-21 23:21:02
【问题描述】:

我正在构建一些 Swagger 文档,一切都很好,除了我希望页面以交互方式工作,所以在选择编辑器或 UI 时,如果我点击授权按钮,我会调用我的身份验证 URL 来构建然后在后续请求中使用的 JWT 令牌。

我计划向 API 客户端颁发一个 Api 访问密钥和一个秘密访问密钥,并希望访问一个身份验证页面,该页面将处理这些并构建 JWT 令牌。

令我震惊的是,如果我能在 Swagger 中正确定义如何实现这一点,我将拥有一个现成的测试客户端,然后可以针对我的新代码使用。

是的,这是我第一次使用 JWT,我还没有构建代码。你能说“API-First”吗?

【问题讨论】:

标签: rest authentication jwt swagger


【解决方案1】:

这就是我使用 Swagger 和 JWT 身份验证的方式:

  • 编写 Express.js API 端点以生成 JWT。
  • 创建一个 Swagger 路径以使用上述端点检索 JWT
  • 在 swagger.yaml 根级别:

    securityDefinitions:  
      JWT:  
        type: apiKey  
        in: header  
        name: access_token  
    
  • 在 swagger.yaml 路径中:

    security  
     -JWT: []
    

这将在浏览器的 Swagger UI 中显示一个授权按钮。

  • 在点击上面的Authorize按钮时弹出的Authentication窗口中输入上面生成的JWT
  • 现在 JWT 将与请求标头一起传递

希望这对其他人有所帮助。

【讨论】:

    【解决方案2】:

    Swagger 可以保存您的令牌并自动将令牌应用于您的所有请求。

    这是您需要添加到 Swagger Docket 配置中的内容:

    @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()))
                .apiInfo(generateApiInfo());
    }
    
    @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");
    }
    

    然后,当您的 Swagger UI 加载时,您将能够看到 Authorize 按钮。

    您可以保存您的令牌,请确保在您的令牌前面添加“Bearer”。

    【讨论】:

    • 非常感谢您展示带有“Bearer ”的图像。那个“Bearer”前缀很棘手。
    猜你喜欢
    • 2020-09-25
    • 2020-10-24
    • 2022-12-04
    • 2019-05-01
    • 2017-05-27
    • 2019-08-09
    • 2020-10-07
    • 2020-04-22
    • 2018-08-29
    相关资源
    最近更新 更多