iOS Alamofire不正确的授权标头 [英] iOS Alamofire Incorrect Authorization Header

查看:89
本文介绍了iOS Alamofire不正确的授权标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这样的问题,即Alamofire向服务器发送请求时使用了错误的授权标头.

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

我第一次使用用户名和密码,一切正常.然后,如果我快速更改用户名和密码,然后以其他用户的身份重试该请求,则该请求将完全失败.当我在iOS控制台中打印HTTP标头时,每次都是正确的.但是,当我的服务器打印标题时,它与我在iOS控制台上打印的标题不同.

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.

如果我在更改用户之前等待了几分钟,它似乎可以正常工作.但是,如果我在一分钟内完成此操作,那么在iOS设备上打印的授权标头将与服务器收到的授权标头不同.因此,它使用的是旧的授权信息,而不是新的授权信息.

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)
        }
    }
}

因此,如果我第一次调用此函数,它将正常工作. base64LoginString是正确的,并且与服务器收到的内容匹配.如果我注销并输入其他用户信息,则base64LoginString不同于原始的,正确的是预期的.但是,该请求在发送到服务器时仍然具有旧的base64LoginString值,而不是新的.因此,即使我们现在已经以第二个用户身份登录,服务器也会为第一个用户返回信息.

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.

因此,在打印base64LoginString和服务器接收请求之间的某处失败.几乎就像它缓存了标头之类的东西,根本没有任何意义.

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.

我也使用Node,Express和Passport.js来处理Web请求和后端的身份验证,以供参考.让我知道是否可以提供更多信息以帮助您.

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.

推荐答案

不确定是否与您的情况相同,但就我而言,缓存结果是由Cookie引起的.在执行身份验证请求之前(例如,当用户退出时)删除所有cookie可以为我工作.我想这可能是您的问题,因为我正在执行登录请求的后端也正在使用Node和Express.

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.

您可以尝试以下代码删除所有cookie:

You can try this code to remove all cookies:

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

这篇关于iOS Alamofire不正确的授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆