简体   繁体   English

Laravel sanctum 检查用户是否通过身份验证

[英]Laravel sanctum check if user is authenticated

How to check if the user is authenticated when using Laravel sanctum?使用 Laravel 密室时如何检查用户是否通过身份验证?

Example:例子:

Controller: Controller:

public function testAuth(Request $request)
{ 
     if ($request->user()) {
            return "auth";
      } else {
            return "guest";
      }
}

api.php api.php

Route::get('testauth', [MyTestController::class, 'testAuth']);

this route always returns guest even if I pass token in headers.即使我在标头中传递令牌,这条路线也总是返回客人

when I add sanctum middleware, route return auth当我添加 sanctum 中间件时,路由返回auth

api.php api.php

Route::get('testauth', [MyTestController::class, 'testAuth'])->middleware('auth:sanctum');

but I don't want that, I want to check if the user is authenticated in the controller without using middleware但我不想那样,我想在不使用中间件的情况下检查用户是否在 controller 中经过身份验证

Try this following code will help you.....You can use user('sanctum') instead of user()试试下面的代码会帮助你.....你可以使用 user('sanctum') 而不是 user()

public function testAuth(Request $request)
{ 
     if ($request->user('sanctum')) {
            return "auth";
      } else {
            return "guest";
      }
}

first attach auth middleware with sanctum guard like this to route首先像这样将auth中间件与sanctum guard 连接到路由

Route::get('/somepage', 'SomeController@MyMethod')->middleware('auth:sanctum');

Then inside route closure/controller action access it with然后在路由闭包/控制器操作中访问它

auth()->user()

as usual照常

authorization http header must hold your bearer token授权 http header 必须持有您的不记名令牌

return auth('sanctum')->check() ? "Auth" : "Guest";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM