如何在 Laravel 中验证 API 路由的 Vue.js / Axios 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/50193349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:42:07  来源:igfitidea点击:

How to authenticate Vue.js / Axios request of an API route in Laravel

laravelauthenticationvue.jsaxios

提问by jreikes

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 5.6 中。我已经构建了所有 API 路由并正确响应来自我的 REST 客户端 (Paw) 的请求。我正在尝试构建一个简单的前端来访问这些路由。

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.

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

The problem seems obvious enough... The auth:apiguard on my /apiroutes 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:apiguard in my api routes file?

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

回答by DigitalDrifter

You will probably want to use Larvel Passportor a JWT auth mechanism for obtain the Authorizationtoken.

您可能希望使用Larvel Passport或 JWT 身份验证机制来获取Authorization令牌。

Seeing as how you're using axios, add a request interceptor to attach the access token to every request once you successfully authenticate. A simple example:

看看您如何使用 axios,添加一个请求拦截器,以便在您成功进行身份验证后将访问令牌附加到每个请求。一个简单的例子:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    // assume your access token is stored in local storage 
    // (it should really be somewhere more secure but I digress for simplicity)
    let token = localStorage.getItem('access_token')
    if (token) {
       config.headers['Authorization'] = `Bearer ${token}`
    }
    return config;
  }, function (error) {
    // Do something with request error
    return Promise.reject(error);
  });

回答by jreikes

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 文档中,但我会说我在在这里发布问题之前尝试过这个,但它不起作用。也许当时还有别的东西坏了。

Per the Laravel docs:

根据Laravel 文档

All you need to do is add the CreateFreshApiTokenmiddleware to your webmiddleware group in your app/Http/Kernel.phpfile:

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

This Passport middleware will attach a laravel_tokencookie 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...

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

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

此 Passport 中间件将laravel_token在您的传出响应中附加一个cookie。此 cookie 包含一个加密的 JWT,Passport 将使用它来验证来自您的 JavaScript 应用程序的 API 请求。现在,您可以向应用程序的 API 发出请求,而无需显式传递访问令牌...