search

Home  >  Q&A  >  body text

swift - 在 iOS 上做 EVE SSO 授权失败

我在iOS上做 EVE Online 的 SSO授权:

首先跳转至网页进行登录并回调:

swiftUIApplication.sharedApplication().openURL(NSURL(string: "https://login.eveonline.com/oauth/authorize?response_type=code&redirect_uri=eve%3A%2F%2Fcallback&client_id=97501bccc99b40b69b349dc7277621d8&scope=publicData")!)

用户被定向至Safari登录完成后,由预先定义的 URL Scheme 返回应用,并附带用于授权的code:

swiftfunc parseScheme(url: NSURL) ->Bool {
        var authCode = ""

        if let params = url.query {

            for param in params.componentsSeparatedByString("&") {

                let pair = param.componentsSeparatedByString("=")

                if pair[0] == "code" {
                    authCode = pair[1]
                    print("Code: \(authCode)", appendNewline: true)
                    CRest.sharedInstance.verifyAuthCode(authCode)
                }
            }
        }

        return true
    }

取得code后,向服务器发送授权验证请求:

swiftfunc verifyAuthCode(code: String) {
     let authStrBuff = CLIENT_ID + ":" + CLIENT_SECRET

     let authData = authStrBuff.dataUsingEncoding(NSUTF8StringEncoding)

     let authStr = authData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding76CharacterLineLength).stringByReplacingOccurrencesOfString("\r\n", withString: "")

     let headers = ["Authorization": "Basic " + authStr!,
                     "Content-Type": "application/x-www-form-urlencoded",
                             "Host": "login.eveonline.com"]

     let params = ["grant_type": "authorization_code",
                         "code": code]

     Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders = headers
     Alamofire.request(.POST, URLString: "https://login.eveonline.com/oauth/token", parameters: params).responseJSON { (req, res, JSON, err) -> Void in
         if let e = err {
             print(e, appendNewline: true)
         }

         print("\(JSON)", appendNewline: true)
     }
}

但是按照流程走下来之后授权失败,最终打印JSON结果如下:

{
    error = "invalid_client";
    "error_description" = "Unknown client";
}

求解答0.0

怪我咯怪我咯2772 days ago680

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-04-17 15:27:06

    Solution found.

    In Alamofire, Alamofire.Manager.sharedInstance() has a default Additional Header, but practice has proven that it cannot be changed, and you must create an Alamofire.Manager instance yourself. The solution code is as follows:

    var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders as! [String: String]
    for (key, value) in headers {
        defaultHeaders[key] = value
    }
    
    let config = NSURLSessionConfiguration.defaultSessionConfiguration()
    config.HTTPAdditionalHeaders = defaultHeaders
    authManager = Alamofire.Manager(configuration: config)
    
    authManager.request(.POST, "xxxxx", parameters: params, encoding: ParameterEncoding.URL)    
    

    reply
    0
  • Cancelreply