首页 > 解决方案 > 获取令牌和用户信息 iOS Swift

问题描述

我正在处理网络视图登录表单,我已经在网络视图中请求了 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"
        );
    } })

标签: iosswift

解决方案


错误的原因很可能是在字符串插值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)
                }
            }
        })
    }
}

推荐阅读