我正在使用Passport将用户登录到Laravel API端点,用户使用laravel-socialite包使用他们的社交帐户(google,facebook)进行身份验证。
登录和注销用户的工作流可以完美地工作(生成tokens...Etc)。问题是我有一个控制器,它应该根据是否有用户登录来返回数据。
我确实拦截了HTTP请求中的持有者令牌,但我无法让用户使用该令牌(我会使用DB facade根据令牌选择用户,但实际上我正在查看Passport中是否已经实现了一种更简洁的方法)
我也不想使用auth:api中间件,因为即使没有用户登录,控制器也应该工作并返回数据。
这是api路由:
Route::get("/articles/{tag?}", "ArticleController@get_tagged");这是我希望控制器具有的逻辑
public function get_tagged($tag = "", Request $request)
{
if ($request->header("Authorization"))
// return data related to the user
else
// return general data
}发布于 2019-08-17 02:52:50
假设您将api防护设置为passport,您可以简单地调用if (Auth::guard('api')->check())来检查是否有经过身份验证的用户:
public function get_tagged($tag = "", Request $request)
{
if (Auth::guard('api')->check()) {
// Here you have access to $request->user() method that
// contains the model of the currently authenticated user.
//
// Note that this method should only work if you call it
// after an Auth::check(), because the user is set in the
// request object by the auth component after a successful
// authentication check/retrival
return response()->json($request->user());
}
// alternative method
if (($user = Auth::user()) !== null) {
// Here you have your authenticated user model
return response()->json($user);
}
// return general data
return response('Unauthenticated user');
}这将以与auth:api guard相同的方式触发Laravel身份验证检查,但不会将用户重定向到别处。实际上,重定向是在身份验证检查失败时由Authenticate中间件(存储在vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php中)完成的。
请注意,如果您没有指定要使用的防护,Laravel将使用config/auth.php文件中的默认防护设置(在全新的Laravel安装中通常设置为web )。
如果您更喜欢使用Auth facade/类,那么也可以使用Auth::guard('api')->user()或request对象。
发布于 2020-07-21 16:22:56
感谢@mdexp回答
在我的例子中,我可以使用
if (Auth::guard('api')->check()) {
$user = Auth::guard('api')->user();
}在我的控制器里。
https://stackoverflow.com/questions/57529562
复制相似问题