access laravel app from android app with csrf token

江枫思渺然 提交于 2019-12-18 12:34:14

问题


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 ?


回答1:


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
}



回答2:


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



来源:https://stackoverflow.com/questions/31627477/access-laravel-app-from-android-app-with-csrf-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!