Swagger和JWT令牌认证

5
我正在编写一些 Swagger 文档,一切顺利。但是我希望页面可以互动工作。例如,当选择编辑器或UI时,如果我点击授权按钮,我想调用我的身份验证 URL 来构建 JWT 令牌,然后在随后的请求中使用它。
我计划向 API 客户端发放 API 访问密钥和秘密访问密钥,并希望使用一个身份验证页面来处理这些密钥并构建 JWT 令牌。
我认为,如果我能正确地获得如何在 Swagger 中实现这一点的定义,那么我将拥有一个已经准备好的测试客户端,然后可以对我的全新代码进行测试。
没错,这是我第一次使用 JWT,而且我还没有编写过代码。你能说“API-First” 吗?

请查看此处:https://github.com/domaindrivendev/Swashbuckle#describing-securityauthorization-schemes - Alexandru Marculescu
2个回答

9

这是我如何在JWT身份验证中使用Swagger的方法:

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

securityDefinitions:  
  JWT:  
    type: apiKey  
    in: header  
    name: access_token  
  • 在 swagger.yaml 文件中的 paths:

  • security  
     -JWT: []
    

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

    • 在上述授权按钮被点击时,输入上面生成的JWT到弹出的认证窗口中
    • 现在JWT将会随请求头一同传递

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


    1
    但这是 API 密钥... - Polem

    4
    使用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加载完成后,您将能够看到“授权”按钮。

    enter image description here

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

    enter image description here


    非常感谢您展示带有“Bearer <token>”的图像。那个“Bearer”前缀确实有些棘手。 - Mc_Topaz

    网页内容由stack overflow 提供, 点击上面的
    可以查看英文原文,
    原文链接