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

Alamofire POST请求带Token仍提示未提供认证凭证求助

Troubleshooting "Authentication credentials were not provided" in Alamofire 4.5 POST Request

Hey there, let's work through why you're hitting that authentication error even though you're including the Authorization header. Here are the key fixes and checks to resolve this:

1. You're not actually sending a POST request (critical!)

In Alamofire 4.x, the request method defaults to GET if you don't specify the HTTP method. Your code is missing the method: .post parameter, so you're sending a GET request instead of the intended POST. Many APIs enforce stricter authentication for POST endpoints, which explains the error even with a valid token.

Fix: Explicitly set POST method and correct encoding

Update your request to use POST explicitly, and ensure you're using JSON encoding (most APIs expect this for POST bodies):

@IBAction func accept(_ sender: Any) {
    var comm, cat, dist : String!
    comm = observationstwee.text!
    print(comm)
    let catd = 7
    cat = String(catd)
    print(cat)
    dist = distancetwee.text!
    print(dist)

    // Safely unwrap token to avoid crashes
    guard let validToken = token else {
        print("Error: Token is nil, can't authenticate")
        return
    }

    let parameters: Parameters = [
        "comment": comm,
        "category": cat,
        "distance": dist,
        "timestamp": time
    ]

    let headers: HTTPHeaders = ["Authorization": "Token \(validToken)"]
    print(headers.debugDescription)

    // Explicit POST request with JSON encoding
    Alamofire.request("https://llegoelbigotes.ubiqme.es/api/new-travel",
                      method: .post,
                      parameters: parameters,
                      encoding: JSONEncoding.default,
                      headers: headers)
        .responseJSON { response in
            switch(response.result) {
            case .success(let value):
                print("Full response: \(response)")
                print("Response data: \(value)")
                print("Correct Travel")
                // changeViewController(storyboard_name: "Main", viewcontroller_name: "tabBarController", context: self)
            case .failure(let error):
                print("FAILURE: \(error.localizedDescription)")
            }
        }
}

2. Verify your token's validity and format

  • Add a print statement to confirm your token is not empty or invalid:
    print("Current token value: \(token ?? "nil")")
    
  • Check your API documentation to confirm the auth header scheme. Some APIs use Bearer instead of Token (e.g., ["Authorization": "Bearer \(validToken)"]).

3. Confirm the Authorization header is being sent

Use a network debugging tool like Charles or Proxyman to capture the request and verify:

  • The request method is definitely POST
  • The Authorization header appears in the request headers with the correct value
  • All your parameters (comment, category, etc.) are present in the request body

4. Check for global Alamofire session overrides

If you're using a custom SessionManager elsewhere in your app, it might be stripping or overriding the headers you're passing. Ensure your custom session configuration doesn't modify request headers without your knowledge.


内容的提问来源于stack exchange,提问作者Pol Valls Ortiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 06:34:36