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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭