Objective-C and Preemptive Authentication - iphone

I am trying to get data from WebService for my Ipad App.
To do that, I am using a NSURLConnection with NSMutableURLRequest.
Web Services are published on Apache-Coyote 1.1 with Preemptive Basic Authentication, but I don't know how to send my credentials from Objective-C.
Anybody knows how can I set my user/password in Objective-C to log my clients with the Apache premptive authentication system?
Thank you.

EDIT:
In order to set the creds yourself, you'll need to be able to base64 encode the username and password and set the appropriate header. Matt Gallagher, from Cocoa With Love, has a great post on how to add a category to NSData to easily do this.
NSString* username = #"username";
NSString* password = #"password";
NSString* encodedUsername = [[username dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSString* encodedPassword = [[password dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
NSURL* url = [NSURL URLWithString:#"http://yourUrl.com/"];
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:url];
NSString* headerValue = [NSString stringWithFormat:#"Basic %#:%#", encodedUsername, encodedPassowrd];
[request addValue:#"Authorization" forHTTPHeaderField:headerValue];
[NSURLConnection connectionWithRequest:request delegate:self];
As with all use of credentials, please make sure you are doing this all over HTTPS because these credentials are essentially being passed in clear text.

Consider using the ASIHTTPRequest framework, which makes preemptive Basic authentication requests simple:
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com/top_secret/"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setAuthenticationScheme:(NSString *)kCFHTTPAuthenticationSchemeBasic]; /** preemptively present credentials **/
[request setUsername:#"username"];
[request setPassword:#"password"];
[request startSynchronous];
NSError *error = [request error];
if (!error)
NSString *response = [request responseString];
And, yes, you definitely want to do Basic authentication over SSL (i.e. via some https://... URL).

Related

cURL web services from iphone

I need to fetch data from curl web services from iOS, the client provided me a header name, header value and a base url, I dont know what to do with them, the url isn't giving me anything opening in a browser. They mentioned data is JSON encoded.
Please link me to some library or tutorial on how to call them.
You can use ASIHTTPRequest for cURL as well.
what I have used is:
NSURL *url = [NSURL URLWithString:url];
__weak ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:url];
[request setDelegate:self];
request.shouldPresentCredentialsBeforeChallenge = YES;
[request appendPostData:[JSONString dataUsingEncoding:NSUTF8StringEncoding]];
[request setUsername:username];
[request setPassword:password];
[request setRequestMethod:#"PUT"];
request.timeOutSeconds = 30;
request.validatesSecureCertificate = NO;
[request startAsynchronous];
solved it, had to set NSURLRequest http method and header like
[request setHTTPMethod:#"GET"];
[request setValue:#"HEADER_VALUE" forHTTPHeaderField:#"HEADE_RNAME_"];

What I did is correct or not? When I send an audio file to server in NSData

I am recording audio in a .wav format and converting the .wav1 file to NSData and sending to server.
Recorded path is:
file://localhost/var/mobile/Applications/8F81BA4C-7C6F-4496-BDA7-30C45478D758/Documents/sound.wav
I am sending to the server using:
audioURL=#"file://localhost/var/mobile/Applications/8F81BA4C-7C6F-4496-BDA7-30C45478D758/Documents/sound.wav";
NSURL *url=[NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL: url];
[request setHTTPMethod: #"POST"];
[request setValue: #"multipart/form-data" forHTTPHeaderField: #"Content-Type"];
NSData *audiodata = [NSData dataWithContentsOfURL:audioURL];
NSMutableData *highScoreData = [NSMutableData data];
[highScoreData appendData:audiodata];
[request setHTTPBody:highScoreData];
nsurlConnection = [[NSURLConnection alloc] initWithRequest: request
delegate: self];
When I play this back it gives me the right recorded voice. However, when I play the same recorded voice from the server it says "quotation" instead of the actual recorded voice.
My full code of how I did audio recording and how i send the audio can be found here.
Please tell me if the way I did this(i.e, to sending to server) is correct or not?
Multipart requests don't work that way. You need boundaries to differ between different data. Please check: http://www.w3.org/Protocols/rfc1341/7_2_Multipart.html
For the solution, I use AFNetworking (https://github.com/AFNetworking/AFNetworking).
The AFHTTPClient can create multipart requests for you.
Check: http://afnetworking.github.com/AFNetworking/Classes/AFHTTPClient.html#//api/name/multipartFormRequestWithMethod:path:parameters:constructingBodyWithBlock:
Here is the code I use to upload. The header part depends on how your server handles this.
AsiFormdata is more proper here.
NSString* fileString;
fileString = [[self documentsPath]
stringByAppendingPathComponent:#"testcombine.m4a"];
NSData* songData=[NSData dataWithContentsOfFile:fileString];
NSURL *url = [[NSURL alloc] initWithString:[NSString stringWithFormat:#"http://%#/UsingWebServer2/UploadServlet",RemoteEndpoint]];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setData:songData withFileName:#"upload_test.m4a" andContentType:#"audio/m4a" forKey:#"file"];
//[request appendPostData:[Jstring dataUsingEncoding:NSUTF8StringEncoding]];
[request startSynchronous];
If you want to send the data via multipart/form-data, use ASIFormDataRequest. Find documentation here for more reference.

Creating XML requests and sending them to server using ASIHttpRequest

I am trying to generate XML request to be sent to server over Http Post. I am aware of ASIHttpRequest library and want to use it.
I have two questions regarding this:
1) How to generate XML request? (Which is best library to use? GData/libXML/KissXML? or else?)
2) How to send it to server using ASIHttpRequest?
Please help.
Thanks in advance.
Achieved it this way:
NSString* newStr = [[NSString alloc] initWithData:postBody
encoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:urlstr];
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"r" forKey:newStr];
request.delegate = self;
[request startSynchronous];

NSMutableURLRequest loses session information

I have an iphone app that I'm trying to get to talk to a rails back end. I'm using NSMutableURLRequest to pull data back and forth. All the calls work fine on GET requests but when I need to post data, my rails app can't seem to find the session. I've posted the code below for both a get and a POST request.
This is the POST request:
//Set up the URL
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/players.xml"];
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
//To create an object in rails
//We have to use a post request
////This is the format when using xml
NSString *requestString = [[NSString alloc] initWithFormat:#"<player><team_game_id>%#</team_game_id><person_id>%#</person_id></player>", game, person];
NSData *requestData = [NSData dataWithBytes:[requestString UTF8String] length:[requestString length]];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:requestData];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
//For some reason rails will not take application/xml
[request setValue:#"application/xml" forHTTPHeaderField:#"content-type"];
The get request is:
NSString *url_string = [NSString stringWithFormat:#"https://testserver.example.com/people/find_by_passport?passport=%i", passport];
passportString = [[NSMutableString alloc] initWithFormat:#"%i", passport];
NSLog(#"The passport string is %#", passportString);
NSLog(url_string, nil);
NSURL *url = [NSURL URLWithString:url_string];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestReloadIgnoringCacheData
timeoutInterval:30];
I am at my wits end here trying to find out whats going on so any help would be GREATLY appreciated.
Faced the same issue. Parse the response headers for the Set-Cookie header, extract the cookies by hand, pass them back as Cookie: header on subsequent requests.
If this is just about sessions in their simplest, you don't have to worry about persistence, HTTPS, domains/paths and such.
EDIT: I found class NSHTTPCookieStorage. See if it can be of help...

iPhone development: How to implement HTTPS connection?

I am working on an iPhone project which need to connect to the IIS server over HTTPS or SSL protocol. Can anyone tell me how to implement HTTPS connection in iPhone? Any advice would be appreciate.
Thank you in advance.
Ben Copsey's ASIHTTPRequest framework makes it trivially easy to issue web requests over SSL.
Modifying the site's example slightly:
NSURL *url = [NSURL URLWithString:#"https://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog (#"%#", response);
}
Just use NSURLConnection with an NSURLRequest pointing to an NUSUL with https protocol, just like that:
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"https://mySecureServer.net"]];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!error) {
//do something with response & data
}
But I suggest you have a look at the documentation of the URL loading system in Cocoa.
Jason don't forget to implement the connection:canAuthenticateAgainsProtectionSpace and connection:didReceiveAuthenticationChallenge to make sure you're handling the challenges for the Server authentication and Client Authentication:
check out this post that will help you with this https://devforums.apple.com/message/143091#143091
You probably don't have a public certificate. Can you access the https resource with firefox/safari/chrome without an error? if not - that's the problem, not your code.