gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 20:38:47 24 4
gpt4 key购买 nike

我正在尝试让我的 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com