The development of our app usually has 2 kinds of authentication way is basic Auth, one kind is oauth; now generally or use oauth more, and use basic Auth authentication less, just what I introduced today is the use of relatively few badic Auth authentication methods, This authentication mode development and debugging is simple, there is no complex page jump logic and interactive process, more conducive to the initiator control. The downside, however, is that security is lower, but it's OK, we can use HTTPS secure encryption protocol, which is more secure.
I am using the network request sent by afnetworking, so we can no longer use the default Get or POST request of AFN by using the basic Auth authentication method, but the nsmutablerequest request that we define, use AFN to send, like the following code:
HTTP GET request address NSString *urlstr=[nsstring stringwithformat:@ "https://192.168.1.157:8443/v1/sms/send/%@",
Self.username.text];
Nsurl *url = [Nsurl urlwithstring:urlstr];
Custom request Nsmutableurlrequest *request = [Nsmutableurlrequest Requestwithurl:url];
Request Expiration Time Request.timeoutinterval = 10; Get requested request.
HttpMethod = @ "Get";
Configure username Password NSString * str = [NSString stringwithformat:@ "%@:%@", @ "lairen.com", @ "sdclean.com"]; Encrypt [str base64encodedstring] Use open source Base64.h classified file encryption NSString * str2 = [NSString stringwithformat:@ "Basic%@", [str base
64EncodedString]];
[Request SETVALUE:STR2 forhttpheaderfield:@ "Authorization"];
Afhttprequestoperation *op=[[afhttprequestoperation Alloc]initwithrequest:request];
Sets the return data to JSON data op.responseserializer= [Afjsonresponseserializer serializer];
Send Network Request [op setcompletionblockwithsuccess:^ (afhttprequestoperation *operation, id responseobject) { NSLog (@ "%@", responseobjECT);
} failure:^ (Afhttprequestoperation *operation, Nserror *error) {NSLog (@ "%@", error);
}]; Request complete return to main thread [[Nsoperationqueue mainqueue] addoperation:op];
Use basic Auth authentication method, AFN Send network request is the above code format, which some difficult to understand the point of code, I made a note in the following figure;
The first one I'm commenting on is the username, the second is the password, the request header that makes our basic Auth authentication must be set, and then the third one is that we Base64 encrypt the username and password strings for my security, and the 2 files used are open source Base64.h BASE64.M. GitHub can be downloaded above.
This line in the above code is to encrypt the string, remember to use the BASE64.H classification method of encryption, must first import Base64.h file can be so encrypted.
[Str base64encodedstring]
NSString * str2 = [NSString stringwithformat:@ "Basic%@", [str base64encodedstring]];
Here our basic AUTH certification way is finished, how, very simple.