您的位置:首页 > 编程语言 > PHP开发

Laravel5.3+框架定义API路径取消CSRF保护方法详解

2020-04-07 07:08 1221 查看

从Laravel 5.3+开始,API路径被放入了routes/api.php中。我们绝大多数的路径其实都会在web.php中定义,因为在web.php中定义的路径默认有CSRF保护,而API路径默认没有CSRF保护。在Laravel官网文档中写到:/p>

Any HTML forms pointing to POST, PUT, or DELETE routes that are defined in the web routes file should include a CSRF token field. Otherwise, the request will be rejected.

所以,请注意你页面的表单中是否使用了POST、PUT或DELETE方法,如果有,并且你没有在表单中添加相应的CSRF token时,你的请求将会失败。

有时候,我们可能不想要CSRF保护。比如我们想使用第三方软件测试表单提交,或者比如微信公众号接口的开发时,当微信服务器使用POST推送给我们消息时,如果开启了CSRF保护,那么请求肯定是失败的。

在这样的情况下,我们可以使用API路径来取消CSRF保护。

我们有两种办法来定义API Routes。

第一种办法:

将routes放进VerifyCsrfToken这个middleware的$except数组里:

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;

class VerifyCsrfToken extends BaseVerifier
{
/**
* The URIs that should be excluded from CSRF verification.
*
* @var array
*/
protected $except = [
'/api/my-route',
];
}

以上middleware的位置在app/Http/Middleware文件夹中。

第二种方法:

将routes放进api.php里:

<?php

use Illuminate\Http\Request;

/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/

Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});

Route::get('/wechat', 'WechatAPIController@some-method');
Route::post('/wechat', 'WechatAPIController@some-other-method');

api.php和web.php同处于routes文件夹下。

在api.php中添加的路径,在访问时,我们需要在路径前,加上api/前缀:

//www.jb51.net/api/wechat

好了,这样一来,我们就完成了API路径的定义,或者换句话说,取消了路径的CSRF保护。

本文主要讲解了Laravel框架定义API路径取消CSRF保护的操作方法,更多关于Laravel框架的使用技巧请查看下面的相关链接

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Laravel API CSRF