You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用jwt.get_unverified_header在Google Cloud Function中报错的问题

问题分析与解决

问题根源

Google Cloud Function(GCF)的HTTP触发器函数中,hello_http接收的event(实际是Flask的Request实例)和你本地测试时传入的参数完全不同:

  • 本地测试时,你应该是直接将JWT字符串/字节作为参数传给函数,符合jwt.get_unverified_header的参数要求;
  • 但在GCF中,这个参数是完整的HTTP请求对象,不是原始的JWT token,所以会触发Invalid token type错误。

解决方案

需要从HTTP请求中提取出JWT token,再传入JWT库处理。常见的提取方式有两种:

1. 从Authorization头提取Bearer Token

这是JWT最常用的传递方式:

@functions_framework.http
def hello_http(request):
    print('---------')
    # 获取Authorization请求头
    auth_header = request.headers.get('Authorization')
    if not auth_header or not auth_header.startswith('Bearer '):
        return '缺少有效Authorization头', 400
    
    # 拆分出JWT token部分
    jwt_token = auth_header.split('Bearer ')[1]
    # 转成bytes类型传入(jwt库也支持直接传str)
    jwt_header = jwt.get_unverified_header(jwt_token.encode('utf-8'))
    print(jwt_header)
    return '处理成功', 200

2. 从请求体提取JWT

如果你的JWT是放在请求体(比如JSON格式)中:

@functions_framework.http
def hello_http(request):
    print('---------')
    try:
        request_data = request.get_json()
        jwt_token = request_data.get('jwt_token')
        if not jwt_token:
            return '请求体中缺少jwt_token字段', 400
    except Exception:
        return '无效的JSON请求体', 400
    
    jwt_header = jwt.get_unverified_header(jwt_token.encode('utf-8'))
    print(jwt_header)
    return '处理成功', 200

额外说明

GCF的HTTP函数遵循Flask的请求处理逻辑,所有请求相关的信息(头、体、参数等)都需要从Request实例中获取,而不是直接拿到业务数据。本地测试时你跳过了请求解析步骤,直接传入了token,所以两者的参数类型不一致导致报错。

内容的提问来源于stack exchange,提问作者PiaklA

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:35:11