iOS中的NSURLConnection和基本HTTP身份验证


85

我需要GET HTTP request使用Basic调用一个缩写Authentication。这将是第一次将请求发送到服务器,而我已经拥有了,username & password因此不需要服务器进行授权挑战。

第一个问题:

  1. 是否NSURLConnection必须设置为同步才能进行基本身份验证?根据这篇文章的答案,如果您选择异步路由,似乎无法进行基本身份验证。

  2. 有人知道GET request不需要挑战响应就能说明基本认证的一些示例代码吗?Apple的文档显示了一个示例,但仅在服务器向客户端发出质询请求之后。

我是SDK的联网部分中的新成员,但我不确定应该使用哪个其他类来使其正常工作。(我看到了NSURLCredential该类,但似乎仅NSURLAuthenticationChallenge在客户端从服务器请求授权资源后才使用该类)。

Answers:


132

我正在使用与MGTwitterEngine的异步连接,它在NSMutableURLRequesttheRequest)中设置了授权,如下所示:

NSString *authStr = [NSString stringWithFormat:@"%@:%@", [self username], [self password]];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];
[theRequest setValue:authValue forHTTPHeaderField:@"Authorization"];

我不认为此方法需要经历挑战循环,但我可能错了


2
我没有写那部分,它只是添加到NSData中的类别中的MGTwitterEngine的一部分。在此处查看NSData + Base64.h / m:github.com/ctshryock/MGTwitterEngine
catsby

7
对于base64-encoding([authData base64EncodedString]),将来自Matt Mattaglagher的NSData + Base64.h和.m文件添加到您的XCode-Project(在Mac和iPhone上为Base64编码选项)。
elim 2012年

3
NSASCIIStringEncoding将破坏非美国用户名或密码。请改用NSUTF8StringEncoding
Dirk de Kok

4
NSData上的2014年不存在base64EncodingWithLineLength。请改用base64Encoding。
bickster 2014年

11
base64Encoding自iOS 7.0和OS X 10.9起不推荐使用@bickster 。我[authData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithLineFeed]改用。还可以使用NSDataBase64Encoding64CharacterLineLength或NSDataBase64Encoding76CharacterLineLength
Dirk,

80

即使问题得到了解答,我也想提出解决方案,该解决方案不需要在另一个线程中找到的外部库:

// Setup NSURLConnection
NSURL *URL = [NSURL URLWithString:url];
NSURLRequest *request = [NSURLRequest requestWithURL:URL
                                         cachePolicy:NSURLRequestUseProtocolCachePolicy
                                     timeoutInterval:30.0];

NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
[connection release];

// NSURLConnection Delegates
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
    if ([challenge previousFailureCount] == 0) {
        NSLog(@"received authentication challenge");
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:@"USER"
                                                                    password:@"PASSWORD"
                                                                 persistence:NSURLCredentialPersistenceForSession];
        NSLog(@"credential created");
        [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        NSLog(@"responded to authentication challenge");    
    }
    else {
        NSLog(@"previous authentication failure");
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    ...
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    ...
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    ...
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    ...
}

9
这与其他解决方案并不完全相同:它首先与服务器联系,接收401响应,然后以正确的凭据响应。因此,您浪费了往返行程。从好的方面来说,您的代码将处理其他挑战,例如HTTP Digest Auth。这是一个权衡。
benzado 2012年

2
无论如何,这是做到这一点的“正确方法”。所有其他方式都是捷径。
lagos 2012年

1
非常感谢!@moosgummi
LE SANG

@dom我已经使用了它,但是由于某种原因,未调用didRecieveAuthenticationChallenge,并且从站点返回了403访问被拒绝消息。有人知道发生了什么事吗?
Declan McKenna 2015年

是的,这是唯一的正确方法。并且它仅在第一次时引起401响应。对同一服务器的后续请求将通过身份验证发送。
dgatwood'3

12

这是没有第三者参与的详细答案:

请在这里检查:

//username and password value
NSString *username = @“your_username”;
NSString *password = @“your_password”;

//HTTP Basic Authentication
NSString *authenticationString = [NSString stringWithFormat:@"%@:%@", username, password]];
NSData *authenticationData = [authenticationString dataUsingEncoding:NSASCIIStringEncoding];
NSString *authenticationValue = [authenticationData base64Encoding];

//Set up your request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://www.your-api.com/“]];

// Set your user login credentials
[request setValue:[NSString stringWithFormat:@"Basic %@", authenticationValue] forHTTPHeaderField:@"Authorization"];

// Send your request asynchronously
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *responseCode, NSData *responseData, NSError *responseError) {
      if ([responseData length] > 0 && responseError == nil){
            //logic here
      }else if ([responseData length] == 0 && responseError == nil){
             NSLog(@"data error: %@", responseError);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"Error accessing the data" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
             [alert show];
             [alert release];
      }else if (responseError != nil && responseError.code == NSURLErrorTimedOut){
             NSLog(@"data timeout: %@”, NSURLErrorTimedOut);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"connection timeout" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
             [alert show];
             [alert release];
      }else if (responseError != nil){
             NSLog(@"data download error: %@”,responseError);
             UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"data download error" delegate:nil cancelButtonTitle:@"Close" otherButtonTitles:nil];
             [alert show];
             [alert release];
      }
}]

请让我知道您对此的反馈。

谢谢


现在不建议使用用于将NSData转换为NSString的方法base64Encoding: - (NSString *)base64Encoding NS_DEPRECATED(10_6, 10_9, 4_0, 7_0);最好改用NSDataBase64Encoding类别。
2015年

7

如果您不想导入整个MGTwitterEngine,并且不执行异步请求,则可以使用 http://www.chrisumbel.com/article/basic_authentication_iphone_cocoa_touch

要对base64编码的用户名和密码,请替换

NSString *authValue = [NSString stringWithFormat:@"Basic %@", [authData base64EncodingWithLineLength:80]];

NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];

您将需要包含以下文件

static char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

@implementation Base64
+(NSString *)encode:(NSData *)plainText {
    int encodedLength = (((([plainText length] % 3) + [plainText length]) / 3) * 4) + 1;
    unsigned char *outputBuffer = malloc(encodedLength);
    unsigned char *inputBuffer = (unsigned char *)[plainText bytes];

    NSInteger i;
    NSInteger j = 0;
    int remain;

    for(i = 0; i < [plainText length]; i += 3) {
        remain = [plainText length] - i;

        outputBuffer[j++] = alphabet[(inputBuffer[i] & 0xFC) >> 2];
        outputBuffer[j++] = alphabet[((inputBuffer[i] & 0x03) << 4) | 
                                     ((remain > 1) ? ((inputBuffer[i + 1] & 0xF0) >> 4): 0)];

        if(remain > 1)
            outputBuffer[j++] = alphabet[((inputBuffer[i + 1] & 0x0F) << 2)
                                         | ((remain > 2) ? ((inputBuffer[i + 2] & 0xC0) >> 6) : 0)];
        else 
            outputBuffer[j++] = '=';

        if(remain > 2)
            outputBuffer[j++] = alphabet[inputBuffer[i + 2] & 0x3F];
        else
            outputBuffer[j++] = '=';            
    }

    outputBuffer[j] = 0;

    NSString *result = [NSString stringWithCString:outputBuffer length:strlen(outputBuffer)];
    free(outputBuffer);

    return result;
}
@end

3

由于不推荐使用NSData :: dataUsingEncoding(ios 7.0),因此可以使用以下解决方案:

// Forming string with credentials 'myusername:mypassword'
NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
// Getting data from it
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
// Encoding data with base64 and converting back to NSString
NSString* authStrData = [[NSString alloc] initWithData:[authData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSASCIIStringEncoding];
// Forming Basic Authorization string Header
NSString *authValue = [NSString stringWithFormat:@"Basic %@", authStrData];
// Assigning it to request
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

1

如果您使用GTMHTTPFetcher进行连接,则基本身份验证也相当容易。您只需要在开始获取之前将凭据提供给获取程序。

NSString * urlString = @"http://www.testurl.com/";
NSURL * url = [NSURL URLWithString:urlString];
NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:url];

NSURLCredential * credential = [NSURLCredential credentialWithUser:@"username" password:@"password" persistence:NSURLCredentialPersistenceForSession];

GTMHTTPFetcher * gFetcher = [GTMHTTPFetcher fetcherWithRequest:request];
gFetcher.credential = credential;

[gFetcher beginFetchWithDelegate:self didFinishSelector:@selector(fetchCompleted:withData:andError:)];

0

您能告诉我示例代码中将编码行长度限制为80的原因是什么?我以为HTTP标头的最大长度约为4k(或者某些服务器的长度不超过此长度)。–贾斯汀·加尔西奇(Justin Galzic)2009年12月29日17:29

它不限于80,它是NSData + Base64.h / m中base64EncodingWithLineLength方法的选项,您可以在其中将编码的字符串拆分为多行,这对于其他应用程序(例如nntp传输)很有用。我相信twitter引擎作者选择80的长度足够大,可以将大多数用户/密码编码结果容纳到一行。


0

您可以使用AFNetworking(它是开源的),这是对我有用的代码。此代码使用基本身份验证发送文件。只需更改URL,电子邮件和密码即可。

NSString *serverUrl = [NSString stringWithFormat:@"http://www.yoursite.com/uploadlink", profile.host];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] requestWithMethod:@"POST" URLString:serverUrl parameters:nil error:nil];


NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];

// Forming string with credentials 'myusername:mypassword'
NSString *authStr = [NSString stringWithFormat:@"%@:%@", email, emailPassword];
// Getting data from it
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
// Encoding data with base64 and converting back to NSString
NSString* authStrData = [[NSString alloc] initWithData:[authData base64EncodedDataWithOptions:NSDataBase64EncodingEndLineWithLineFeed] encoding:NSASCIIStringEncoding];
// Forming Basic Authorization string Header
NSString *authValue = [NSString stringWithFormat:@"Basic %@", authStrData];
// Assigning it to request
[request setValue:authValue forHTTPHeaderField:@"Authorization"];

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

NSURL *filePath = [NSURL fileURLWithPath:[url path]];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
     dispatch_async(dispatch_get_main_queue(), ^{
                //Update the progress view
                LLog(@"progres increase... %@ , fraction: %f", uploadProgress.debugDescription, uploadProgress.fractionCompleted);
            });
        } completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
            if (error) {
                NSLog(@"Error: %@", error);
            } else {
                NSLog(@"Success: %@ %@", response, responseObject);
            }
        }];
[uploadTask resume];
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.