Laravel - 如何根据通过 URL 参数传递的不记名令牌获取用户信息?
Laravel - How can I get user info based on a bearer token passed through a URL parameter?
我正在使用 sanctum
来验证 API 调用。
我正在应用程序中加载图像和视频,并且由于我希望用户登录并且实际上能够识别哪个用户正在请求图像或视频,所以我将不记名令牌添加为video/image URL.
内的参数
即<img src="https://mysite.test/private/video?e=XXXXX&tk=my_bearer_token" />
在后端,我正在做类似的事情:
public function getPrivateVideo (Request $request) {
$validator = Validator::make($request->all(), [
'e' => 'required|exists:employees,id',
't' => 'required|exists:course_lesson_videos,code',
'tk' => 'nullable'
]);
if(auth()->check(){
$user = auth()->user();
}elseif($request->tk){
$user = get user by access token or fail
}else{
return abort('403');
}
Log::info([$user->id,$request->e,$request->t]);
$video_code = $request->t;
if($validator->fails() || $request->user()->client_employee->id !== $request->e || !CourseLessonVideo::join('course_lesson_questions as clq','clq.lesson_id','course_lesson_videos.lesson_id')->join('course_employee_assigned_questions as ceaq','ceaq.question_id','clq.id')->where('employee_id',$request->e)->where('code',$video_code)->first())
return abort('403');
return response()->file(storage_path('app/videos/'.$video_code));
}
我想这一定是可能的吧?
通过代币获取用户
试试这个代码
use Laravel\Sanctum\PersonalAccessToken;
$token = PersonalAccessToken::findToken($request->get('tk'));
$user = $token->tokenable;
或者
$token = PersonalAccessToken::where('token', $token)->first();
$user = $token->tokenable;
我正在使用 sanctum
来验证 API 调用。
我正在应用程序中加载图像和视频,并且由于我希望用户登录并且实际上能够识别哪个用户正在请求图像或视频,所以我将不记名令牌添加为video/image URL.
内的参数即<img src="https://mysite.test/private/video?e=XXXXX&tk=my_bearer_token" />
在后端,我正在做类似的事情:
public function getPrivateVideo (Request $request) {
$validator = Validator::make($request->all(), [
'e' => 'required|exists:employees,id',
't' => 'required|exists:course_lesson_videos,code',
'tk' => 'nullable'
]);
if(auth()->check(){
$user = auth()->user();
}elseif($request->tk){
$user = get user by access token or fail
}else{
return abort('403');
}
Log::info([$user->id,$request->e,$request->t]);
$video_code = $request->t;
if($validator->fails() || $request->user()->client_employee->id !== $request->e || !CourseLessonVideo::join('course_lesson_questions as clq','clq.lesson_id','course_lesson_videos.lesson_id')->join('course_employee_assigned_questions as ceaq','ceaq.question_id','clq.id')->where('employee_id',$request->e)->where('code',$video_code)->first())
return abort('403');
return response()->file(storage_path('app/videos/'.$video_code));
}
我想这一定是可能的吧?
通过代币获取用户
试试这个代码
use Laravel\Sanctum\PersonalAccessToken;
$token = PersonalAccessToken::findToken($request->get('tk'));
$user = $token->tokenable;
或者
$token = PersonalAccessToken::where('token', $token)->first();
$user = $token->tokenable;