2

是否可以在 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
....

但我无法在同一请求中设置“基本”和“OAuth”授权标头,因为 AFNetworking 似乎覆盖了此标头,如文档中所示

可以在同一个 Authorization 标头中使用“Basic”和“OAuth”,也许用“\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];
4

1 回答 1

1

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

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

于 2012-12-11T12:54:52.070 回答