NSURLCredential.h
NSURLCredential 代表的是一个身份证证书,URL Loading系统支持3种类型的证书:password-based user credentials, certificate-base。
NSURLCredential适合大多数的认证请求,因为它可以表示由用户名/密码组合、客户端证书及服务器信任创建的认证信息。
认证信息有三种持久化选项:
NSURLCredentialPersistenceNone : 要求URL载入系统 “在用完相应的认证信息后立即丢弃”
NSURLCredentialPersistenceForSession : 要求URL载入系统“在应用终止时,丢弃相应的crediential”
NSURLCredentialPersistencePermanent:要求URL载入系统“将相应的认证信息载入钥匙串(keychain)”,以便其他应用也能使用
为了认证, 要创建一个NSURLCedential对象,在提供的authentication challenge的protection space 上调用authenticationMethod方法,可以获取服务器的认证方法
NSURLCredential支持的认证方法
-
HTTP basic authentication (NSURLAuthenticationMethodHTTPBasic) 需要一个用户和密码,使用credentialWithUser:password:persistence:方法创建NSURLCredential对象
-
HTTP digest authentication (NSURLAuthenticationMethodHTTPDigest), 与basic authentication类似, 也需要一个用户名和密码,使用credentialWithUser:password:persistence:方法创建NSURLCredential对象
-
Client certificate authentication (NSURLAuthenticationMethodClientCertificate) 需要system identity 和需要与server进行身份验证的所有证书,使用credentialWithIdentity:certificates:persistence:创建NSURLCredential对象
- Server trust authentication (NSURLAuthenticationMethodServerTrust) 需要authentication challenge的protection space提供一个trust。使用credentialForTrust:来创建NSURLCredential对象。
(Basic、Digest与NTLM认证都是基于用户名/密码的认证。他们认证的响应逻辑是相同的。)
身份认证原理
在代码需要向认证的服务器请求资源时,服务器会使用http状态码401进行响应,即访问被拒绝需要验证。NSURLConnection会接收到响应并立刻使用认证challenge的一份副本来发送一条willSendRequestForAuthenticationChallenge:委托消息,过程如下:
image.pngNSURLAuthenticationChallenge
NSURLAuthenticationChallenge encapsulates a challenge from a server requiring authentication from the client.
authentication challenge — An HTTP or HTTPS response indicating that the server requires authentication information from the client Foundation represents this with the NSURLAuthenticationChallenge class, and it also uses this infrastructure to support custom HTTPS server trust evaluation. An authentication challenge originates from a protection space.
NSURLAuthenticationChallenge封装一个挑战来自客户机的服务器要求身份验证。
身份验证的挑战——一个HTTP或HTTPS响应表明服务器需要身份验证信息从客户机与NSURLAuthenticationChallenge基金会代表这类,它也使用这种基础设施,以支持自定义HTTPS服务器信任评估。身份验证的挑战源于保护空间。
AFNetworking 中的具体使用:
+ (void)post:(NSString *)url params:(NSDictionary *)params success:(void (^)(id json))success failure:(void (^)(NSError *error))failure
{
AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
mgr.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"text/html",@"text/plain", nil];
[mgr.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[mgr setTaskDidReceiveAuthenticationChallengeBlock:^NSURLSessionAuthChallengeDisposition(NSURLSession *session, NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, NSURLCredential *__autoreleasing *credential) {
if (challenge.previousFailureCount == 0) {
NSURLCredential *cre = [NSURLCredential credentialWithUser:@"账号"
password:@"密码" persistence:NSURLCredentialPersistenceForSession];
*credential = cre;
return NSURLSessionAuthChallengeUseCredential;
} else {
return NSURLSessionAuthChallengeCancelAuthenticationChallenge;
}
}];
[mgr POST:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
if (success) {
success(responseObject);
}
} failure:^(NSURLSessionDataTask *task, NSError *error) {
if (failure) {
failure(error);
}
}];
}
NSURLCredentialStorage.h
The manager of a shared credentials cache.
The shared cache stores and retrieves instances of NSURLCredential. You can store password-based credentials permanently, based on the NSURLCredentialPersistence they were created with. Certificate-based credentials are never stored permanently.
共享凭证缓存的管理员
共享缓存存储和检索NSURLCredential的实例。 您可以根据创建的NSURLCredentialPersistence永久存储基于密码的凭据。 永远不会存储基于证书的凭据。
测试代码
- (IBAction)urlCredentialBtn:(id)sender {
NSLog(@"------身份认证 NSURLCredential----");
NSURLCredential *cre = [[NSURLCredential alloc] initWithUser:@"天下林子" password:@"123456" persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace * pro = [[NSURLProtectionSpace alloc] initWithHost:@"127.0.0.1" port:8080 protocol:@"we:we" realm:@"123" authenticationMethod:@"method"];
[self saveCredential:cre forProtectionSpace: pro];
}
- (void)saveCredential:(NSURLCredential*)credential forProtectionSpace:(NSURLProtectionSpace*)protectionSpace
{
//NSLog(@"---------->>>>>>>>>ATTEMPTING SAVE:----------");
[self debugCredential:credential]; //credential is properly formatted
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
//NSLog(@"---------->>>>>>>>>ATTEMPTING RETRIEVAL:---------");
NSURLCredential* retrievedTest = [[NSURLCredentialStorage sharedCredentialStorage]defaultCredentialForProtectionSpace:protectionSpace];
[self debugCredential:retrievedTest]; //all values are null, credential is not null
}
- (void)debugCredential:(NSURLCredential*) credential
{
NSLog(@"+++++++++++++DEBUG Credential: [%@]",credential);
NSLog(@"+++++++++++++credential identity: %@", credential.identity);
NSLog(@"+++++++++++credential cert: %@", credential.certificates);
NSLog(@"++++++++++credential persistence: %lu", (unsigned long)credential.persistence);
}
打印结果:
2018-09-21 14:57:36.760570+0800 MOBFrameWorkTest[16859:847307] ------身份认证 NSURLCredential----
2018-09-21 14:57:36.760969+0800 MOBFrameWorkTest[16859:847307] +++++++++++++DEBUG Credential: [<NSURLCredential: 0x600002598460>: 天下林子]
2018-09-21 14:57:36.761113+0800 MOBFrameWorkTest[16859:847307] +++++++++++++credential identity: (null)
2018-09-21 14:57:36.761242+0800 MOBFrameWorkTest[16859:847307] +++++++++++credential cert: (null)
2018-09-21 14:57:36.761363+0800 MOBFrameWorkTest[16859:847307] ++++++++++credential persistence: 1
2018-09-21 14:57:36.762243+0800 MOBFrameWorkTest[16859:847307] +++++++++++++DEBUG Credential: [<NSURLCredential: 0x60000258c470>: 天下林子]
2018-09-21 14:57:36.762363+0800 MOBFrameWorkTest[16859:847307] +++++++++++++credential identity: (null)
2018-09-21 14:57:36.762465+0800 MOBFrameWorkTest[16859:847307] +++++++++++credential cert: (null)
2018-09-21 14:57:36.762560+0800 MOBFrameWorkTest[16859:847307] ++++++++++credential persistence: 1
网友评论