Access laravel app from Android app using csrf token

I will describe the framework of laravel, I installed version 5.0. I use it for a json api service that will give JSON output after calling a specific route. It works very well if I requrest the URL from the browser. but when I try to access from my Android application, it gives an error that the file did not find an exception (java.io.filenotfoundexception). after checking the log I got an indication that laravel has a Token disagreement exception error. laravel needs a csrf token to access resources. I have the option that I can disable this authentication, but it looks in a less secure way.

can I somehow allow access to the laravel application from my android application and not from another application? can we specify the csrf key from an android application?

+7
source share
2 answers

If you do not want to disable CSRF tokens, you will need to get the CSRF in one request, and then pass the extracted token along with the 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 } 
+12
source

I have tried

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

But it does not work

If you can try

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

it works for me

0
source

All Articles