经过身份验证的HTTP请求快速Alamofire [英] Authenticated http request swift Alamofire

查看:112
本文介绍了经过身份验证的HTTP请求快速Alamofire的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力使其能够向我的API发出请求。如果没有令牌,那么对我来说,当我尝试添加其他标头时,事情就变得很复杂。

I'm struggling with getting this to work to make request to my API. Without a token works, but when I try to add additional headers, things turn to be complicated, for me.

首先,结构。
一个称为: APIAsyncTask 的类,它发出请求

First, the structure. one class called: APIAsyncTask that makes the requests

一个称为 APIParams 的类,只是一个数据将参数发送到 APIAsyncTask 类的所有者。

one class called APIParams, just a data holder to send parameters to the APIAsyncTask class.

一个名为 DatabaseAPI 的类,该类用于构建参数,以及将其发送到 APIAsyncTask 类。

one class called DatabaseAPI that makes that builds the parameters, and send that to the APIAsyncTask class.

DatabaseAPI

func someMethod()
{
    let task = APIAsyncTasks()
    task.registerCallback { (error, result) -> Void in
        print("Finished task, back at DatabaseAPI")
    }
    let params2 = APIParams(request: .GET, apiPath: "Posts/1", apiToken: "4iTX-56w")
    task.APIrequest(params2)
}

APIAsyncTask

此部分用于修复另一个错误,因为管理器不是全局的,因此任务被迅速取消。

This part is for fixing another error, because manager was not global, the task got cancelled quickly.

var manager : Manager!

init(authenticatedRequest : Bool, token: String?)
{
    manager = Alamofire.Manager()
    print("Pre \(manager.session.configuration.HTTPAdditionalHeaders?.count)")
    if(authenticatedRequest && token != nil)
    {
        var defaultHeaders = Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders!   
        defaultHeaders["Authorization"] = "bearer \(token)"
        let configuration = Manager.sharedInstance.session.configuration
        configuration.HTTPAdditionalHeaders = defaultHeaders

        manager = Alamofire.Manager(configuration: configuration)
    }
    print("Post \(manager.session.configuration.HTTPAdditionalHeaders?.count)")
}

经过一番决策后,这又归结为这一部分。

After some decision making, it comes down to this part.

 private func GetRequest(url: String!,token : String?, completionHandler: (JSON?, NSURLRequest?, NSHTTPURLResponse?, NSError?) -> () ) -> ()
{
    print("Begin Get Request")

    if(token != nil)//if token is not nil, make authenticated request
    {
        print("just before request: \(manager.session.configuration.HTTPAdditionalHeaders?.count)")
        manager.request(.GET, url, parameters: nil, encoding: .JSON).responseJSON { (request, response, json, error) in
            print("Get Request (authenticated), inside alamofire request")
            var resultJson : JSON?
            if(json != nil)
            {
                resultJson = JSON(json!)
            }
            completionHandler(resultJson, request, response, error)
        }
    }
    else
    {
     //working part without token

因此,就像现在的代码一样,我在完成时遇到错误:

So as the code is now, I get an error on completing:

使自己哑气给出使用 Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders
的答案
,这样就可以了...

Mattt himself gives the answer of using Alamofire.Manager.sharedInstance.session.configuration.HTTPAdditionalHeaders , so that should be fine...

我怀疑它与多线程有关,根据博客。或者,由于它与CFNetwork有关,可能是因为我的API不使用SSL?我禁用了NSAppTransportSecurity

I suspect it has something to do with the multiple threads, according to this blog. Or, since it is something about CFNetwork, it could be because my API does not use SSL? I disabled NSAppTransportSecurity

我是个新手,所以我不胜感激!谢谢!

I'm kind of new to swift, so examples would be really appreciated! Thankyou!

推荐答案

因此,您的大部分代码看起来都很稳定。

So the majority of your code looks solid.

该错误使我相信CFNetwork很难弄清楚如何计算挑战的保护空间。我还假定您由于附加了 Authorization 标头而遇到了基本的身份验证挑战。

The error leads me to believe that CFNetwork is having difficulty figuring out how to compute the protection space for the challenge. I would also assume you are getting a basic auth challenge since you are attaching an Authorization header.

考虑到更多逻辑,这使我看到您没有将令牌正确地附加到 Authorization 标头。您需要执行以下操作。

Digging through your logic a bit more with this in mind led me to see that your not attaching your token to the string properly inside the Authorization header. You need to do the following instead.

defaultHeaders["Authorization"] = "bearer \(token!)"

否则,您的 Authorization 标头值将包含 Optional(value)而不只是 value

Otherwise your Authorization header value is going to include Optional(value) instead of just value.

我目前能看到的唯一问题。如果您可以尝试一下并发表评论,那就太好了。如果不能真正解决您的问题,我将相应地更新答案。

That's the only issue I can see at the moment. If you could give that a try and comment back that would be great. I'll update my answer accordingly if that doesn't actually solve your problem.

祝您好运!

这篇关于经过身份验证的HTTP请求快速Alamofire的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆