Swift+Alamofire带自定义Header调用Rest API遇授权问题求助
Hey there, let's figure out why your Swift + Alamofire request is failing when Postman works perfectly. Here are the most common issues to check, along with actionable fixes:
1. Fix the Authorization Header Format & Safety
First, many APIs require the Bearer keyword to be capitalized (not lowercase bearer). Postman might handle this automatically, but your code uses lowercase—this could be the immediate issue. Also, avoid force-unwrapping accessToken (those ! symbols) because it risks crashes if Session.user or accessToken is nil.
Update your header code to use safe unwrapping and correct capitalization:
guard let accessToken = Session.user?.accessToken else { let tokenError = NSError(domain: "Auth Error", code: -1, userInfo: ["msg": "Missing access token"]) errorBlock(tokenError) return } let requestHeaders: HTTPHeaders = [ "Authorization": "Bearer \(accessToken)" ]
2. Verify URL Case Sensitivity & Exact Match
Double-check that the URL in your code is identical to what you used in Postman. Some servers are case-sensitive for paths—for example, /api/StoreType/Stores vs /api/storetype/stores could be treated as entirely different endpoints. Confirm every character, including slashes and capitalization.
3. Bypass App Transport Security (ATS) for HTTP Requests
If your API uses HTTP (not HTTPS), iOS blocks the request by default. You'll need to add an exception in your Info.plist:
<key>NSAppTransportSecurity</key> <dict> <!-- Recommended: Allow only your target domain --> <key>NSExceptionDomains</key> <dict> <key>abcabc.com</key> <dict> <key>NSIncludesSubdomains</key> <true/> <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> <!-- Not recommended for production: Allow all HTTP loads --> <!-- <key>NSAllowsArbitraryLoads</key> <true/> --> </dict>
4. Debug the Exact Server Response
Your current code hides useful error details. Update the .failure case to log more context—this will tell you exactly what the server is sending back (like "invalid token" or "unauthorized"):
case .failure(let error): print("Error message: \(error.localizedDescription)") if let statusCode = response.response?.statusCode { print("Status code: \(statusCode)") } // Print raw server response to see hidden error messages if let data = response.data, let responseString = String(data: data, encoding: .utf8) { print("Server response: \(responseString)") } errorBlock(error)
5. Match Postman's Request Headers Exactly
Postman automatically adds headers like User-Agent or Accept that your Alamofire request might be missing. In Postman's Headers tab, copy all headers and add them to your requestHeaders in code. For example:
let requestHeaders: HTTPHeaders = [ "Authorization": "Bearer \(accessToken)", "Accept": "application/json", "User-Agent": "PostmanRuntime/7.32.3" // Match the value from Postman ]
6. Check Alamofire Version Compatibility
If you're using Alamofire 5.x or newer, the request syntax changed from Alamofire.request to AF.request. Make sure your code matches your installed version:
// For Alamofire 5+: AF.request("http://abcabc.com/api/StoreType/Stores", headers: requestHeaders).responseJSON { response in // ... your existing response handling code ... }
Start with these checks—most likely, the issue is either the authorization header case, a missing token, or ATS blocking the request. Let me know if you uncover the root cause!
内容的提问来源于stack exchange,提问作者Fakhar Zaman

