Laravel 5.3+ 如何定义API路径(取消CSRF保护)

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

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.

所以,请注意你页面的表单中是否使用了POSTPUTDELETE方法,如果有,并且你没有在表单中添加相应的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.phpweb.php同处于routes文件夹下。

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

http://my-web-site/api/wechat

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

转载:https://blog.sbot.io/articles/10

猜你喜欢

转载自blog.csdn.net/qq_30202073/article/details/84647143
今日推荐