Flask 学习-52.Flask-RESTX 生成 Swagger 文档带上Authorization认证

283 篇文章 58 订阅

前言

我们在开发的接口中,一般会带上用户登录的token认证,需在请求头部传Authorization。
Flask-RESTX 生成 Swagger 文档,可以直接在文档上登录,方便快速测试接口。

需登录认证的接口

接着前面一篇,需要登录的接口加上@jwt_required()装饰器

from flask_jwt_extended import jwt_required

@api.route('/')
class TodoList(Resource):
    '''Shows a list of all todos, and lets you POST to add new tasks'''
    @api.doc(description='接口描述,描述接口在什么场景使用 list_todos')
    @api.marshal_list_with(todo)
    @jwt_required()
    def get(self):
        '''List all tasks'''
        return DAO.todos

在 Swagger 文档中测试该接口

会返回401

接下来我们看下,如何在文档中全局登录

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Swagger2 可以通过添加全局请求参数的方式来自动添加 Authorization 请求头。具体步骤如下: 1. 创建一个拦截器类,用于在请求头中添加 Authorization 参数。 ```java public class AuthInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { String token = "your_token_here"; request.addHeader("Authorization", token); return true; } // 省略其他方法 } ``` 2. 在 Swagger2 配置类中添加全局请求参数。 ```java @Configuration @EnableSwagger2 public class SwaggerConfig { @Autowired private AuthInterceptor authInterceptor; @Bean public Docket api() { return new Docket(DocumentationType.SWAGGER_2) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build() .apiInfo(apiInfo()) .globalOperationParameters(Collections.singletonList(new ParameterBuilder() .name("Authorization") .description("Authorization token") .modelRef(new ModelRef("string")) .parameterType("header") .required(true) .build())) .securityContexts(Collections.singletonList(SecurityContext.builder() .securityReferences(Collections.singletonList(SecurityReference.builder() .reference("Authorization") .scopes(new AuthorizationScope[0]) .build())) .build())) .securitySchemes(Collections.singletonList(new ApiKey("Authorization", "Authorization", "header"))); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("API") .description("API documentation") .version("1.0") .build(); } // 添加拦截器 @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(authInterceptor); } } ``` 在这里我们使用 `globalOperationParameters` 方法添加一个全局请求参数,该参数名为 `Authorization`,类型为 `header`,并且是必须的。我们还需要使用 `securityContexts` 和 `securitySchemes` 方法来配置 Swagger2 使用该参数作为授权信息。 当我们访问 Swagger2 文档时,会自动向请求头中添加 Authorization 参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值