如何在Laravel中验证API路由的Vue.js/Axios请求 [英] How to authenticate Vue.js / Axios request of an API route in Laravel

查看:50
本文介绍了如何在Laravel中验证API路由的Vue.js/Axios请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Laravel 5.6中.我已经构建了所有API路由,并且可以正确响应来自REST客户端(Paw)的请求.我正在尝试构建一个简单的前端来访问这些路由.

I'm in Laravel 5.6. I have all my API routes built out and properly responding to requests from my REST client (Paw). I'm trying to build a simple front end to access those routes.

我试图尽可能多地使用Laravel的开箱即用功能,因此我正在使用Axios使用Vue.js从刀片模板调用这些路由.如果我在测试路由上禁用身份验证中间件,则可以使用它,但是当为路由启用身份验证中间件时,在控制台上会出现401错误.

I'm trying to use Laravel's out-of-the-box features as much as possible, so I'm using Axios to call those routes from a blade template using Vue.js. It works if I disable auth middleware on the test route, but I get 401 errors on the console when auth middleware is enabled for the route.

问题似乎很明显...我的/api 路由上的 auth:api 防护程序希望在标头中看到oauth令牌,但是当我登录时与网页进行会话身份验证.我认为有一种简单的方法可以解决此问题,而不必在Web前端中欺骗oauth令牌请求,对吗?我是否需要以某种方式在Axios的请求中传递会话令牌?而且,如果是这样,我是否还需要更改我的api路由文件中的 auth:api 保护?

The problem seems obvious enough... The auth:api guard on my /api routes wants to see an oauth token in the header, but when I log in with the web page it does session authentication. I assume there's a simple way to resolve this without having to spoof an oauth token request in the web frontend, right? Do I need to somehow pass the session token in my request with Axios? And, if so, do I also need to change the auth:api guard in my api routes file?

推荐答案

我解决了!我有点尴尬,因为答案实际上是在Laravel文档中,但是我会说我在将问题发布到此处之前尝试了此操作,但它没有用.也许当时还有其他问题.

I solved it! I'm a bit embarrassed because the answer was actually in the Laravel docs, but I will say I tried this before posting the question here and it wasn't working. Perhaps something else was broken at the time.

根据 Laravel文档:

您需要做的就是将 CreateFreshApiToken 中间件添加到您的您的 app/Http/Kernel.php 文件中的 web 中间件组:

All you need to do is add the CreateFreshApiToken middleware to your web middleware group in your app/Http/Kernel.php file:

'web' => [
    // Other middleware...
    \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,
],

此Passport中间件会将 laravel_token cookie附加到您的外向的回应.该Cookie包含一个加密的JWT,该JWTPassport将用于验证来自JavaScript的API请求应用.现在,您可以向应用程序的API发出请求没有显式传递访问令牌...

This Passport middleware will attach a laravel_token cookie to your outgoing responses. This cookie contains an encrypted JWT that Passport will use to authenticate API requests from your JavaScript application. Now, you may make requests to your application's API without explicitly passing an access token...

这篇关于如何在Laravel中验证API路由的Vue.js/Axios请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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