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

为何请求中的Authorization Header会丢失?(FastAPI+Alamofire)

问题:Alamofire发送的Authorization Header未被FastAPI服务器接收

我在Xcode中使用Alamofire向FastAPI搭建的API发送请求,已配置JWT认证,但添加带Bearer Token的Authorization Header后,服务器未接收到该Header。其他Header能正常发送,且用Postman请求可正常完成认证,因此排除API本身问题。

请求代码

func getPosts() {
                 
        let headers: HTTPHeaders = [
            "Authorization":"Bearer \(UserDefaults.standard.object(forKey: "access_token") as! String)",
            "Content-type":"application/json"
        ]
        
        AF.request("\(mainURL)posts", method: .get, headers: headers).responseDecodable(of: Dictionary<String, String>.self) { response in
            debugPrint(response)
        }
        
}

Alamofire打印的请求日志

[Request]: GET http://127.0.0.1:8000/posts
    [Headers]:
        Authorization: Bearer xxxx
        Content-Type: application/json
    [Body]: None
[Response]:
    [Status Code]: 401
    [Headers]:
        Content-Length: 30
        Content-Type: application/json
        Date: Fri, 20 Jan 2023 23:27:48 GMT
        Server: uvicorn
        Www-Authenticate: Bearer
    [Body]:
        {"detail":"Not authenticated"}
[Network Duration]: 0.13030695915222168s
[Serialization Duration]: 0.0005600140430033207s
[Result]: success(["detail": "Not authenticated"])

服务器端打印的Header日志

Headers({'host': '127.0.0.1:8000', 'content-type': 'application/json', 'accept': '*/*', 'user-agent': 'APITest/1.0 (my-Name.APITest; build:1; iOS 16.2.0) Alamofire/5.6.4', 'accept-language': 'en;q=1.0', 'accept-encoding': 'br;q=1.0, gzip;q=0.9, deflate;q=0.8', 'connection': 'keep-alive'})

可能的解决办法

  • 更换请求地址
    模拟器请求127.0.0.1可能存在本地路由问题,尝试改用http://localhost:8000或者你的电脑局域网IP(如http://192.168.x.x:8000)发送请求。

  • 使用Alamofire内置的Authorization Header构造方法
    避免手动拼接Header,改用官方提供的方法确保格式正确:

    func getPosts() {
        guard let token = UserDefaults.standard.string(forKey: "access_token"), !token.isEmpty else {
            print("Token无效")
            return
        }
        
        let headers: HTTPHeaders = [
            .authorization(bearerToken: token),
            .contentType("application/json")
        ]
        
        AF.request("\(mainURL)posts", method: .get, headers: headers).responseDecodable(of: Dictionary<String, String>.self) { response in
            debugPrint(response)
        }
    }
    
  • 检查FastAPI的CORS配置
    确保FastAPI的CORS中间件允许Authorization Header通过:

    from fastapi import FastAPI
    from fastapi.middleware.cors import CORSMiddleware
    
    app = FastAPI()
    
    app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"],  # 生产环境替换为具体的iOS应用域名
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["Authorization", "Content-Type"],
    )
    
  • 安全获取UserDefaults中的Token
    避免强制类型转换导致的异常,改用可选绑定确保Token有效:

    guard let token = UserDefaults.standard.object(forKey: "access_token") as? String, !token.isEmpty else {
        print("Token不存在或为空")
        return
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 22:40:30