基本和OAuth身份验证标头同时进行

时间:2012-12-11 12:28:27

标签: objective-c oauth-2.0 afnetworking

是否可以在AFNetworking的同一请求中使用Basic和OAuth授权标头(避免覆盖)?

我有这个代码:

NSURL *url = [NSURL URLWithString:@"https://www.infojobs.net/"];
AFOAuth2Client *OAuthClient = [[AFOAuth2Client alloc] initWithBaseURL:url clientID:kClientID secret:kClientSecret];

[OAuthClient registerHTTPOperationClass:[AFJSONRequestOperation class]];

[OAuthClient authenticateUsingOAuthWithPath:@"oauth/authorize" code:self.authorizationCode redirectURI:kInfoJobsRedirectURLString success:^(AFOAuthCredential *credential) {
    NSLog(@"Credentials: %@", credential.accessToken);
    if (![credential.accessToken isEqualToString:@""]) {
        self.isAuthenticated = YES;

        [AFOAuthCredential storeCredential:credential withIdentifier:@"kInfoJobsAccessToken"];


        [[InfoJobsAPI sharedClient] setAuthorizationHeaderWithToken:credential.accessToken];

        // (!) This overwrites the Authorization header set with the accessToken
        [[InfoJobsAPI sharedClient] setAuthorizationHeaderWithUsername:kClientID password:kClientSecret];   

        success(credential);

    }
} failure:^(NSError *error) {
    NSLog(@"Error: %@", error.localizedDescription);

}];

我需要这样的请求:

GET /api/1/application HTTP/1.1
Host: api.infojobs.net
Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Authorization: OAuth 07d18fac-77ea-461f-9bfe-a5e9d98deb3d
....

但我无法设置" Basic"和" OAuth"同一请求中的授权标头,因为AFNetworking似乎覆盖此标头,如documentation中所示

可以使用" Basic"和" OAuth"在同一个Authorization标题中,可能用" \ n" ?

谢谢,抱歉我的英语很差


修改

最后,我可以使用" Basic"和" Oauth"同一标头中的身份验证,这是代码:

[[InfoJobsAPI sharedClient] setAuthorizationHeaderWithUsername:kClientID password:kClientSecret];

AFOAuthCredential *credential = [AFOAuthCredential retrieveCredentialWithIdentifier:@"kInfoJobsAccessToken"];

NSMutableURLRequest *request = [self requestWithMethod:@"GET" path:@"/api/2/candidate" parameters:nil];

[request addValue:[NSString stringWithFormat:@"OAuth %@", credential.accessToken] forHTTPHeaderField:@"Authorization"];

AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
    DLog(@"Response : %@",JSON);
}failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
    DLog(@"Error : %@",error);
}];

[operation start];

1 个答案:

答案 0 :(得分:1)

根据HTTP规范,请求中只能有一个Authorization标头。因此,根据该规范,库显示的行为是正确的:第二次调用setAuthorizationHeader...会覆盖前一个。

您通常在HTTP中看到的是存在握手阶段,服务器告诉客户端它可以接受哪些授权协议。然后,客户端可以从这些协议中选择一个,它想要使用哪个协议。