Home » Android » php – access laravel app from android app with csrf token

php – access laravel app from android app with csrf token

Posted by: admin June 15, 2020 Leave a comment

Questions:

I am leaning laravel framework, i have installed 5.0 version.
i use it for json api service which will give JSON output after calling certain route.
it works very well if i requrest URL from browser. but when i am trying to access from my android app it gives error that file not found exception (java.io.filenotfoundexception).
after checking log i got point that laravel has error of Token Mismatch Exception. laravel need csrf token to access it resources.
I have option that i can disable that authentication but it seem less secure way.

can somehow i can allow access to laravel app from my android app not from other app ? can we specify csrf key from android app ?

How to&Answers:

If you don’t want to disable CSRF tokens, then you will need to retrieve the CSRF in one request, then pass the retrieved token along with your POST request.

// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();

// Get the CSRF token
httpClient.execute(new HttpGet("http://www.yoursite.com/"));
CookieStore cookieStore = httpClient.getCookieStore();
List <Cookie> cookies =  cookieStore.getCookies();
for (Cookie cookie: cookies) {
    if (cookie.getName().equals("XSRF-TOKEN")) {
        CSRFTOKEN = cookie.getValue();
    }
}

// Access POST route using CSRFTOKEN
HttpPost httppost = new HttpPost("http://www.yoursite.com/your-post-route");

try {
    // Add your data
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
    nameValuePairs.add(new BasicNameValuePair("_token", CSRFTOKEN));
    nameValuePairs.add(new BasicNameValuePair("stringdata", "Hello!"));
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    // Execute HTTP Post Request
    HttpResponse response = httpclient.execute(httppost);

} catch (ClientProtocolException e) {
    // TODO Auto-generated catch block
} catch (IOException e) {
    // TODO Auto-generated catch block
}

Answer:

I tried

...
nameValuePairs.add(new BasicNameValuePair("_token", CSRFTOKEN));
...

But it doesn’t work

If you can try

request.addHeader("X-CSRF-Token", token);

it works for me