使用csrf令牌从android应用访问laravel应用 [英] access laravel app from android app with csrf token

查看:174
本文介绍了使用csrf令牌从android应用访问laravel应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用laravel框架,我已经安装了5.0版本. 我将其用于json api服务,该服务将在调用某些路由后提供JSON输出. 如果我从浏览器中获取URL,它会很好地工作.但是当我尝试从我的Android应用程序访问时,它给出错误,即文件未找到异常(java.io.filenotfoundexception). 检查日志后,我明白了laravel有令牌不匹配异常的错误. laravel需要csrf令牌才能访问它的资源. 我可以禁用该身份验证,但似乎不太安全.

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.

我能以某种方式允许我从android应用程序访问laravel应用程序,而不允许其他应用程序访问吗?我们可以从android应用程序指定csrf密钥吗?

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 ?

推荐答案

如果您不想禁用CSRF令牌,则需要在一个请求中检索CSRF,然后将检索到的令牌与POST请求一起传递

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
}

这篇关于使用csrf令牌从android应用访问laravel应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆