First, verify that the application communicates with the correct server (verify Protection Space)
in the Willsendrequestforauthenticationchallenge callback method, check challenge to determine if you want to respond to the server's authentication challenge, and issue an appropriate Challenge Response.
Prevent: If the transmission is rerouted to a third-party server on top of a malicious network, then the protection of space authentication will fail due to mismatched hosts and subsequent traffic will be terminated.
Create a protective space to compare the information contained in the Adventure Challenge.
Nsurlprotectionspace *defaultspace = [[Nsurlprotectionspace alloc] initwithhost:@ "xxx.com" port:443 protocol: Nsurlprotectionspacehttps realm:@ "mobile" authenticationmethod:nsurlauthenticationmethoddefault];
Supported Nsurlprotectionspace protocols:
- nsurlprotectionhttp:80/8080
- nsurlprotectionhttps:443
- Nsurlprotectionftp:21/22
Basic Challenge Response Process:
1.1 Way One: Protection space authentication in this way requires a backup authentication server or other alternative server, including multiple pretection space to achieve a certain degree of flexibility.
-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: ( Nsurlauthenticationchallenge *) Challenge {Nsurlprotectionspace *defaultspace = [[Nsurlprotectionspace alloc] InitW ithhost:@ "xxx.com" port:443 Protocol:nsurlprotectionspacehttps realm:@ "mobile" Authenticationmethod: Nsurlauthenticationmethoddefault]; Nsurlprotectionspace *trustspace = [[Nsurlprotectionspace alloc] initwithhost:@ "xxx.com" port:443 protocol: Nsurlprotectionspacehttps realm:@ "mobile" authenticationmethod:nsurlauthenticationmethodclientcertificate]; Nsarray *validspaces = [Nsarray arraywithobjects:defaultspace, Trustspace, nil]; if (![ Validspaces ContainsObject:challenge.protectionSpace]) {NSString *errormessage = @ "We" re unable to establish a sec Ure connection. Please check your network connection and try again. "; Dispatch_async (Dispatch_get_main_queue (), ^{//Show Alertview}); [Challenge.sender CancelauthenTicationchallenge:challenge]; }}
1.2 Mode two: To achieve backend flexibility, only to verify certain properties of challenge, such as host, port, protocol and distress definition number matching.
-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: ( Nsurlauthenticationchallenge *) Challenge { if (![ Challenge.protectionSpace.host isequaltostring:@ "xxx.com" | | (Challenge.protectionSpace.port! = 443) | | ! [Challenge.protectionSpace.protocol Isequaltostring:nsurlprotectionspacehttps]) { NSString *errormessage = @ "We ' re unable to establish a secure connection. Please check your network connection and try again. "; Dispatch_async (Dispatch_get_main_queue (), ^{ //Show Alertview }); [Challenge.sender Cancelauthenticationchallenge:challenge];} }
Second, the use of HTTP authentication
2.1 Standard Certification
HTTP basic, HTTP Digest, NTLM uses the user name and Password Authentication challenge, the three authentication response logic is similar, the following is an example of HTTP basic.
-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: (Nsurlauthenticationchallenge *) Challenge {if ( Challenge.protectionSpace.authenticationMethod = = Nsurlauthenticationmethodhttpbasic) {if (Challenge.previousfailu recount = = 0) {nsurlcredential *cred = [[Nsurlcredential alloc] Initwithuser:username password:password persis Tence:nsurlcredentialpersistenceforsession]; [Challenge.sender usecredential:cred Forauthenticationchallenge:challenge]; } else {//Before the authentication failed, need to be handled according to the situation, generally blocking the user [Challenge.sender Cancelauthenticationchallenge:challenge]; Warning user authentication failed nsstring *message = @ "Invalid username/passeord."; Dispatch_async (Dispatch_get_main_queue (), ^{//display view prompt}); } }}
If the challenge authentication fails, you need to prompt the user and cancel the challenge authentication, because Willsendrequestforauthenticationchallenge may be called multiple times. According to the configuration, if the user's authentication information is not valid and not properly checked, it is possible that the user submitted an illegal authentication information, the account is locked. If the incoming Challenge authentication method is not a type that the application can handle, no response is emitted.
2.2 Fast Authentication
Let the user register the device, then use a PIN for verification, no need to use a username and password at the time of authentication. To ensure the security of fast authentication, after the device registration succeeds, the server response needs to include a user certificate (encoded as PKCS P12 using Base64), the client application saves the certificate, and then checks it at startup.
2.2.1: Registering the device to finish saving the client certificate returned by the server
Certificate data returned successfully by the server registration
{ "result": "SUCCESS", "message": "Authentication Successful", "certificate": "<BASE64 encoded Certificate> " }
After successful registration, decode the Base64. P12 book and store it in keychain.
-(void) connectiondidfinishloading: (nsurlconnection *) connection {nserror *error = nil; Nsdictionary *responsedict = [nsjsonserialization jsonobjectwithdata:responsedata options:0 error:&error]; // ... Device registration complete operation//Save the certificate returned by the server if (isdeviceregisted) {nsstring *certstring = responsedict[@ "certificate"]; NSData *certdata = [Base64 decodestring:certstring]; Secidentityref identity = NULL; Seccertificateref certificate = NULL; [Utils identity:&identity certificate:&certificate frompkcs12data:certdata withphrase:@ "test"]; if (identity) {//The identity, certificate saved to keychain nsarray *cerarray = [Nsarray arraywithobje CT: (__bridge ID) certificate]; Nsurlcredential *credential = [nsurlcredential credentialwithidentity:identity certificates:cerarray Persistence: Nsurlcredentialpersistencepermanent]; Nsurlprotectionspace *certspace = [[NsurlprotectionspacE Alloc] initwithhost:@ "xxx.com" port:443 protocol:nsurlprotectionspacehttps realm:@ "Mobileapp" AuthenticationMethod : Nsurlauthenticationmethodclientcertificate]; [[Nsurlcredentialstorage Sharedcredentialstorage] setdefaultcredential:credential forProtectionSpace:certSpace]; } }}
Get identity,certificate from NSData
+ (void) Identity: (SECIDENTITYREF *) Identity Certificate: (SECCERTIFICATEREF *) certificate frompkcs12data: (NSData *) Certdata withphrase: (NSString *) phrase {//bridge the import data to foundation objects Cfstringref IMPORTPASSP Hrase = (__bridge cfstringref) phrase; Cfdataref ImportData = (__bridge cfdataref) certdata; Create Dictionary of options for the PKCS12 import const void *keys[] = {Ksecimportexportpassphrase}; const void *values[] = {Importpassphrase}; Cfdictionaryref importoptions = cfdictionarycreate (null, keys, values, 1, NULL, NULL); Create array to store import results cfarrayref importresults = cfarraycreate (null, 0, 0, NULL); Osstatus pkcs12importstatus = Secpkcs12import (ImportData, ImportOptions, &importresults); if (Pkcs12importstatus = = errsecsuccess) {Cfdictionaryref identityandtrust = Cfarraygetvalueatindex (ImportResults, 0); Retrieve the identity from the certificate imported const void *tempidentity = Cfdictionarygetvalue (Identityandtrust, ksecimportitemidentity); *identity = (secidentityref) tempidentity; Extract certificate from the identity seccertificateref tmpcertificate = NULL; Secidentitycopycertificate (*identity, &tmpcertificate); *certificate = (seccertificateref) tmpcertificate; }//Clean up if (importoptions) {cfrelease (importoptions); } if (importresults) {cfrelease (importresults); }}
2.2.2 Because Willsendrequestforauthenticationchallenge will be called multiple times during server and client authentication, it is necessary to determine which challenge to handle. The following code is used to determine whether a client certificate should be issued or authenticated using a user credential that is subject to discrimination.
-(void) connection: (Nsurlconnection *) connection Willsendrequestforauthenticationchallenge: ( Nsurlauthenticationchallenge *) Challenge {//Use client certificate authentication nsurlprotectionspace *clientcertificateprotectionspace = [[Nsurlprotectionspace alloc] initwithhost:@ "xxx.com" port:443 Protocol:nsurlprotectionspacehttps realm:@ "mobileApp [Authenticationmethod:nsurlauthenticationmethodclientcertificate]; if (Challenge.protectionSpace.authenticationMethod = = Nsurlauthenticationmethodclientcertificate && isdeviceregisted) {if (Challenge.previousfailurecount = = 0) {//Read locally stored client certificate nsurlcredent ial *cred = [[Nsurlcredentialstorage sharedcredentialstorage] Defaultcredentialforprotectionspace: Clientcertificateprotectionspace]; if (cred) {[Challenge.sender usecredential:cred forauthenticationchallenge:challenge]; }} else {[Challenge.sender cancelauthenticationchallenge:challenge]; and prompt for user authentication failed}} else {//Use other authorization methods, such as HTTP Basic, HTTP Digest, NTLM, see 2.1 Standard Quasi-Authentication Code}//If it is not the type that the app can handle, it does not respond to authentication and continues to connect [Challenge.sender Continuewithoutcredentialforauthenticationchallenge:cha Llenge]; }
At the service level, you can retrieve the properties of a certificate through the Openssl_x509_parse () function. After you obtain the certificate properties, you can use many of the authentication options at the server level. One of the options is like validating the request initiator, and then finding the user in the list of known private keys. Another option is to use the PIN mechanism in your app to authenticate before issuing a client certificate to authentication.
If it is a self-signed SSL certificate, nsurlconnection will intercept the server response without a trusted certificate. Therefore, the server certificate (. cer file extension) needs to be sent as a message to the configured email account on the device, and the certificate can be installed on the stand-alone basis.
Securing the implementation of network transmissions