OAuth 2承载授权标头 [英] OAuth 2 bearer Authorization header
问题描述
通过更新客户端API,HTTPBasicAuthication方法已替换为OAuth2 Bearer
授权标头。
With an update to the client's API the HTTPBasicAuthication method has been replace with a OAuth2 Bearer
Authorization header.
使用旧API,我会执行以下操作:
With the old API I would do the following:
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];
但这不适用于 Bearer
标题。
现在我通常只需添加标题即可添加标题:
Now normally I would just add the header my self by adding it like so:
NSString *authorization = [NSString stringWithFormat:@"Bearer %@",self.account.token];
[urlRequest setValue:authorization forHTTPHeaderField:@"Authorization"];
但是这个解决方案的问题是API将大多数调用重定向到其他URL,这有与安全有关。
重定向 NSURLRequest
后,将从请求中删除Authorization标头,因为我无法将Bearer方法添加到 NSURLCredentialStorage
重定向后无法再对其进行身份验证。
But the problem with this solutions is that the API redirect most of the calls to other URLs, this has to do with security.
After the NSURLRequest
gets redirected the Authorization header is removed from the request and since I'm unable to add the Bearer method to the NSURLCredentialStorage
it can't authenticate any more after being redirected.
什么是好的解决方案?我只能考虑捕获重定向并修改 NSURLRequest
,因此它确实包含 Bearer
标头。但是如何?
What would be a good solutions? I can only think to catch the redirect and modify the NSURLRequest
so it does include the Bearer
header. But how?
推荐答案
经过大量研究后我发现我只需更换 NSURLRequest
重定向呼叫时。
Well after much research I found out that I will just have to replace the NSURLRequest
when a call is redirected.
不如我想的那样好,但确实有效。
Not as nice as I would like it to be, but is does work.
我用 AFNetworking
并添加了重定向块,然后检查授权
标头是否仍然设置如果不是我创建一个新的 NSMutableURLRequest
并设置所有属性以匹配旧请求(我知道我刚刚创建了一个可变副本):
I used AFNetworking
and added the redirect block, then check wether the Authorization
header is still set if not I create a new NSMutableURLRequest
and set all the properties to match the old request (I know I could have just created a mutable copy):
[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;
}];
这篇关于OAuth 2承载授权标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!