测试已测试 | ✗ |
语言语言 | Obj-CObjective C |
许可 | MIT |
发布最后发布 | 2014年12月 |
由 Arthur Ariel Sabintsev 维护。
这是一个 iOS Objective-C 分类,用于执行 HTTP 基本访问认证,也称为 基本认证。
大多数在 iOS 上执行 基本认证 的解决方案都涉及到使用第三方 Base64 库。Apple 在 CFNetworking 框架中提供了原生函数,从而消除了对第三方库的需要。此分类把解决方案封装在一个干净且可重复使用的方法中。
:
)的用户名的异常NSMutableURLRequest+BasicAuth.h
导入到您的类(们)中。CFNetworking
框架。NSMutableURLRequest
并确保设置以下属性URL
HTTPMethod
basicAuthForRequest:withUsername:andPassword
方法。NSURLConnection
并加载您的 基本认证 请求。+ (void)basicAuthForRequest:(NSMutableURLRequest *)request withUsername:(NSString *)username andPassword:(NSString *)password;
// Cast username and password as CFStringRefs via Toll-Free Bridging
CFStringRef usernameRef = (__bridge CFStringRef)username;
CFStringRef passwordRef = (__bridge CFStringRef)password;
// Reference properties of the NSMutableURLRequest
CFHTTPMessageRef authoriztionMessageRef = CFHTTPMessageCreateRequest(kCFAllocatorDefault, (__bridge CFStringRef)[request HTTPMethod], (__bridge CFURLRef)[request URL], kCFHTTPVersion1_1);
// Encodes usernameRef and passwordRef in Base64
CFHTTPMessageAddAuthentication(authoriztionMessageRef, nil, usernameRef, passwordRef, kCFHTTPAuthenticationSchemeBasic, FALSE);
// Creates the 'Basic - <encoded_username_and_password>' string for the HTTP header
CFStringRef authorizationStringRef = CFHTTPMessageCopyHeaderFieldValue(authoriztionMessageRef, CFSTR("Authorization"));
// Add authorizationStringRef as value for 'Authorization' HTTP header
[request setValue:(__bridge NSString *)authorizationStringRef forHTTPHeaderField:@"Authorization"];
// Cleanup
CFRelease(authorizationStringRef);
CFRelease(authoriztionMessageRef);
如果用户名包含冒号(例如 :
),将抛出异常。
由 Arthur Ariel Sabintsev 为 ID.me, Inc. 创建。