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

查看:25
本文介绍了如何在 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 中间件添加到您的web 中间件组在您的 app/Http/Kernel.php 文件中:

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...
    LaravelPassportHttpMiddlewareCreateFreshApiToken::class,
],

这个 Passport 中间件会附加一个 laravel_token cookie 到你的传出的回应.此 cookie 包含一个加密的 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天全站免登陆