swift - 在 iOS 上做 EVE SSO 授权失败
怪我咯
怪我咯 2017-04-17 15:25:06
0
1
678

我在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

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
刘奇

解决方案已找到。

在Alamofire中,Alamofire.Manager.sharedInstance()有一个默认的Additional Header,但是实践证明无法更改,必须自行创建Alamofire.Manager实例。解决方案代码如下:

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)    
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板