Alamofire POST请求带Token仍提示未提供认证凭证求助
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
Bearerinstead ofToken(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
Authorizationheader 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

