I know that if I use following nsurlconnectiondelegate it will be fixed
– connection:willSendRequestForAuthenticationChallenge: –
connection:canAuthenticateAgainstProtectionSpace
But I am trying to use
sendAsynchronousRequest:queue:completionHandler:
So you don't get the callback. I looked into apple docs it say following
If authentication is required in order to download the request, the required credentials must be specified as part of the URL. If authentication fails, or credentials are missing, the connection will attempt to continue without credentials.
I could not figure out how to do that. When I looked up all I got is this private call
+(void)setAllowsAnyHTTPSCertificate:(BOOL)inAllow forHost:(NSString *)inHost;
Any idea how to do this?
Following is the error I get
The certificate for this server is invalid. You might be connecting to
a server that is pretending to be “example.com=0x8b34da0
{NSErrorFailingURLStringKey=https://example.com/test/,
NSLocalizedRecoverySuggestion=Would you like to connect to the server
anyway?, NSErrorFailingURLKey=https://example.com/test/,
NSLocalizedDescription=The certificate for this server is invalid. You
might be connecting to a server that is pretending to be “example.com”
which could put your confidential information at risk.,
NSUnderlyingError=0xa26c1c0 "The certificate for this server is
invalid. You might be connecting to a server that is pretending to be
“example.com” which could put your confidential information at risk.",
NSURLErrorFailingURLPeerTrustErrorKey=
The webserver which you are using is asking for Server Trust Authentication, you need to properly respond with the appropriate action. You need to implement connection:willSendRequestForAuthenticationChallenge: delegate method and use SecTrustRef to authenticate it.
More information can be found here:-
https://developer.apple.com/library/ios/technotes/tn2232/_index.html
This was my code to fix error:
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
NSURLProtectionSpace *protectionSpace = [challenge protectionSpace];
id<NSURLAuthenticationChallengeSender> sender = [challenge sender];
if ([[protectionSpace authenticationMethod] isEqualToString:NSURLAuthenticationMethodServerTrust])
{
SecTrustRef trust = [[challenge protectionSpace] serverTrust];
NSURLCredential *credential = [[NSURLCredential alloc] initWithTrust:trust];
[sender useCredential:credential forAuthenticationChallenge:challenge];
}
else
{
[sender performDefaultHandlingForAuthenticationChallenge:challenge];
}
}
Try this.
Initiate your session using custom session config as shown below:
let session = URLSession(configuration: URLSessionConfiguration.ephemeral,
delegate: self,
delegateQueue: nil)
Implement the following delegate callback method:
public func urlSession(_: URLSession, task _: URLSessionTask, didReceive challenge: URLAuthenticationChallenge, completionHandler: #escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
guard let serverTrust = challenge.protectionSpace.serverTrust else {
return completionHandler(URLSession.AuthChallengeDisposition.useCredential, nil)
}
return completionHandler(URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
}
If you are using AFNetworking, you can use this code:
(Just as a temp client-side solution!)
AFHTTPSessionManager * apiManager = [AFHTTPSessionManager initWithBaseURL:[NSURL URLWithString:baseURL];
AFSecurityPolicy *policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
policy.allowInvalidCertificates = YES;
apiManager.securityPolicy = policy;
you can't fix it with the way you are trying
either drop to CFNetworking to allow bad certs
use NSConnection with a delegate and an undoc'd method
use the private API you found
all not good. CFNetwork would have to be OK for apple for now but the other 2 methods aren't even appstore-safe
Better get the server fixed. Thats the easiest and CLEANEST
This issue cannot be fixed with the way you are trying with blocks. you need to set delegates and implement the authentication challenge delegates to bypass the certificate validation.
Best solution is to either create a right certificate (make sure it is not self-signed) or change the protocol to HTTP if you are fine with it.
In my case, this error occurred due to my firewall blocked the required url. it's worked fine after removing firewall restrictions
That is a certificate error. you need to change your settings so that your program/os ignores the certificate, or add the url/certificate to a trusted list.
Sorry that is authentication, certificate is authentication. I took a look, and I found this article.
Not sure if it will resolve your issue, but it basically states, that they don't cover the case of connecting to a site with how a certificate in the documentation.
http://www.cocoanetics.com/2009/11/ignoring-certificate-errors-on-nsurlrequest/
In my case, this error occurred due to my system date. It was set as an old date, and the certificate is not effective from that old date. After correct the date, it works.
Related
I'm doing a SSL pinning check for a website and I need to tap into the didReceiveAuthenticationChallenge in order to do so. However when I am debugging the application I noticed that the challenge is being called 3 times before finishing and afterwards I end up with NSURLErrorDomainCode=-999.
Small snippet of how my code looks:
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
{
SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;
SecCertificateRef certificate = SecTrustGetCertificateAtIndex(serverTrust, 0);
What I found odd is that on the third attempt the certificate on the bottom line of the snippet, is returning nil. But for the first 2 runs it is returning the same server certificate again.
Is this a normal behaviour from this method? The server only has one certificate installed that I am comparing against. I don't know if it might be relevant to add that I am using the React-Native-Webview solution for my application.
I have a static function which I use to retrieve a configuration file through AFNetworking library, as follows:
static func getConfiguration(success: NetworkServiceSuccessBlock, failure: NetworkServiceFailureBlock) -> AFHTTPSessionManager? {
let sessionManager = AFHTTPSessionManager(sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
sessionManager.requestSerializer.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalCacheData
sessionManager.GET(getConfigurationUrl()!, parameters: nil, progress: nil, success: success, failure: failure)
return sessionManager
}
I need to check the server SSL certificate domain to be the proper one, something like challenge.protectionSpace.host for NSURLSession, and I need the check to determine whether the GET request will fail or not.
EDIT: I don't want to perform SSL Pinning with certificates stored in the app bundle, it is enough for me to verify the server certificate domain is correct.
Can someone point me in the right direction to perform this?
SITUATION
Using AFNetworking (NSURLConnection) to access my server API
The API needs Basic Authentication with token as username
The API returns HTTP 401 when token is invalid
I set the Basic Authentication headers before any request
If it returns 401, I retry like this:
AFHTTPRequestOperation *requestOperation = [MyHTTPClient.sharedClient HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
processSuccessBlock(operation, responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
processFailureBlock(operation, error);
if (operation.response.statusCode == 401)
[MyHTTPClient.sharedClient refreshTokenAndRetryOperation:operation success:processSuccessBlock failure:processFailureBlock];
}];
PROBLEM
When the server returns HTTP 401 with a Basic Authentication challenge, AFNetworking/NSURLConnection sends the identical request twice (initial request and then in answer to the authentication challenge)
But because of the code above that I handle the HTTP 401 myself, this is totally unnecessary and I want it to stop answering the authentication challenge automatically
WHAT I'VE TRIED
Responding with cancelAuthenticationChallenge: to willSendRequestForAuthenticationChallenge: is aborting the second call, but it gives the error code -1012 (NSURLErrorUserCancelledAuthentication) instead of 401 and masks the real response
How do you disable the authentication challenge response mechanism so you get the servers response without calling it twice?
You have a few of options to fully customize the authentication handling:
Utilize setWillSendRequestForAuthenticationChallengeBlock: and setAuthenticationAgainstProtectionSpaceBlock: from class AFURLConnectionOperation and set corresponding blocks where you can tailor the mechanism you require.
The headers contain documentation.
Override connection:willSendRequestForAuthenticationChallenge: in a subclass of AFURLConnectionOperation. This will effectively override the complete authentication mechanism setup in AFNetworking.
Note, that you cannot disable the "server validates client identity" authentication challenge -- this is part of the server. You MUST provide the correct credentials for the requested authentication method.
Try this.
- (void)connection:(NSURLConnection *)connection willSendRequestForAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
SecTrustRef trust = challenge.protectionSpace.serverTrust;
NSURLCredential *cred;
cred = [NSURLCredential credentialForTrust:trust];
[challenge.sender useCredential:cred forAuthenticationChallenge:challenge];
}
So it seems that ASIHTTPRequest allows you to ignore the certificates on https:// endpoints. I'm currently using MKNetworkKit and have implemented all my calls. Unfortunately, our testing server is on https but does not have a SSL certificate.
I'm able to connect fine using a curl with the -k command. I've tried various things in MKNetworkKit to ignore the NSURLAuthenticationChallenge, but to no avail. The latest thing I tried was the following:
op.authHandler = ^(NSURLAuthenticationChallenge *challenge)
{
NSURLCredential *credential = [NSURLCredential credentialWithUser:_userName password:password persistence:NSURLCredentialPersistenceNone];
[challenge.sender useCredential:credential forAuthenticationChallenge:challenge];
};
This allowed me to actually get a 401 error returned (instead of being blank). Looking at the curl string, MKNetworkKit strips my username/password when the above block hits. I'm not sure if that's progress or not.
Anyone know how to simply ignore the SSL certificate?
Edit:
I had to update MKNetwork kit to get the new method ShouldContinueWithInvalidCertificate on MKNetworkOperation and my testing server got the certError fixed.
However, now I'm having a weird error happening. I'm still unable to get any return from two specific endpoints on the server. I look at the request, copy it into the command as a curl, and it immediately returns results. I'm not getting an error either from the operation.
What's happening here?
The MKNetworkOperation class has a property called shouldContinueWithInvalidCertificate which is defaulted to NO. All you have to do is set it to YES, and it will ignore the certs.
The comments:
/*!
* #abstract Boolean variable that states whether the operation should continue if the certificate is invalid.
* #property shouldContinueWithInvalidCertificate
*
* #discussion
* If you set this property to YES, the operation will continue as if the certificate was valid (if you use Server Trust Auth)
* The default value is NO. MKNetworkKit will not run an operation with a server that is not trusted.
*/
I am trying to perform SSL certificate validation and have implemented the delegate canAuthenticateAgainstProtectionSpace
- (BOOL)connection:(NSURLConnection *)connection canAuthenticateAgainstProtectionSpace: (NSURLProtectionSpace*)protectionSpace
{
OSStatus status = SecTrustEvaluate(protectionSpace.serverTrust, &trustResult);
if(status == errSecSuccess)
{
}
else
{
}
}
However, I notice that this delegate gets called the first time for a given URL, but not for subsequent attempts for the same URL. I thought this had to do with the cached response , so I created the NSURLRequest like the following:
NSURLRequest *request = [[NSURLRequest alloc]
initWithURL: [NSURL URLWithString:_urlString]
cachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData
timeoutInterval: 10
];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
This doesn't help either. Any ideas, how I can get canAuthenticateAgainstProtectionSpace method to get called every time?
The answer above doesn't solve the actual problem. The actual problem here is that an authentication challenge is only being presented the first time a connection is established for that URL while the app is open.
As explained here
A TLS session is processor intensive and Apple doesn't want you to create a new one every time a connection is made to that URL, so they cache one for you. In this case, it's working against you, but you should be able to work around the issue by including a "." character at the end of your host.
In our case, we were trying to establish a connection to a web server containing a certificate issued by an in-house CA. Since we knew the CA wouldn't be trusted on the first connection, we allowed the connection to continue so that the CA could be downloaded. During that connection, we add the "." character to the end of the host. All subsequent connections use the regular URL without the "." character at the end of the host. This ensures that the CA cert we downloaded is validated the first time a "real" connection is made.
I solved the problem by adding the following code:
- (void)connection:(NSURLConnection *)connection
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
{
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
The above cancels the authentication challenge and so the delegate canAuthenticateAgainstProtectionSpace gets called every time