iPhone:如何使用 NSURLCredential 获得 HTTPS Web 服务的基本身份验证
我正在尝试使用基本身份验证调用 https Web 服务(RESTful)。 如果我将凭据放在 url 本身中,效果很好,但我宁愿将其添加到请求中,这样密码就不会出现,例如在异常中。
我正在使用以下代码:
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser"
password:@"mypassword"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"example.com"
port:443
protocol:@"https"
realm:nil
authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
但它不起作用。 didReceiveAuthenticationChallenge 委托方法被调用,我可以在其中添加凭据,但理想情况下我会随请求一起发送它。
有什么想法吗?
I am trying to call an https web service (RESTful) using basic authentication.
It works fine if I put the credentials in the url itself but I would rather add it to the request so that the password does not appear, for instance in an exception.
I am using the following code:
NSURLCredential *credential = [NSURLCredential credentialWithUser:@"myuser"
password:@"mypassword"
persistence:NSURLCredentialPersistenceForSession];
NSURLProtectionSpace *protectionSpace = [[NSURLProtectionSpace alloc]
initWithHost:@"example.com"
port:443
protocol:@"https"
realm:nil
authenticationMethod:NSURLAuthenticationMethodHTTPBasic];
[[NSURLCredentialStorage sharedCredentialStorage] setDefaultCredential:credential
forProtectionSpace:protectionSpace];
NSURLConnection *theConnection = [NSURLConnection connectionWithRequest:theRequest delegate:self];
but it does not work. The didReceiveAuthenticationChallenge
delegate method gets called and I can add a credential there but ideally I would send it with the request.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果是基本身份验证,请尝试在标头中发送凭据。每次都对我有用。
用于在请求标头中发送用户名和密码
在您的请求中,添加包含字段名称 Authorization 和值
"Basic " + FinalAuth
的标头Try sending the credentials in the header if it is basic authentication. Works for me every time.
For sending the username and password in the header of the request
In your request, add a header with the field name Authorization and value
"Basic " + finalAuth
我错过了您使用 NSURLConnection 的最后一行代码。确保您的代表正在响应:
并且为您的保护空间返回“是”。
另外,请确保您的委托正在响应:
在这里,您可以将您创建的凭据分配给proposalCredential属性中的
NSURLAuthenticationChallenge
,以及将您的NSURLProtectionSpace
实例分配给NSURLAuthenticationChallenge
的 protectedSpace 属性。I missed that last line of code where you are using NSURLConnection. Make sure that your delegate is responding to :
And is returning YES for your protectionSpace.
Also, make sure that your delegate is responding to :
Here you can assign the credential that you created to the
NSURLAuthenticationChallenge
in the proposedCredential property, as well as yourNSURLProtectionSpace
instance into the protectionSpace property of theNSURLAuthenticationChallenge
.