OAuth 2承载授权标头

rck*_*nes 13 nsurlconnection nsurlrequest ios oauth-2.0

通过更新客户端的API,HTTPBasicAuthication方法已替换为OAuth2 BearerAuthorization标头.

使用旧API我会执行以下操作:

NSURLCredential *credential = [NSURLCredential credentialWithUser:self.account.username 
                                                         password:self.account.token 
                                                      persistence:NSURLCredentialPersistenceForSession];

NSURLProtectionSpace *space = [[NSURLProtectionSpace alloc] initWithHost:kAPIHost
                                                                    port:443
                                                                protocol:NSURLProtectionSpaceHTTPS
                                                                   realm:@"my-api"
                                                    authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
Run Code Online (Sandbox Code Playgroud)

但这不适用于Bearer标题.

现在通常我会添加标题我自己添加它像这样:

NSString *authorization = [NSString stringWithFormat:@"Bearer %@",self.account.token];
[urlRequest setValue:authorization forHTTPHeaderField:@"Authorization"];
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案的问题在于API将大多数调用重定向到其他URL,这与安全性有关.NSURLRequest重定向后,从请求中删除了Authorization标头,因为我无法将Bearer方法添加到其中,NSURLCredentialStorage因此重定向后无法再对其进行身份验证.

什么是好的解决方案?我只能想到捕获重定向并修改NSURLRequest它,所以它确实包括Bearer标题.但是怎么样?

rck*_*nes 15

经过大量研究后,我发现我只需更换NSURLRequest呼叫被重定向的时间.

不像我希望的那样好,但确实有效.

我使用AFNetworking并添加了重定向块,然后检查Authorization标头是否仍然设置如果不是我创建一个新的NSMutableURLRequest并设置所有属性以匹配旧请求(我知道我可能刚刚创建了一个可变副本):

[requestOperation setRedirectResponseBlock:^NSURLRequest *(NSURLConnection *connection, NSURLRequest *request, NSURLResponse *redirectResponse) {

    if ([request.allHTTPHeaderFields objectForKey:@"Authorization"] != nil) {
        return request;
    }

    NSMutableURLRequest *urlRequest = [[NSMutableURLRequest alloc] initWithURL:request.URL cachePolicy:request.cachePolicy timeoutInterval:request.timeoutInterval];
    NSString *authValue = [NSString stringWithFormat:@"Bearer %@", self.account.token];
    [urlRequest setValue:authValue forHTTPHeaderField:@"Authorization"];

    return  urlRequest;

}];
Run Code Online (Sandbox Code Playgroud)