iOS Alamofire Incorrect Authorization Header

随声附和 提交于 2019-12-23 01:57:21

问题


I'm having this issue where Alamofire is using an incorrect authorization header when sending a request to my server.

The first time I use the username and password and everything works fine. Then if I change the username and password quickly and retry the request as a different user it completely fails. When I print the HTTP headers in the iOS console it is correct every time. But when my server prints the headers it's different then the headers I printed on the iOS console.

If I wait a couple of minutes before changing users it seems to work fine. But if I do it within a minute the authorization header that is printed on the iOS device is different then the one the server receives. So it's using the old authorization information not the new one.

Below is the code I'm using.

func reloadData() {
    print("Reloading data!!")   
    let keychain = KeychainSwift()

    let email: String = keychain.get("email")!
    let password: String = keychain.get("password")!

    URLCache.shared.removeAllCachedResponses()

    let sessionManager = Alamofire.SessionManager.default
    sessionManager.session.configuration.requestCachePolicy = .reloadIgnoringLocalCacheData


    let loginString = String(format: "%@:%@", email, password)
    let loginData = loginString.data(using: String.Encoding.utf8)!
    let base64LoginString = loginData.base64EncodedString()

    print(base64LoginString)

    let headers: HTTPHeaders = ["Authorization": "Basic \(base64LoginString)"]



    sessionManager.request("http://IPHERE:3000/api/items", headers: headers).validate().responseJSON { response in
        switch response.result {

        case .success(let value):

            let json = JSON(value)
            print("JSON: \(json)")

            for item in json.array! {

                let title: String? = item["title"].stringValue
                self.titles.append(title!)
                self.colors.append(UIColor.blue)
            }

            self.tableView.reloadData()

        case .failure(let error):
            print ("My Error")
            print (error)
            let alertController = UIAlertController(title: "Error", message: "Error, please try again or contact support", preferredStyle: UIAlertControllerStyle.alert)
            let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (result : UIAlertAction) -> Void in
            }
            alertController.addAction(okAction)
            self.present(alertController, animated: true, completion: nil)
        }
    }
}

So if I call this function the first time it works fine. base64LoginString is correct and matches what the server receives. If I logout and enter a different users information, base64LoginString is different then the original which is correct and is expected. But that request when it gets sent to the server still has the old base64LoginString value instead of the new one. So the server returns the information for the first user even tho we are now logged in as the second user.

So somewhere between printing base64LoginString and the server receiving the request something fails. It's almost like it caches the headers or something, which doesn't make sense at all.

Also for reference I'm using Node, Express, and Passport.js to handle web requests and auth on the backend. Let me know if I can provide any more information to help out.


回答1:


Not sure if its your same scenario but in my case the cache result was caused for a cookie. By removing all the cookies before doing the authentication request (E.g when the user signs out) worked for me. I guess it could be your issue since the backend I'm doing the sign in requests are also using Node and Express.

You can try this code to remove all cookies:

let cookieStore = HTTPCookieStorage.shared
for cookie in cookieStore.cookies ?? [] {
    cookieStore.deleteCookie(cookie)
}


来源:https://stackoverflow.com/questions/42448677/ios-alamofire-incorrect-authorization-header

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!