2

我正在尝试使用基本身份验证调用 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那里添加一个凭证,但理想情况下我会随请求一起发送它。

有任何想法吗?

4

2 回答 2

2

如果是基本身份验证,请尝试在标头中发送凭据。每次都为我工作。

用于在请求的标头中发送用户名和密码

NSString *authString = [[NSString stringWithFormat:@"%@:%@", userName, password] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *finalAuth = base64 of authString;

在您的请求中,添加带有字段名称Authorization和 value的标头"Basic " + finalAuth

于 2010-03-09T14:04:56.510 回答
0

我错过了您使用 NSURLConnection 的最后一行代码。确保您的代表正在响应:

- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace:(NSURLProtectionSpace *)protectionSpace

并为您的 protectionSpace 返回 YES。

此外,请确保您的代表正在响应:

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

在这里,您可以将您创建的凭据分配给NSURLAuthenticationChallenge建议的凭据属性,以及将您的NSURLProtectionSpace实例分配给 的 protectionSpace 属性NSURLAuthenticationChallenge

于 2010-03-12T08:17:00.297 回答