带有身份验证的 Laravel api 路由 [英] Laravel api routes with auth

查看:33
本文介绍了带有身份验证的 Laravel api 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.php but it returns {"error":"Unauthenticated."}

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

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

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

推荐答案

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

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

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

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.

因此,您几乎没有办法遇到这种情况.

Thus, you have few options to encounter this.

  1. 在 web.php 中移动schedules"的路由.不用担心,如果未通过身份验证,您的 ajax 将会失败.但是,请注意,任何涉及 POST 方法的内容都需要 csrf(_token 参数),除非您使用的是 laravel axios
  2. 使用 api 进行身份验证,您可以参考本教程,了解令牌"驱动程序和所有安全路由将在其 Authentication 标头中使用令牌
  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 (_token parameter), unless you are using laravel axios
  2. Using authentication using api also which you can refer this tutorial for "token" driver and all your secure routes will be using token in its Authentication header

这篇关于带有身份验证的 Laravel api 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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