使用Basic Auth进行身份验证时遇到问题.我正在使用符合URLRequestConvertible协议的标准枚举来构造我的请求.问题是,当我在枚举中手动设置授权标头时,如下所示:
let user = ***
let password = ***
let credentialData = "\(user):\(password)".dataUsingEncoding(NSUTF8StringEncoding)!
let base64Credentials = credentialData.base64EncodedStringWithOptions([])
mutableURLRequest.setValue("Basic \(base64Credentials)", forHTTPHeaderField: "Authorization")
Run Code Online (Sandbox Code Playgroud)
我总是得到401未经授权的回复.但是,如果我使用authenticate回调设置密码,如下所示:
Alamofire.request(request)
.authenticate(user: "USERNAME_HERE", password: "PASSWORD_HERE")
.responseJSON { (response) -> Void in
print("JSON response \(response)")
completion(success: true, error: nil)
}
Run Code Online (Sandbox Code Playgroud)
它正确验证.我希望能够在enum中手动设置它,URLRequestConvertible而不是传入凭据authenticate.
我知道它正在使用NSURLCredential引擎盖来进行auth挑战,但我希望能够手动设置它.
这是我的URLRequestConvertible实现:
enum CheckedUpAPI: URLRequestConvertible {
static let baseURLString = "https://***"
static let APIKey = "***"
static let APIClientName = "iPad"
case UpdatePatient(String, …Run Code Online (Sandbox Code Playgroud) 我有3个方法,UserLogin,Login和LogoutButtonPressed:
UserLogin:我使用AFNetworking使用NSURLCredential连接到Windows身份验证的URL:
-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{
NSURL *url = [NSURL URLWithString:kIP];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
NSURLCredential *credential = [NSURLCredential
credentialWithUser:user
password:password
persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
[[NSOperationQueue mainQueue] addOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completionHandler) {
completionHandler(responseObject, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completionHandler) {
completionHandler(nil, error);
}
}];
[operation start];
}
Run Code Online (Sandbox Code Playgroud)
Login方法调用此方法:
- (void)Login
{
NSString *rawString = [self.idTextField text];
NSCharacterSet *whitespace = …Run Code Online (Sandbox Code Playgroud) 我一直在搜索stackoverflow,谷歌,苹果和其他地方.提供的提示看起来很有前途,我实现了它们但总的来说似乎没有工作或得到强制执行.
问题:我有一个NSURLConnection具有特定凭据.然后我有一个注销,我清除凭据,保护空间,我删除所有缓存的响应并删除所有的cookie sharedHTTPCookieStorage但几秒钟后再次调用我的身份验证请求,即使有错误的凭据我仍然使用旧(已删除)凭据
以下是一些代码提取,其中删除了凭据
NSDictionary *credentialsDict = [[NSURLCredentialStorage sharedCredentialStorage] allCredentials];
if ([credentialsDict count] > 0) {
// the credentialsDict has NSURLProtectionSpace objs as keys and dicts of userName => NSURLCredential
NSEnumerator *protectionSpaceEnumerator = [credentialsDict keyEnumerator];
id urlProtectionSpace;
// iterate over all NSURLProtectionSpaces
while (urlProtectionSpace = [protectionSpaceEnumerator nextObject]) {
NSEnumerator *userNameEnumerator = [[credentialsDict objectForKey:urlProtectionSpace] keyEnumerator];
id userName;
// iterate over all usernames for this protectionspace, which are the keys for the actual NSURLCredentials
while (userName = [userNameEnumerator nextObject]) …Run Code Online (Sandbox Code Playgroud) 我NSURLCredentials在这个方法中使用:
-(void)UserLogin:(NSString *)user andPassWordExists:(NSString *)password completionHandler:(void (^)(NSArray *resultsObject, NSError *error))completionHandler
{
NSURL *url = [NSURL URLWithString:kIP];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]
initWithRequest:request];
NSURLCredential *credential = [NSURLCredential
credentialWithUser:user
password:password
persistence:NSURLCredentialPersistenceForSession];
[operation setCredential:credential];
[[NSOperationQueue mainQueue] addOperation:operation];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (completionHandler) {
completionHandler(responseObject, nil);
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (completionHandler) {
completionHandler(nil, error);
}
}];
[operation start];
}
Run Code Online (Sandbox Code Playgroud)
现在我想在注销方法中清除NSURLCredentials,如下所示:
-(void)logout
{
//Clear NSURLCredentialPersistenceForSession
}
Run Code Online (Sandbox Code Playgroud)
我该怎么做呢?我应该重置NSURLCredentials还是在那里清除它们?
UPDATE
我找到了这个解决方案
NSURLCredentialStorage *credentialStorage …Run Code Online (Sandbox Code Playgroud) 我需要从受密码保护的URL解析xml文件,我尝试了以下操作
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"admin" password:@"123456" persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"xyz.com"
port:80
protocol:@"http"
realm:nil
authenticationMethod:NSURLAuthenticationMethodDefault];
[[NSURLCredentialStorage sharedCredentialStorage] setCredential:credential
forProtectionSpace:protectionSpace];
url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"GET"];
[request setValue:@"application/xml" forHTTPHeaderField:@"Content-Type"];
connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSURLResponse *response;
NSError *error;
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: &response error: &error];
NSString *dataStr=[[NSString alloc]initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(@"data == %@\n error in connecting == %@",dataStr,error);
Run Code Online (Sandbox Code Playgroud)
我收到了以下回复
data == <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
<html><head>
<title>401 Authorization Required</title> …Run Code Online (Sandbox Code Playgroud) 大家早上好,
我一直在尝试编写一个从需要身份验证的远程Web服务执行某些GET的应用程序.我的主要问题是这些远程服务器中的大多数(并且有很多远程服务器)没有有效的证书.我有代码接受无效的证书和代码,以正确的uname&pass(下面)来响应挑战.我遇到的问题是让两人一起玩.我似乎无法找到一种方法来发送挑战NSURLCredential或正确链接回调的方法.当我试图将它们连接起来时,我无法NSURLRequest接到didReceiveAuthenticationChallenge两次电话.
任何想法将不胜感激!
认证代码......
-(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
if(!hasCanceled){
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential=[NSURLCredential credentialWithUser:_username password:_password persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
}
else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
NSLog(@"Bad Username Or Password");
badUsernameAndPassword = YES;
finished = YES;
}
}
}
Run Code Online (Sandbox Code Playgroud) 我使用a登录我的服务器SOAP web service.登录后,我正在查看的许多文件仅供登录用户使用,因此iOS必须在其中创建会话NSURL.
当尝试使用MPMoviePlayerViewController它预览视频文件将无法工作时,它只是加载viewController,然后解散它.
如果我使用QuickLook它确实有效,可能是因为我首先在本地下载视频,然后查看它.
但是,我不想这样做,我想使用流式传输视频,MPMoviePlayerViewController因为我不希望用户必须下载整个视频文件.我看过关于使用的帖子,NSURLCredential但这对我来说似乎不起作用.我用过(显然添加了我自己的个人信息):
/**
* Play media session
*
* @version $Revision: 0.1
*/
- (void)playMediaWithURL:(NSString *)mediaURL {
// Authenticate
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myusername"
password:@"mypassword"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"mysite.com"
port:80
protocol:@"http"
realm:nil
authenticationMethod:NSURLAuthenticationMethodDefault];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace];
// The movie player
NSURL *movieURL = [NSURL URLWithString:[mediaURL stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
MPMoviePlayerViewController *tempPlayer = [[MPMoviePlayerViewController alloc]initWithContentURL:movieURL];
// Add observer
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification object:nil]; …Run Code Online (Sandbox Code Playgroud) objective-c nsurl mpmovieplayercontroller nsurlcredential ios
球队,
我有基于.net的REST服务配置了双向SSL.在我的iphone方面,我已在设备配置文件中安装了服务器证书,并将客户端证书捆绑为应用程序资源.服务器证书验证工作正常,但客户端证书身份验证失败.以下是我的代码段
- (void)connection:(NSURLConnection *) connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
NSLog(@"Authentication challenge with host: %@", challenge.protectionSpace.host);
if([challenge previousFailureCount] == 0) {
NSURLProtectionSpace *protectionSpace = [challenge protectionSpace];
NSString *authMethod = [protectionSpace authenticationMethod];
if(authMethod == NSURLAuthenticationMethodServerTrust ) {
NSLog(@"Verifying The Trust");
[[challenge sender] useCredential:[NSURLCredential credentialForTrust:[protectionSpace serverTrust]] forAuthenticationChallenge:challenge];
}
else if(authMethod == NSURLAuthenticationMethodClientCertificate ) {
NSLog(@"Trying Certificate");
// load cert
NSString *thePath = [[NSBundle mainBundle]
pathForResource:@"Myclientcertificate" ofType:@"pfx"];
NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:thePath];
CFDataRef inPKCS12Data = (CFDataRef)PKCS12Data;
OSStatus status = noErr;
SecIdentityRef myIdentity;
SecTrustRef …Run Code Online (Sandbox Code Playgroud) iphone authentication client-certificates nsurlcredential ios4
早上
我一直致力于创建一个iOS应用程序,该应用程序使用存储的凭据NSURLCredentialStorage进行特定的保护空间.我现在已经到了proposedCredential用于获取存储凭据的地步.
我的问题是它正在回归null,而我似乎无法找到任何关于proposedCredential实际做什么以及为什么它没有返回我认为它应该返回的任何好的解释.
这就是我正在做的事情:
首先,我定义一个NSURLProtectionSpace,给出凭据并将它们存储在NSURLCredentialStorage.我已经检查过这是在我引用之前完成的,proposedCredential并且我传递的凭据是正确的.
NSURLProtectionSpace *protectionSpaceOne = [[NSURLProtectionSpace alloc]
initWithHost:xyz
port: 80
protocol:NSURLProtectionSpaceHTTP
realm:nil
authenticationMethod:NSURLAuthenticationMethodDefault];
//credential is initiated elsewhere.
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpaceOne];
-(void)connection:(NSURLConnection *)connection didRecieveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge{
//Has the authentication failed before?
if([challenge previousFailureCount]>0){
//Why?
NSError *error = [challenge error];
//Here I respond to the failure count
[[challenge sender]cancelAuthenticationCallenge:challenge];
}
NSURLCredential *proposedCredential = [challenge proposedCredential];
}
Run Code Online (Sandbox Code Playgroud)
有人可以告诉我proposedCredential实际做了什么,它是什么比较在一起来弄清楚它是否应该传递一个凭证,以及我可能从代码中遗漏了什么?
我在这里做的是,获取一个具有身份验证的URL.因此,我使用该功能
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;
Run Code Online (Sandbox Code Playgroud)
当它面向身份验证时,我提供UIAlertView输入用户名和密码,如果用户输入正确,则调用此方法.
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
Run Code Online (Sandbox Code Playgroud)
在这个方法中,我使登录窗口消失并引入详细视图.
当我想要注销功能时出现问题.我想要的是删除用户输入的凭据并再次获取该URL,以进行身份验证=目的.所以,我称之为didReceiveAuthenticationChallenge.
但是会发生什么呢,它直接转到didReceiveResponse方法而不问任何问题.这里的问题是我无法清除凭据.你能帮我这么做吗?
非常感谢提前!
我试图NSURLCredential通过使用该+credentialWithIdentity:certificates:persistence:方法创建一个.然而,它返回零.
我已经完成了以下步骤.首先,我创建一个私钥和公钥,然后生成一个证书并将其添加到我的钥匙串.第一个问题,当我这样做时:
static const uint8_t certificateIdentifier[] = "test.certificate";
NSData * certificateTag = [NSData dataWithBytes:certificateIdentifier length:sizeof(certificateIdentifier)];
SecCertificateRef cert = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) certificadoData);
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:(__bridge id)kSecClassCertificate forKey:(__bridge id)kSecClass];
[dictionary setObject:certificateTag forKey:(__bridge id)kSecAttrApplicationTag];
[dictionary setObject:(__bridge id)(cert) forKey:(__bridge id<NSCopying>)(kSecValueRef)];
OSStatus status = SecItemAdd((__bridge CFDictionaryRef)dictionary, NULL);
Run Code Online (Sandbox Code Playgroud)
状态告诉我,我certificateTag的论点无效.如果我没有放这个标签,我可以将证书放在我的钥匙串上,然后在方法内
(void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
Run Code Online (Sandbox Code Playgroud)
我放
SecIdentityRef myIdentity;
SecCertificateRef myCertificate;
NSMutableDictionary * queryCertificate = [[NSMutableDictionary alloc] init];
[queryCertificate setObject:(__bridge id)kSecClassIdentity forKey:(__bridge id)kSecClass];
[queryCertificate setObject:[NSNumber numberWithBool:YES] forKey:(__bridge …Run Code Online (Sandbox Code Playgroud) 我试图连接到http://cmis.demo.nuxeo.org/nuxeo/atom/cmis/用NSURLConnection.这个演示Web服务记录到要求身份验证(登录:管理员/密码:管理员).
编辑:此Web服务现在发送身份验证质询,但当时没有问到该问题.
此Web服务不发送身份验证质询,因此我无法使用connection:didReceiveAuthenticationChallenge:委托方法.相反,我NSURLCredential在共享凭据存储中设置了默认值.不幸的是,此默认凭据未被使用NSURLConnection.
这是我的代码(使用ARC,在iOS 5上测试):
@implementation ViewController
{
NSMutableData *responseData;
}
- (IBAction) connect:(id)sender
{
NSString *user = @"Administrator";
NSString *password = @"Administrator";
NSURL *nuxeoURL = [NSURL URLWithString:@"http://cmis.demo.nuxeo.org/nuxeo/atom/cmis/"];
NSURLCredential *credential = [NSURLCredential credentialWithUser:user password:password persistence:NSURLCredentialPersistenceForSession];
NSString *host = [nuxeoURL host];
NSNumber *port = [nuxeoURL port];
NSString *protocol = [nuxeoURL scheme];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc] initWithHost:host port:[port integerValue] protocol:protocol realm:nil authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential forProtectionSpace:protectionSpace]; …Run Code Online (Sandbox Code Playgroud) nsurlcredential ×12
ios ×8
iphone ×5
objective-c ×5
afnetworking ×2
cocoa ×2
nsurlrequest ×2
alamofire ×1
certificate ×1
https ×1
ios4 ×1
keychain ×1
nsurl ×1
swift ×1
uiwebview ×1