带有身份验证的 Laravel api 路由

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44861937/
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 16:14:39  来源:igfitidea点击:

Laravel api routes with auth

ajaxlaravelxmlhttprequestvue.jsaxios

提问by user3743266

I'm trying to make an api route that's only accessible if the user making the request is logged in. This is what I have in my routes/api.phpbut it returns {"error":"Unauthenticated."}

我正在尝试创建一个只有在发出请求的用户登录时才能访问的 api 路由。这就是我的内容,routes/api.php但它返回 {"error":"Unauthenticated."}

Route::group(['middleware' => ['auth:api'], function () {
    Route::post('schedules', ['uses' => 'Api\ScheduleController@store']);
});

Can this be done without laravel passport and how? I only need the route for in-app use for logged in users.

这可以在没有 laravel 护照的情况下完成吗?我只需要登录用户在应用程序内使用的路线。

回答by xmhafiz

I assumed the login mentioned is on "web" which using "session" as driver.

我假设提到的登录名是在使用“会话”作为驱动程序的“网络”上。

Your are getting this issue because "web" and "api" guard is using different driver for authentication. Take a look in config/auth.php. The "api" guard is using "token" as it's default driver.

您遇到此问题是因为“web”和“api”guard 使用不同的驱动程序进行身份验证。进去看看config/auth.php。“api”守卫使用“令牌”作为默认驱动程序。

Thus, you have few options to encounter this.

因此,遇到这种情况您几乎没有选择。

  1. Move the route for "schedules" in web.php. No worry, your ajax will failed if not authenticated. But, take note that anything that involved POST method will require csrf(_tokenparameter), unless you are using laravel axios
  2. Using authentication using api also which you can refer this tutorialfor "token" driver and all your secure routes will be using token in its Authenticationheader
  1. 在 web.php 中移动“schedules”的路由。不用担心,如果未通过身份验证,您的 ajax 将会失败。但是,请注意,任何涉及 POST 方法的内容都需要csrf_token参数),除非您使用的是 laravel axios
  2. 也可以使用 api 进行身份验证,您可以参考本教程获取“令牌”驱动程序,并且您的所有安全路由都将在其身份验证标头中使用令牌