How do I get Ruby on Rails to work with ASIHTTPRequest? - iphone

I am creating an iOS application with a Ruby on Rails backend. I've got my logic setup and working in Rails, and have verified by testing in a web browser. My Rails application will not respond properly to my iOS application, saying something about an authenticity token.
I have setup an authenticity token in application.rb with the following code (I did a server reboot after adding this):
protect_from_forgery :secret => 'some_secret_here'
I'm passing the authenticity token from iOS to Rails with ASIHTTPRequest using the following code:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"some_secret_here" forKey:#"authenticity_token"];
[request setPostValue:#"some value" forKey:#"some_parameter"];
[request setDelegate:self];
[request startAsynchronous];
Is there anything I'm missing or doing wrong?
This same code works fine with allow_forgery_protection set to false, so I assume the error lies in how I'm trying to pass the authenticity token.

The authenticity token is different for each page/request, so you need to find a way to send it through the pipe some other way.
Maybe try sending it via headers, like so:
class ApplicationController < ActionController::Base
before_filter :send_form_authenticity_token
private
def send_form_authenticity_token
response.headers['X-Authenticity-Token'] = form_authenticity_token
end
end
On the response callback of your first (and following) request(s), you need to do:
NSString *authenticityToken = [[request responseHeaders] objectForKey:#"X-Authenticity-Token"];
This implies that the first request you do is a GET one.
Would be better to have a global state variable, but this is the basic concept.
By the way, and just so you know, you don't need forgery protection if your rails application is just a backend sorts of app.
Forgery protection is there to avoid XSS attacks, and that wouldn't happen on the iPhone.

Related

Authenticating iPhone application with Rails application

I have been doing research on this for quite some time and have not been able to solve my issue so I figure i'd ask. I have searched the other questions here on stackoverflow and other articles and they don't seem to get me in the right direction.
Here is what I am trying to do. I have a Rails 3 application that is only providing data in JSON format. The data will be entered by only 1 user so access to it will be very limited. I am using Devise so that it is protected via authentication.
I also have an iPhone application that will access this data. Since the Rails 3 application has username/password protection the iPhone application needs a way to authenticate with the application.
I have looked in to token authentication in Devise, but can't seem to get it to work. I have a loading symbol and it just spins and doesn't return any data. I also looked at http basic authentication. Again, haven't had any luck. On the iPhone side I am using ASIHTTPRequest. Following is what I am using for posting via the authenticity token:
//the url variable below is defined in my code but I did not paste that part
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
[request setPostValue:#"auth token" forKey:#"authenticity_token"];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request setDelegate:self];
[request startAsynchronous];
When I tried http basic authentication I passed a username and password and that didn't work as well with the same issue and not returning data. I am sure I am missing something, but I can't find the information I need to get this working. I took a look at RestKit, but it seems to have a lot more then I need.
I only need the iPhone application to access the JSON data with it being protected on the Rails 3 side. The iPhone user will not need to sign in via a sign in form or be able to create, update or delete any data. It is strictly read only. Can anyone push me in the right direction?
The easiest way is to using basic auth
In you api/application controller on the rails side add
before_filter :check_auth
def check_auth
authenticate_or_request_with_http_basic do |username,password|
resource = User.find_by_email(username)
if resource.valid_password?(password)
sign_in :user, resource
end
end
end
On the iOS side you should set the Authorization header on the request object:
ASIHTTP supports this out of box. Luck you.
[request setUsername:#"username"];
[request setPassword:#"password"];
or you can add them to the URI of your request.
NSURL *url = [NSURL URLWithString:#"http://username:password#allseeing-i.com/top_secret/"];
this will allow a sign in with basic auth and further controllers will get your user from the session
then on the ios side you can just pass credentials like you would with any basic auth system.
I recommend using SSL/HTTPS in production or credentials will be passed in plain text or base64.

How to initiate webservice request that expects JSON payload

I am JSON newbie and can't find any material on how to simulate JSON payload request.
My ultimate goal is to be able to build an objective-c iOS app that will handle these request-response. I am aware of ASIHttprequest framework and the request-response mechanism it works around.
However right now I have a webservice api which expects various json payloads and also provides response in json format. Here is an example:
Example URL:
https://mywebServiceURL/api/ApiKey/user/create
The ContentType header = “application/json”.
Payload: The PUT payload is a JSON dictionary, containing the following keyvalue pairs:
email
screenName
User’s screen name.
password
passwordConfirm
phoneNumber (optional)
User’s phone number (optional)
picture A png file (64x64), encoded as a Base64 string (optional)
Now my questions:
1 - how do I simulate this normally (outside ios, just for the sake of testing)? I searched google but can't find exactly what I need, I got curl.exe but it gives me same as what a browser gives, like method not allowed etc. But that's not the only thing I want. I want to play with various requests, supply values and take the api for a ride for sometime before I know how it really works for PUT, GET, POST etc.
2 - what is the best way to incorporate such stuff into iOS? I already have ASIHttp for web requests and JSONKit for JSON handling included in my project.
I have done this kind of stuff but with xml responses, get requests. JSON I am working for the first time. Just a pointer to an example stuff like this would be a great help.
There are several Chrome extensions, such as Advanced REST client or REST Console, that you can use to simulate REST calls. These are very quick and easy to install into your browser and will allow you to construct requests and view the response.
I recommend using the open source iOS networking library AFNetworking. This library has built in support for REST calls and JSON parsing. It is very easy to get up and running, and is very powerful if you need more advanced features.
Hope this helps.
Jsut to add upon Andy's suggestions as I have used similar kind of things in one of my recent app.
Used Chrome extension Poster for testing REST calls.
Used ASIHttpRequest for handling async queries.
Sample code snippet
//dictionaryData contains the login user details
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryData options:kNilOptions error:nil];
NSString *jsonString = [[[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding]autorelease];
//Handling ASI requests
ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:uri];
[request addRequestHeader:#"Content-Type" value:#"application/json"];
[request addRequestHeader:#"Accept" value:#"application/json"];
[request appendPostData:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
[request setRequestMethod:#"POST"];
[ASIHTTPRequest setDefaultTimeOutSeconds:30];
request.delegate = self;
[request startAsynchronous];

ASIHTTPRequest https request & SSL

I'm trying to send out a very simple ASIHTTPRequest with https. Although I have set the validatesSecureCertificate flag to "NO", I still get an odd response for my request:
A connection failure occurred: SSL problem (Possible causes may include a bad/expired/self-signed certificate, clock set to wrong date)
The code I am using is pretty straightforward, I am removing the actual parameters for security reasons:
NSURL *url = [NSURL URLWithString:#"https://secured.cet.ac.il/KotarServices/getMyBooks.aspx?username=xxxxxxxx&password=xxxxx&packageid=x"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request setDidFailSelector:#selector(getMyBooksFailedWithError:)];
[request setDidFinishSelector:#selector(getMyBooksFinishedWithResult:)];
[request setDelegate:self];
[request setValidatesSecureCertificate:NO];
[request startAsynchronous];
Digging deeper into the code, I see that the request fails on a "-9807" error code, which is related only to the operating system and has nothing to do with the server I am interacting with (SecureTransport.h maps this out to be "invalid certificate chain"). Any ideas how to overcome this issue? Thanks in advance.
I remember i had a similar problem with a GoDaddy certificate and had to make the following change in ASIHTTPRequest.m, below the comment "Handle SSL certificate settings", inside the if(![self validatesSecureCertificate]), around line 1160:
[sslProperties setObject:(NSString *)kCFBooleanTrue forKey:(NSString *)kCFStreamSSLAllowsAnyRoot];
I ran into this with a GoDaddy certificate I just bought today. One correction to trydis's solution: I think you want this outside the if(![self validatesSecureCertificate]), since you actually want to validate the certificate. As the comment says, stuff inside the if clause "tells CFNetwork not to validate SSL certificates". TBH, I have no idea why the GoDaddy certificate is being interpreted by the client as a root certificate, which is what's necessitating this change in the first place.

ASIHTTPRequest and web services secured

I am using ASIHTTPRequest in my IOS application to call a wsdl/SOAP web services. my clients use a security mod ( with his ModSecurity / a PHP code).
i am using this :
NSData *xmlData = // I construct the soap message witk soapui
NSURL *url = [NSURL URLWithString:#"https:myUrlWSDL"];
self.currentRequest = [ASIFormDataRequest requestWithURL:url];
[self.currentRequest appendPostData:xmlData];
[self.currentRequest setDelegate:self];
[self.currentRequest startAsynchronous];
But the server send to me the 400 bed request.
How i can, please, do to call my wsdl/web services with all this security mode ? what are the http headers required to call the web services ? thanks for your answers
i have disabled the secure module. now i have this error :
WSDLSOAP-ERROR: Parsing WSDL: Couldn't load from 'http://...?wsdl' : failed to load external entity "http://...?wsdl"
That's how you use ASI to call a secure connection - you're doing everything correctly.
The problem must be in your code that creates the xmlData - what other error information can you get back from your clients server?
You might also need to add more headers to the request (though thats also something that your clients should be able to tell you) - e.g.
[request addRequestHeader:#"Referer" value:#"http://allseeing-i.com/"];

iOS: How to make a secure HTTPS connection to pass credentials?

I am creating my first iPad app. I have a web application that I would like to authenticate against and pull data from in a RESTful way.
If you open up the URL in the browser (https://myapp.com/auth/login), you will get a form to enter your username and password. I was thinking I could set the login credentials in the post data of the request and submit the data.
The site uses HTTPS for login so that credentials aren't passed in plain text over the internet.
How can I make a secure HTTPS connection to pass credentials? Will this remember that I am logged in for future requests? What is the best way to do this?
Further update, October 2013
Although at the time I wrote this answer, ASIHTTPRequest was maintained a widely supported, this is no longer the case. It is not recommended for new projects - instead use NSURLConnection directly, or use AFNetworking.
With AFNetworking, there is a [httpClient setAuthorizationHeaderWithUsername:username password:password]; method for http authentication, and create a POST style form is equally easy - see AFNetworking Post Request for that.
Original answer:
A lot of people use the ASIHTTPRequest class to deal with http & https on the iPhone/iPad, as it has a lot of useful features that are difficult or time consuming to achieve with the built in classes:
http://allseeing-i.com/ASIHTTPRequest/
Starting at the simplest level you'd start with something like:
NSURL *url = [NSURL URLWithString:#"http://allseeing-i.com"];
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
[request startSynchronous];
NSError *error = [request error];
if (!error) {
NSString *response = [request responseString];
NSLog(#"response = %#", response);
}
If you're using HTTP authentication, ASIHTTPRequest will automatically prompt the user for the username and password.
IF you're using some other form of authentication you probably need to request the username and password from the user yourself, and submit them as a POST value or a custom http header, and then the response may either include a token in a JSON or XML response, or it could set a cookie.
If you add more details as to how the authentication scheme works I can be a bit more specific.
Update
Based on the update, to emulate a POST form you'd just need to add lines like:
[request addPostValue:usernameString forKey:#"username"];
[request addPostValue:passwordString forKey:#"password"];
You will also need to change the way you create the request, instead of:
ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
do:
ASIFormDataRequest *request = [ASIFormDataRequest requestWithURL:url];
(I also forget to mention it above, there's code I put earlier is using a synchronous request, so you'd want to replace it with an asynchronous one to avoid blocking the UI once you'd proved it was working.)
There's a JSON framework for the iphone here:
http://code.google.com/p/json-framework/
which works well for me and is simple to use with ASIHTTPRequest.