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

iOS Swift中如何给请求Header加AccessToken?遇401令牌无效错误

解决Header中AccessToken导致的401无效/过期错误

错误响应信息

Status Code: 401

{"response":{"success":"false","result":{"errorCode":"4012001002","message":"Invalid token / expired."}}}

问题分析

你的代码中存在两个核心问题导致401错误:

  1. Token格式错误:使用String(describing: tokens)会将Optional类型的包装字符(如Optional("your_real_token"))一起传入Header,服务器无法识别这种格式的token,直接判定为无效。
  2. 数据解析逻辑错误:response.result.success返回的data是Data?类型,无法直接强制转换为[TicketResponse],需要用Alamofire的解码API处理。

修复方案及代码

修正后的代码

import UIKit
import Alamofire
import SwiftKeychainWrapper

class HelpViewController: UIViewController {
    var ticketResult = [TicketResponse]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        HistoryAPI()
    }
    
    func HistoryAPI() {
        // 安全获取Keychain中的token,避免Optional干扰
        guard let token = KeychainWrapper.standard.string(forKey: "accessToken") else {
            print("无法从Keychain读取accessToken")
            return
        }
        
        print("当前使用的AccessToken: \(token)")
        
        let headers: HTTPHeaders = [
            "content-type": "application/json",
            "correlationId": "myYt005",
            "operation": "ticketDetail",
            "destination": "CRM",
            "source": "WEB",
            "srDate": "16-05-2022",
            "token": token // 直接传入纯token字符串
        ]
        
        // 使用Alamofire的解码API处理响应数据
        AF.request(ticketHistory_url, method: .get, headers: headers)
            .responseDecodable(of: [TicketResponse].self) { response in
                debugPrint(response)
                switch response.result {
                case .success(let ticketData):
                    self.ticketResult = ticketData
                case .failure(let error):
                    print("请求/解析失败: \(error.localizedDescription)")
                }
            }
    }
}

额外排查点

  • 确认Keychain中存储的accessToken是服务器颁发的有效、未过期的字符串,可通过打印token值对比验证。
  • 检查服务器要求的token请求头字段名是否正确:部分服务器要求使用Authorization字段(如Bearer格式:"Authorization": "Bearer \(token)"),若你的接口遵循此规范,需修改对应Header字段。
  • 确认srDate等其他Header参数的格式符合服务器要求,避免因其他参数错误间接导致401。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 16:06:30