问题
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