在 iOS 上做 EVE SSO 授权失败
我在iOS上做 EVE Online 的 SSO授权 :
首先跳转至网页进行登录并回调:
swift
UIApplication.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:
swift
func 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后,向服务器发送授权验证请求:
swift
func 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
詹姆斯·邦德
9 years, 10 months ago
Answers
解决方案已找到。
在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)
mikicn
answered 9 years, 10 months ago