du22399 2014-10-24 13:06
浏览 47
已采纳

AFNetworking和授权标头

I'm new to AFNetworking, and I'm trying to use it to talk to an API that I've written in Go. I'm having difficulty getting the Authorization header to work. I've subclassed AFHTTPSessionManager and configured it as follows

+ (HMAPIClient *)sharedHMAPIClient
{
    static HMAPIClient* _sharedHMAPIClient = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _sharedHMAPIClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:HMBaseURL]];
    });

    return _sharedHMAPIClient;
}

- (instancetype)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];

    if (self) {
        self.responseSerializer = [AFJSONResponseSerializer serializer];
        self.requestSerializer = [AFJSONRequestSerializer serializer];

        [self.requestSerializer setAuthorizationHeaderFieldWithUsername:RegistrationAPIKey
                                                               password:@"Doesn't matter what goes here."];
    }

    return self;
}

- (void)hitTestEndpoint
{
    [self GET:@"testEndpoint" parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        NSLog(@"%@", responseObject);
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        NSLog(@"%@", error);
    }];
}

When I call -(void)hitTestEndpoint, I see the following headers in my server logs (Authorization is missing):

Key: Accept-Encoding Value: [gzip, deflate]
Key: Connection Value: [keep-alive]
Key: Accept-Language Value: [en;q=1]
Key: User-Agent Value: [TestApp/2 (iPad Simulator; iOS 8.1; Scale/2.00)]
Key: Accept Value: [*/*]

For comparison, when I hit the same endpoint with the following curl command,

curl https://api.example.com/v1/testEndpoint/ -u test_xqzwjcasogptbnpa:

I see the following headers:

Key: Authorization Value: [Basic eHF6d2pjYXNvZ3B0Ym5wYTo=]
Key: User-Agent Value: [curl/7.30.0]
Key: Accept Value: [*/*]

Can someone point me in the right direction? -Thanks

Update: I have added AFNetworkActivityLogger so that I can see each request. The Authorization header is indeed included. Also, I tried hitting http://headers.jsontest.com, which returns the HTTP request headers received from the client. The Authorization header is present in that output.

So, the problem must be with my server. I'm already logging all headers for each request, and I'm not sure where else to look. Going to tag this question with Go to see if someone has an idea.

Update 2: I added a call to httputil.DumpRequest at the top of my request handler, and it also shows that the Authorization header is missing. By the way, any custom headers that I set do appear as expected. It's just the Authorization header that's missing.

Here's the Go Code:

func testResponse(rw http.ResponseWriter, request *http.Request) {

    // check output from DumpRequest()
    dump,err := httputil.DumpRequest(request,true)
    check(err)
    fmt.Println("Output of DumpRequest():")
    fmt.Println(string(dump))
    fmt.Println("============")

    fmt.Println("request.Headers:")
    for key, value := range request.Header {
        fmt.Println("Key:", key, "Value:", value)
    }
    fmt.Println("===============")

    // return some dummy JSON
    rw.Header().Set("Content-Type", "application/json")
    rw.Write(PersonToJson(getPerson("2f6251b8-d7c4-400f-a91f-51e09b8bfaf4")))

}

  • 写回答

1条回答 默认 最新

  • douzhang1115 2014-10-27 15:55
    关注

    The server log you're showing looks like the headers after Go has already parsed them. It would be helpful to see the raw, plaintext HTTP headers that Go received. That would tell you if Go is ignoring the header or if something upstream is stripping it out.

    Edit: Not sure why Go would strip out the Authorization header before giving you the supposedly raw request. But I think the Authorization header is normally sent by the client only after making a previous un-authorized request and getting a 401 response from the server with a WWW-Authenticate header. Since it sounds like your client is sending the Authorization header out of the blue, maybe the Go server API is ignoring & stripping the header because it never asked the client to send it.

    If you just want to send a simple auth token on every request, what if you simply used a made up X- header instead, since you indicated that other headers you set arrive just fine?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图