错误请求Alamofire + Basic Auth

时间:2017-03-27 13:53:19

标签: ios swift3 request alamofire basic-authentication

我正在尝试发出此请求,但只返回错误401,请求是否正确?我必须使用Basic Auth

    var user = ""
    var password = ""

    user = textField.text!
    password = textField2.text!

    print(user)
    print(password)


    let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
    print(credentialData)
    let base64Credentials = credentialData.base64EncodedString(options: [])
    print(base64Credentials)
    let headers: HTTPHeaders = ["Authorization":" Basic \(base64Credentials)"]

    print(headers)

    Alamofire.request("https://www.floratilemevidencia.com.br/wp-json/wp/v2/users/me", headers: headers)
        .validate().responseJSON { response in
            switch response.result {

            case .success:
                print("Validation Successful")
                let viewController: UIViewController = self.storyboard!.instantiateViewController(withIdentifier: "SideNavigationController")
                self.present(viewController, animated: true, completion: { _ in })

            case .failure(let error):
                print(error.localizedDescription)
                self.alertLabel.isHidden = false
            }
    }

它只返回错误401。

这是HTTPHeaders的正确部分吗?

2 个答案:

答案 0 :(得分:1)

对代码进行细微更改,它会起作用。

var user = ""
var password = ""

user = textField.text!
password = textField2.text!

print(user)
print(password)


let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
print(credentialData)

let base64Credentials = credentialData.base64EncodedString(options: [])
print(base64Credentials)

let url: String = "https://www.floratilemevidencia.com.br/wp-json/wp/v2/users/me"

var request = URLRequest(url:  NSURL(string: url)! as URL)
request.httpMethod = "GET"
request.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")

Alamofire.request(request)
    .validate().responseJSON { response in
        switch response.result {

        case .success:
            print("Validation Successful")
            // Your desired functionality

        case .failure(let error):
            print(error.localizedDescription)
            // Your desired functionality

        }
}

答案 1 :(得分:0)

最好让Alamofire生成你的标题。每https://github.com/Alamofire/Alamofire#authentication

修改

替换此代码块

let credentialData = ("\(user):\(password)").data(using: String.Encoding.utf8)!
print(credentialData)
let base64Credentials = credentialData.base64EncodedString(options: [])
print(base64Credentials)
let headers: HTTPHeaders = ["Authorization":" Basic \(base64Credentials)"]

var headers: HTTPHeaders = [:]

if let authorizationHeader = Request.authorizationHeader(user: user, password: password) {
    headers[authorizationHeader.key] = authorizationHeader.value
}