当前位置: 移动技术网 > IT编程>开发语言>PHP > Laravel5.3+框架定义API路径取消CSRF保护方法详解

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

2020年05月10日  | 移动技术网IT编程  | 我要评论

本山带谁上春晚第二季全集,爱发呆的红骑士,李二妹

从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框架的使用技巧请查看下面的相关链接

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网