If we get authentication challenge as NSURLAuthenticationMethodHTTPBasic in your authentication challenge delegate method using NSURLConnection/NSURLSession, We need to pass the credentials in the 'Autherization' header field of the request.
Here is the objective C code to convert the user credentials to BASIC format.
NSString *username = @"username";
NSString *password = @"password";
NSString *authStr = [NSString stringWithFormat:@"%@:%@", username, password];
NSData *authData = [authStr dataUsingEncoding:NSASCIIStringEncoding];
NSString *authValue = [authData base64EncodedStringWithOptions:0];
[request setValue:[NSString stringWithFormat:@"Basic %@",authValue]
forHTTPHeaderField:@"Authorization"];
If you look at the code, It's a 4 step process.
- We need to place the colon in between username and password.
- Convert the above resulted string to data using ASCII Encoding.
- Convert the above resulted data into string using Base64 Encoding.
- Finally, Add Basic as a prefix to the above resulted string with a space in between.
Hope this post is useful. Feel free to comment incase of any queries.
No comments:
Post a Comment