[英]What is difference between Auth::onceUsingID() and Auth::setUser() in Laravel-8
I want to implement Impersonate functionality into Laravel-8 without using any package.我想在不使用任何 package 的情况下在 Laravel-8 中实现模拟功能。
Here is my middleware:这是我的中间件:
<?php
namespace App\Http\Middleware;
use Closure;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class ImpersonateUser
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$impersonateId = $request->cookie('x-impersonate-id');
if($request->user()->is_admin && $impersonateId) {
$user = User::findOrFail($impersonateId);
if($user->is_admin) {
return response()->json(["message" => trans("You cannot impersonate an admin account.")], 400);
}
Auth::setUser($user);
}
return $next($request);
}
}
My route file:我的路线文件:
// Impersonate routes.
Route::middleware(['auth:sanctum', 'impersonate'])->group(function () {
// checklist routes
Route::get('checklists', [ChecklistController::class, "index"]);
});
Whether use Auth::setUser($user) is safe or I have to use Auth::onceUsingId($userId);使用Auth::setUser($user)是安全的还是我必须使用Auth::onceUsingId($userId); ?
?
Auth::onceUsingId($userId); Auth::onceUsingId($userId); not working with
auth::sanctum
middleware.不使用
auth::sanctum
中间件。 So Auth::setUser($user) is safe or not?那么Auth::setUser($user)是否安全?
I used laravel to develop backend API only.(SPA)我仅使用 laravel 开发后端 API。(SPA)
They should be the same in terms of safety.它们在安全性方面应该相同。
OnceUsingId()
calls setUser()
in the background. OnceUsingId()
setUser()
。
From the Illuminate\Auth\SessionGuard class从Illuminate\Auth\SessionGuard class
/** * Log the given user ID into the application without sessions or cookies. * * @param mixed $id * @return \Illuminate\Contracts\Auth\Authenticatable|false */ public function onceUsingId($id) { if (; is_null($user = $this->provider->retrieveById($id))) { $this->setUser($user); return $user; } return false. } /** * Set the current user; * * @param \Illuminate\Contracts\Auth\Authenticatable $user * @return $this */ public function setUser(AuthenticatableContract $user) { $this->user = $user; $this->loggedOut = false; $this->fireAuthenticatedEvent($user); return $this; }
Both of these methods come from the SessionGuard though.不过,这两种方法都来自 SessionGuard。 I don't know if Sanctum implements its own version.
我不知道 Sanctum 是否实现了自己的版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.