Post an image from Android client to Rails server without triggering InvalidAuthenticityToken - android

I'm building an Android app that runs off of a rails server. At first, when I tried to post simple String data to the server, I ran into an InvalidAuthenticityToken issue, but realized that I can bypass the authentication by setting the content type to "json"
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(Constants.REST_HOST + "/add_comment");
post.addHeader("Content-Type", "application/json");
The next step was trying to get upload profile picture working. However, when I tried uploading a photo via a MultipartEntity post, setting the content type to "json" causes the following error
StandardError (Invalid JSON string):
but not setting the content type brings back the InvalidAuthenticityToken exception. What's the correct way to post an image to a rails server from a foreign Java client?
ActionController::InvalidAuthenticityToken
(ActionController::InvalidAuthenticityToken):

Based on Jesse's suggestion, I ended up using
protect_from_forgery :except => :upload_avatar_pic
to disable authenticity check, but only for a specific function, so checks for browser requests are still validated.

You can disable authenticity checking on API non-get calls from non-web clients. You can do this in a before filter
class ApiController < ApplicationController
skip_before_filter :verify_authenticity_token
def create
#or whatever
end
end

The problem solved by Jesse Wolgamott said, but the page show "You are being redirected" message when I submit the form (Update,create,show). In before that the page redirected correctly. I am using rails 2.3.8.how to resolve this?

Related

Android Calling Django Server With POST Data

someone may asked my question already but I cannot find any suggestions.
I writing an Android app which needs to access my Django server by using HttpsURLConnection then Django server will return a JSON array to Android.
The view function in Django will receive the parameters from request.POST and generate the JSON array then return using HTTPResponse Django method. It does not need any Templates and Forms.
When I call the Django view function from Android, it returns 403 error. I know that it is because the POST data does not contains "csrf_token".
My problem is: How can I get the "csrf_token" and put it into my POST data before I send it to Django? I try disable the CSRF checking by "#csrf_exempt" it can return the correct result to Android app but I would not disable the CSRF checking.
Thanks,
Wilson
You have to send the cookies and also have to send a header 'X-CSRFToken' with csrftoken.
This is what I do (may not be the best way):
Get csrf token via a get request.But first try to see if you get a csrftoken cookie by doing same request on your browser with developer tools. If not, you should use ensure_csrf_cookie decorator
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def your_view(request):
pass
Now using the same HttpUrlConnection object do this :
String cookieString="";
String csrftoken="";
// The below code can be shortened using for-each loop
List<HttpCookie> cookies=cookieManager.getCookieStore().getCookies();
Iterator<HttpCookie> cookieIterator=cookies.iterator();
while(cookieIterator.hasNext()){
HttpCookie cookie=cookieIterator.next();
cookieString+=cookie.getName()+"="+cookie.getValue()+";";
if(cookie.getName().equals("csrftoken")){
csrftoken=cookie.getValue();
}
}
Add the following to your post request:
urlConnection.setRequestProperty("X-CSRFToken", csrftoken);
urlConnection.setRequestProperty("Cookie", cookieString);

Android REST API

I need to access this url and put user name and password I am trying a HTTP Post request with parameter but it's giving an error.Can any one help me how can I access this url from android.
https://54.204.193.209:943/rest/GetUserlogin
Getting ERROR
javax.net.ssl.SSLPeerUnverifiedException: No peer certificate
When I tried to access your url, pop up comes up asking to enter credentials that means at server side, HTTP Basic Authentication has been enabled.
To access anything on server, you have to go through it. Add following code :
// Set credentials for HTTP Basic Authentication
defaultHttpClient.getCredentialsProvider().setCredentials(
new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
new UsernamePasswordCredentials(
HTTPS_BASIC_AUTH_USERNAME,
HTTPS_BASIC_AUTH_PASWORD));
Credentials for HTTP basic auth is unique for one server, hence you can hardcode it in your java code.
Hope, this will help you.

Authentication for GET Request in Android HTTP/1.1 406 Not Acceptable

I tried but there seems to be a problem in making a GET Request to a heroku URL example "https://xxxx-xxxxx.herokuapp.com/xxxxxx/xxxxxxxx"
I know the general method is
HttpClient client = factory.getHttpClient(); //or any method to get a client instance
Credentials credentials = new UsernamePasswordCredentials(username, password);
client.getState().setCredentials(AuthScope.ANY, credentials);
And I know that getState() is not available for 3.x version.
I don't know how the Chrome's "Advance REST Client" has handled it, it gave me the pop up and asked for the username and password and I entered Credentials and it worked and since then its working fine. I thought It might have stored the credential locally but, its not the case. I checked all the cookies and cache. I deleted the extension and cleared data and its still working.
Then I tried to use another REST Client by WizTools (for Mac). In the Authorization section there are 3 options. 1.) Basic, 2.) Digest and 3.)Preemptive, I did some permutation and combination with it using the given Credentials but all the time it gave the same response i.e.
"HTTP/1.1 406 Not Acceptable"
I don't understand what's the issues is?
Thanks,
I don't know, if why is it not working, but I used URLConnecton used the authentication mentioned and it worked. I got the response. And yeah BTW I had to assign the "Accept" type a s "Application/Json"

android - build application to authenticate with web server

I'm trying to make an application that needs authentication :- when user type username and pw in the text boxes it should check with the DB in the server and authenticate.
how can i do this in the android?
can please any one help me??
thank you,
If you are a web developer you can do this authentication very easily. You can follow the following steps,
First, get the username and password from the user and put in the variables.
Create the HTTP connection to the web server (Your data posting URL).
Post the data to the URL with specified data using HTTP Get or Post method(Post is preferable for authentication)
Get the posted value using server side script and do the authentication.
send the response status to the client by using JSON encoding or some other format whether the authentication is succeeded of failure.
Get the response in android and create the InputStream and decode the JSON or some specified encoding format which you done in the server side and shown the response in mobile.
Thats it.

Android - Basic Authenticated HTTP Request

So basically i need my android app to connect to a web service using a url as such
"http://username:password#0.0.0.0" aka basic authentication.
obviously the username and password are checked by the web app before allowing access and otherwise doesn't allow the request.
my issue is that all the methods i try always say unauthorised (response code 401) regardless of what combination of classes and methods ive used to try and connect to the the url.
The web app in question is designed to return things only is un/pw clears otherwise it returns nothing, the web app and un/pw etc have all be checked and cleared.
so does anyone no the correct way to send a request to a url like that and have it work correctly?
android api8 btw
UPDATE
Turns out my issue is due to the web app using NTLM windows authentication which is not supported directly by androids/apache http library, investigating appropriate workarounds now
Here's some code form a really old project of mine. I used basic auth for some web service, and this worked at the time. I'm not sure if there are updated api's since then (this was Android 1.6), but it should still work.
HttpGet request = new HttpGet();
request.setURI(new URI(url));
UsernamePasswordCredentials credentials =
new UsernamePasswordCredentials(authUser, authPass);
BasicScheme scheme = new BasicScheme();
Header authorizationHeader = scheme.authenticate(credentials, request);
request.addHeader(authorizationHeader);
Basically, Basic HTTP auth is a simple hash of the user and password. The browser allows you to stuff these values in the url, but it actually does the work of adding the basic auth header to your request.

Categories

Resources