2015-09-01 170 views
1

環境:Swift 2,iOS 9使用Alamofire時的令牌無效

我已經推出了自己的HTTP網絡庫。它沒有壞掉,但我決定修復它並轉向Alamofire。

這裏是我的代碼片段:

case .HTTPTokenAuth: // Token Auth 

    let dictionary = Locksmith.loadDataForUserAccount("Auth_Token", inService: "KeyChainService") 
    let token = dictionary!.valueForKey("access_token") 

    var aManager = Manager.sharedInstance 
    aManager.session.configuration.HTTPAdditionalHeaders = ["Authorization": "Bearer \(token!)" ] 
    aManager.request(method, requestURL!, parameters: parameters, encoding: .JSON).response { request, response, data, error in 

    print("===== Request ================") 
    print(request!.allHTTPHeaderFields!) 
    print("===== Response ================") 
    print(response!.allHeaderFields) 
    print("===== Error ================") 
    print(error) 

    } 

的問題是,由於某種原因,OAuth令牌不使它成爲了頭部。 (至少,這是什麼似乎是問題,因爲我沒有看到它在請求頭我收到以下請求/響應:

===== Request ================ 
["Content-Type": "application/json"] 

===== Response ================ 
[Content-Type: application/json, 
Www-Authenticate: Bearer realm="Doorkeeper", 
error="invalid_token", 
error_description="The access token is invalid", 
Pragma: no-cache, X-Runtime: 0.002205, 
X-Powered-By: Phusion Passenger 4.0.14, X-XSS-Protection: 1; mode=block, Server: nginx/1.6.2 + Phusion Passenger 4.0.14, 
Transfer-Encoding: Identity, 
Cache-Control: no-store, 
Date: Tue, 01 Sep 2015 18:54:16 GMT, 
X-Request-Id: 395d2154-5054-423c-a7bc-f7ef85e0cdbf, 
Connection: keep-alive, 
X-Content-Type-Options: nosniff, 
X-UA-Compatible: chrome=1, 
Status: 401 Unauthorized, 
X-Frame-Options: SAMEORIGIN] 
+0

不要在會話配置HTTPAdditionalHeaders屬性中設置'Authorization',而是在個別請求中設置它。 – mattt

+0

謝謝,我誤解了文檔中有關將未更改的頭信息放入會話配置的註釋。 – Andy

回答

0

我用簡單的方法去:

case .HTTPTokenAuth: // Token Auth 

    let dictionary = Locksmith.loadDataForUserAccount("Auth_Token", inService: "KeyChainService") 
    let token = dictionary!.valueForKey("access_token") 
    let headers = ["Authorization":"Bearer \(token!)"] 

    Alamofire.request(method, requestURL!, parameters: parameters, headers: headers, encoding: .JSON) 
      .response { request, response, data, error in 

    print(request!.allHTTPHeaderFields!) 
    print(response) 
    print(error) 

    }