Alamofire Invalidate credential

杀马特。学长 韩版系。学妹 提交于 2019-12-12 03:44:44

问题


I'm using Alamofire to do a simple request

Alamofire.request(.GET, URL)
     .authenticate(user: user, password: password)                       
     .responseJSON { response in
         ...
}

After a first valid request, I changed the credential with invalid ones and the request succeed, but it should fail.

How can I invalidate previous credentials?

After a successful request, if I change the credential, Alamofire authenticates the previous credential.

How can I invalidate previous credentials?


回答1:


I experienced exactly the same thing. iOS's answer should work, anyway I will provide code snippet using swift3 for someone to reduce research time.

let user = "aaaaa"
let password = "myPassword"

let plainString = "\(user):\(password)"
let plainData = plainString.data(using: .utf8)
let base64String = plainData?.base64EncodedString(options:NSData.Base64EncodingOptions(rawValue: 0))

let authString = "Basic " + base64String!

// Set in in Authorize header like...
let headers: HTTPHeaders = [
        "Authorization": authString,
        "Accept": "application/json"
    ]

// And use it like this..
Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
        debugPrint(response)
    }

Here is where this case was discussed >> https://github.com/Alamofire/Alamofire/issues/32




回答2:


Adding Authorization header helped me.

let user = "user"
let password = "password"

let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])

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

Alamofire.request(.GET, "https://httpbin.org/basic-auth/user/password", headers: headers)
         .responseJSON { response in
             debugPrint(response)
         }


来源:https://stackoverflow.com/questions/36693329/alamofire-invalidate-credential

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