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);
Related
Can't get past Django Rest Framework Token Authorization because I can't set withCredentials=true using OkHttp RequestBuilder. (I'm referring to this https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials)
In javascript using axios.post this works fine. I'm having trouble converting this post request to android using OkHttp request builder.
Request builder only seems to give setter methods for Header and Body of post Request?
Tried reading through OkHttp documentation and I've also tried to send withCredentials=True as a header
Django Rest Framework backend not recognizing the token and not resolving the bearer token to a user.
If no class authenticates, request.user will be set to an instance > of django.contrib.auth.models.AnonymousUser, and request.auth > will be set to None.
I'm going to assume here that withCredentials is a query parameter.
Appending ?withCredentials=true. to the end of the URL will probably get things going for you.
An example in full might look like https://www.example.com?withCredentials=true.
With multiple parameters, it may look like https://www.example.com?withCredentials=true&otherParam=Stuff.
I'm using LoginActivity template and I'm trying to login to a website with email and password using a standard http request. The site doesn't provide an API so I'm thinking of somehow mirroring the site login to fill the email and password boxes on the page then sending the login request.
Think of logging in to stackoverflow for example by taking the input of an email and password TextView (s) and sending a standard http request to the authentication server with those credentials exactly how it would happen in the browser (same requests and addresses).
I haven't done anything like this before and I have no idea if it's even possible so please forgive any ignorance on my part.
This is done in Android in a similar fashion as in the web browser. Namely, you will send a POST request with proper parameters, let's say a JSON Object for the sake of explaining which contains something like:
{
username: 'myUsername'
password: 'mypass'
}
This will get processed and if your credentials are correct, you will get a response which may contain a variety of data, among which the accessToken (it may be called a slight variation of this).
You are supposed to remember this access token and use it to fetch any other data from the site, because that token is used from there on to authenticate you. I have an API I personally made, and I send the accessToken as a parameter in every request for a resource that is unavailable to the unregistered user.
As for the technical side, I'm using a nifty library called OkHttp for sending the Http requests, and it's quite rewarding and easy to use. Here's a code snippet to see what I'm talking about:
//JSON is a media type for parsing json
//json is a json string containing payload e.g. username and pass like in the example
OkHttpClient httpClient = new OkHttpClient();
RequestBody body = RequestBody.create(JSON, json);
Request request = new Request.Builder()
.url(url)
.post(body)
.build();
Response response = httpClient.newCall(request).execute();
The only thing left to to for you is to properly parse the response. You can find various solutions on this topic, but I personally use 2 approaches, BufferedReader for huge responses using response.body().byteStream(), and plain old String for not-so-large responses using response.body().string().
This is not a short, but very thorough explanation, so feel free to ask for clarification if you do not get some part.
Assuming that you need to log in to sites like StackOverflow from your app with standard http request. That is simply impossible. Because no organizations will allow third party sites/apps handling their users' credentials. If they intend to share their resource with third party most organizations follow this procedure:
First they provide api for you to use.
With that api only you can make users to login i.e you can't handle those credentials
Then they give a token to you corresponding to the user.
With that token you can perform subsequent requests.
If the organization doesn't provide api then they most probably are in situation of not allowing third party sites/apps to access their users' resource.
I want my android app to periodically send location information to my django server.
Based on my research, android client should write the location in JSON, payload JSON in http post, and send http post request to django server periodically. and the http post request is created by the client directly, not from a post form by django. Is it a normal way?
If posting data without form is a general way, then to stop csrf verification, according to the answer of Android sending post requests to django server csrf failing, the android client should
"getting the token from the server and sending that along with the POST data "
(suppose I do not use solution of #csrf_exempt)
My question is where to get the csrftoken cookie?
I do see csrftoken cookie if I send a GET request to a post form, but if posting data directly (without asking for the post form), where does a client get the csrftoken cookie?
You could use an API like tastypie or rest-framework. The only way to get the token is by accessing the page that gives it.
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.
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?