I’m trying to access an API that’s demanding username/password credentials. My code is not correctly getting user credentials from user input and I’m receiving the error “Error copying matching creds. Error=-25300” with a status code “401”.
The postReq function looks like this:
func postRequest() {
let parameters = ["grant_type=authorization_code&code=xyz"]
guard let url = URL(string: "url to access") else {return}
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.addValue("xyz", forHTTPHeaderField: "X-API-Key")
request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.addValue("Basic base64(xyz:xyz)", forHTTPHeaderField: "Authorization")
guard let httpbody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else {return}
request.httpBody = httpbody
let session = URLSession.shared.dataTask(with: request) { (data, response, error) in
if let response = response {
print(response)
}
if let data = data {
do {
let json = try JSONSerialization.jsonObject(with: data, options: [])
print(json)
} catch {
print(error)
}
}
}
session.resume()
}
The delegate methods and helper method to get credentials look like this:
func urlSession(_ session: URLSession, task: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let authMethod = challenge.protectionSpace.authenticationMethod
guard authMethod == NSURLAuthenticationMethodHTTPBasic else {
completionHandler(.performDefaultHandling, nil)
return
}
//Call the completion handler
guard let credential = credentialFromUI() else {
completionHandler(.cancelAuthenticationChallenge, nil)
return
}
completionHandler(.useCredential, credential)
}
func credentialFromUI() -> URLCredential? {
guard let email = emailField!.text, !email.isEmpty,
let password = passField!.text, !password.isEmpty else {
return nil
}
return URLCredential(user: email, password: password, persistence: .forSession)
}
I’m having trouble getting user credentials from user input when accessing an API and receiving the error “Error copying matching creds. Error=-25300” with a status code “401”. My postReq function and the delegate methods and helper method to get credentials are provided.