access laravel app from android app with csrf token
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
}
Related videos on Youtube
Dhiraj Wakchaure
Updated on October 13, 2022Comments
-
Dhiraj Wakchaure over 1 year
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 ?
-
Dhiraj Wakchaure over 8 yearsbut by using i think any android app can access my api
-
Ben Claar over 8 yearsCorrect, restricting who can use your app is an "authentication/authorization" problem, not a CSRF problem. CSRF only verifies that a POST request comes from the same client that made a prior GET request, it doesn't restrict who can use the site. Did I miss-understand your question?
-
Addi.Star over 7 yearsi need help in the same problem . i tried this solution but couldn't get through . please chek stackoverflow.com/questions/38672539/…