获取令牌和用户信息iOS Swift

时间:2019-05-31 11:05:14

标签: ios swift

我正在使用Web视图登录表单,并且已经在Web视图中请求了URL,并且成功登录后,我获得了授权码。现在要获取令牌,我正在尝试使用该代码,但看起来它的状态码为400。

如何获取访问令牌?希望这种方法应该是正确的;我不知道哪里出了问题。

super.viewDidLoad()      
        let url = URL(string: "https://***/oauth2/authorize?scope=openid&response_type=code&redirect_uri=\(REDIRECT_URI)&client_id=\(CLIENT_ID)")
        let request = URLRequest(url: url!)
        webView.load(request)
        self.webView.navigationDelegate = self

    }
  func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

        if let url = webView.url?.absoluteString{
            print("url = \(url)")

            let queryItems = URLComponents(string: url)?.queryItems
            authCode = queryItems?.filter({$0.name == "code"}).first
            sessionState = queryItems?.filter({$0.name == "session_state"}).first

            print("CODE VALUE IS",authCode?.value as Any)
            print("SESSION STATE VALUE IS",sessionState?.value as Any)


           let headers = ["content-type": "application/x-www-form-urlencoded"]
            let postData = NSMutableData(data: "grant_type=\(GRANT_TYPE)".data(using: String.Encoding.utf8)!)
            postData.append("&client_id=\(CLIENT_ID)".data(using: String.Encoding.utf8)!)
            postData.append("&client_secret=\(CLIENT_SECRET)".data(using: String.Encoding.utf8)!)
            postData.append("&code=\(String(describing: authCode?.value))".data(using: String.Encoding.utf8)!)
            postData.append("&redirect_ui=\(REDIRECT_URI)".data(using: String.Encoding.utf8)!)

            let request = NSMutableURLRequest(url: NSURL(string: TOKEN_URL)! as URL,
                                              cachePolicy: .useProtocolCachePolicy,
                                              timeoutInterval: 10.0)
            print("POSTDATA",postData.debugDescription)


           request.httpMethod = "POST"
           request.allHTTPHeaderFields = headers
            request.httpBody = postData as Data

            let session = URLSession.shared
            let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
                if (error != nil) {
                    print(error as Any)
                } else {
                    let httpResponse = response as? HTTPURLResponse

                    print("Response is",httpResponse as Any)
                }
            })

            dataTask.resume()
        }

}
}

响应:

Response is Optional(<NSHTTPURLResponse: 0x600000230a60> { URL: https://account.eziemall.com/oauth2/token } { Status Code: 400, Headers {
        "Content-Length" =     (
            82
        );
        "Content-Type" =     (
            "application/json"
        );
        Date =     (
            "Fri, 31 May 2019 11:03:42 GMT"
        );
        Server =     (
            "nginx/1.13.5"
        );
        "Set-Cookie" =     (
            "AWSALB=1Kah/jnLt4LFWcdh26U0DF9Jmf3IjVmSpKleCr9tNyq28wjoRANlQ6DSWcYGtMnWRJfBCQ0N7cMOpganMOaYVNzmoqp7vDyONPA1nwnYVdD9vJctwDAt7MB96xlf; Expires=Fri, 07 Jun 2019 11:03:42 GMT; Path=/"
        );
        "x-content-type-options" =     (
            nosniff
        );
        "x-xss-protection" =     (
            "1; mode=block"
        );
    } })

1 个答案:

答案 0 :(得分:0)

错误的原因很可能是可选的authCode?.value,它在字符串插值中添加了文字"Optional(

在第一行if let中解开可选部分。

这是摆脱丑陋的 objective-c-ish NSMutable...类的改进版本

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

    if let url = webView.url?.absoluteString, let authCodeValue = authCode?.value {
        let headers = ["content-type": "application/x-www-form-urlencoded"]
        var postString = "grant_type=\(GRANT_TYPE)"
        postString += "&client_id=\(CLIENT_ID)"
        postString += "&client_secret=\(CLIENT_SECRET)"
        postString += "&code=\(authCodeValue)"
        postString += "&redirect_uri=\(REDIRECT_URI)"

        var request = URLRequest(url: URL(string: TOKEN_URL)!)
        request.cachePolicy = .useProtocolCachePolicy
        request.timeoutInterval = 10.0
        request.httpMethod = "POST"
        request.allHTTPHeaderFields = headers
        request.httpBody = Data(postString.utf8)

        let session = URLSession.shared
        let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
            if let error = error {
                print(error)
            } else {
                if let httpResponse = response as? HTTPURLResponse {
                    print("Response is", httpResponse)
                }
            }
        })
    }
}