php - 使用 csrf token 从 android 应用程序访问 laravel 应用程序

标签 php android json laravel csrf

我正在学习 laravel 框架,我已经安装了 5.0 版本。 我将它用于 json api 服务,它将在调用特定路由后提供 JSON 输出。 如果我从浏览器请求 URL,它工作得很好。但是当我试图从我的 android 应用程序访问时,它给出了错误,即文件未找到异常 (java.io.filenotfoundexception)。 检查日志后,我发现 laravel 有 token 不匹配异常错误。 laravel 需要 csrf token 来访问它的资源。 我可以选择禁用该身份验证,但它似乎不太安全。

我能否以某种方式允许从我的 android 应用程序而不是其他应用程序访问 laravel 应用程序?我们可以从 Android 应用程序指定 csrf key 吗?

最佳答案

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

// 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
}

关于php - 使用 csrf token 从 android 应用程序访问 laravel 应用程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31627477/

相关文章:

php - 从异常中重新启动实体管理器

android - 在区域内的 TextView 中将文本居中时出现问题

json - Swift 4 JSON 解析(预期解码 Array<Any> 但发现字典)

java - 如何使用类型安全配置解析 JSON 数组?

PHP: undefined index !但它被定义

php - 使用 iframe 的任何缺点

php - PDO 在 PHP 中与多个数据库连接查询

android - 手机增强现实

android - 如何以编程方式更改 ACRA 'interaction mode' 设置

android - React native 中的 CSV 预览