代码之家  ›  专栏  ›  技术社区  ›  Ian1971

iPhone:如何使用NSURLCredential获得对HTTPS Web服务的基本身份验证

  •  2
  • Ian1971  · 技术社区  · 16 年前

    我正在尝试使用基本身份验证调用HTTPSWeb服务(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

    有什么想法吗?

    2 回复  |  直到 16 年前
        1
  •  2
  •   lostInTransit    16 年前

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

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

    在请求中,添加一个带有字段名的头 授权 和价值 "Basic " + finalAuth

        2
  •  0
  •   Mayur Prajapati    12 年前

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

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

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

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

    在这里,您可以将创建的凭据分配给 NSURLAuthenticationChallenge 在proposedCredential属性中,以及 NSURLProtectionSpace NSURLAuthenticationChallenge挑战