NSURLConnection does not use the default credential

人走茶凉 提交于 2019-12-03 17:30:28
BJ Homer

Sending the default credential without an authentication challenge is considered insecure, especially in the case where you're communicating over plain HTTP. The HTTP spec says that you can send credentials proactively, but that you should usually wait for an authentication challenge. And that's the behavior that Cocoa provides by default.

If you need to proactively send the credentials, then you'll have to manually add the headers yourself. You can just base-64 encode it yourself, or you can use the CFHTTP functions to do it for you, like so:

CFHTTPMessageRef dummyRequest =
    CFHTTPMessageCreateRequest(
        kCFAllocatorDefault,
        CFSTR("GET"),
        (CFURLRef)[urlRequest URL],
        kCFHTTPVersion1_1);
CFHTTPMessageAddAuthentication(
    dummyRequest,
    nil,
    (CFStringRef)username,
    (CFStringRef)password,
    kCFHTTPAuthenticationSchemeBasic,
    FALSE);
authorizationString =
    (NSString *)CFHTTPMessageCopyHeaderFieldValue(
        dummyRequest,
        CFSTR("Authorization"));
CFRelease(dummyRequest);

Then just set the authorizationString as the Authorization header in your NSURLRequest.

(Code copied blatantly from https://stackoverflow.com/a/509480/100478, though I've written similar code myself many times.)

As HTTP supports many different authentication methods (Basic, Digest, Kerberos, etc), NSURLConnection cannot send the credentials before it receives the authentication challenge from the server because it does't know how to send them.

While BJ's answer may solve your problem on the client side, the real issue is the server. Internally NSURLConnection will use it's own equivalent of the delegate method connection:didReceiveAuthenticationChallenge: and the other authentication methods. This is where it looks for a credential it can apply from NSURLCredentialStorage . In your case this doesn't seem to be happening. For those methods to be invoked the server not only has to give a 40x HTTP status code, but it must include a WWW-Authenticate header. This tells NSURLConnection to attempt to answer the authentication challenge. It's likely that your server isn't including this, and that's why the client isn't sending credentials.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!