【发布时间】:2012-08-18 22:50:47
【问题描述】:
随着客户端 API 的更新,HTTPBasicAuthication 方法已替换为 OAuth2 Bearer Authorization 标头。
使用旧 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];
但这不适用于Bearer 标头。
现在通常我会像这样添加我自己的标题:
NSString *authorization = [NSString stringWithFormat:@"Bearer %@",self.account.token];
[urlRequest setValue:authorization forHTTPHeaderField:@"Authorization"];
但这个解决方案的问题在于 API 将大部分调用重定向到其他 URL,这与安全性有关。
在NSURLRequest 被重定向后,Authorization 标头已从请求中删除,并且由于我无法将 Bearer 方法添加到 NSURLCredentialStorage,因此在重定向后无法再进行身份验证。
什么是好的解决方案?我只能想抓住重定向并修改NSURLRequest,因此它确实包含Bearer 标头。但是怎么做呢?
【问题讨论】:
标签: ios nsurlconnection oauth-2.0 nsurlrequest