objective-c - iOS 似乎绕过了基本的服务器身份验证

标签 objective-c ios apache http basic-authentication

我正在尝试让我的 iOS 应用程序使用基本身份验证从我的本地 apache 服务器访问文件。在浏览器中一切正常,我必须输入我的用户名和密码才能访问受限文件夹中的图像。然而,在应用程序中发生了一些奇怪的事情。

我创建了一个 NSURLConnection 到服务器(一切正常),第一次我的请求是委托(delegate)方法 - (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge 被调用。出于测试目的,我用一个空的 NSURLCredential 响应,显然连接失败了。但是,当我再次发出请求时,不会调用委托(delegate)方法,并且会以某种方式下载并显示图像而无需任何身份验证。我真的很困惑这是怎么回事!

部分代码如下:

- (IBAction)loginPressed
{
    self.username = self.usernameField.text;
    self.password = self.passwordField.text;
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.0.2/secret/favicon.ico"]];
    self.connection = [NSURLConnection connectionWithRequest:request delegate:self];
}


- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)data
{
    [self.data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.imageView.image = [UIImage imageWithData:self.data];
    self.errorLabel.text = @"";
}

- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
    if ([challenge previousFailureCount] == 0) {
        NSURLCredential *newCredential = [NSURLCredential credentialWithUser:self.username password:self.password persistence:NSURLCredentialPersistenceNone];
        [challenge.sender useCredential:newCredential forAuthenticationChallenge:challenge];
    } else {
        [challenge.sender cancelAuthenticationChallenge:challenge];
        self.errorLabel.text = @"Invalid Username and/or Password";
        self.imageView.image = [UIImage imageWithData:[[NSData alloc] init]];
    }
}

最佳答案

您应该使用不同的委托(delegate)回调,connection:didReceiveAuthenticationChallenge:

- (void) connection:(NSURLConnection *)connection 
    didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {

    if ([challenge previousFailureCount] > 0) {
        // Do something, like prompt for credentials or cancel the connection
    } else {
        NSURLCredential *creds = [NSURLCredential 
                          credentialWithUser:@"someUser" 
                                    password:@"somePassword"
                                 persistence:NSURLCredentialPersistenceForSession];

        [[challenge sender]  useCredential:creds forAuthenticationChallenge:challenge];
    }
}

关于objective-c - iOS 似乎绕过了基本的服务器身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9457783/

相关文章:

apache2 mod_headers 不工作

objective-c - XCode 4 中的 "Validate"

ios - 面向对象 - 父类(super class)中的 iOS isEqual 方法,它对子类是否正常工作?

ios - UISegmentedControl 没有执行目标方法?

c# - 在 iOS 7 中退出 UIDocumentInteractionController 的 PDF 时出现黑屏

ios - 查询应用程序的购买历史记录列表

ruby-on-rails - 一个活泼的 Ubuntu + Rails 服务器的建议

ios - 如何使用 objective-c 将图像存储在缓存内存中

iphone - 当选择器 View 停止滚动时如何获取事件

java - tomcat 和 Apache 之间的适配器