Skip to content

Commit cff8505

Browse files
committed
jwt多个看守器认证及获取用户信息
1 parent 4eb8602 commit cff8505

File tree

3 files changed

+47
-24
lines changed

3 files changed

+47
-24
lines changed

src/Auth/LoginActionTrait.php

Lines changed: 15 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
use Illuminate\Support\Facades\Cache;
1515
use Cyd622\LaravelApi\Jobs\SaveUserTokenJob;
1616
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
17+
use Tymon\JWTAuth\Facades\JWTAuth;
1718

1819
trait LoginActionTrait
1920
{
@@ -51,11 +52,14 @@ protected function credentials(Request $request)
5152
/**
5253
* Get user last token
5354
* @param \Illuminate\Database\Eloquent\Model|\Illuminate\Contracts\Auth\Authenticatable $user
54-
* @return mixed
55+
* @param $guard
56+
* @return string|null
5557
*/
56-
protected function getUserLastToken($user)
58+
protected function getUserLastToken($user, $guard)
5759
{
58-
$key = "User.{$user->id}:LastToken";
60+
$uid = $user->getKey();
61+
// User.api.1:LastToken
62+
$key = sprintf("User.%s-%s:LastToken", $guard, $uid);
5963
return Cache::get($key);
6064
}
6165

@@ -75,27 +79,29 @@ public function login(Request $request)
7579
*/
7680
protected function authenticateClient(Request $request)
7781
{
78-
$presentGuard = Auth::getDefaultDriver();
82+
$presentGuard = $request->get('guard', Auth::getDefaultDriver());
7983

8084
$credentials = $this->credentials($request);
8185

8286
// add guard sign to payload.
83-
$token = Auth::claims(['guard' => $presentGuard])->attempt($credentials);
87+
$token = Auth::guard($presentGuard)->claims(['guard' => $presentGuard])->attempt($credentials);
8488

8589
if ($token) {
86-
$user = Auth::user();
87-
$lastToken = $this->getUserLastToken($user);
90+
91+
$user = Auth::guard($presentGuard)->user();
92+
93+
$lastToken = $this->getUserLastToken($user, $presentGuard);
8894

8995
if ($lastToken) {
9096
try {
91-
Auth::setToken($lastToken)->invalidate();
97+
JWTAuth::setToken($lastToken)->invalidate();
9298
} catch (TokenExpiredException $e) {
9399
// Because an exception will be thrown if an expired token is
94100
// invalidated again, we catch the exception without any processing.
95101
}
96102
}
97103

98-
SaveUserTokenJob::dispatch($user, $token);
104+
SaveUserTokenJob::dispatch($user, $token, $presentGuard);
99105
return $this->success($user, ['token_type' => 'Bearer', 'access_token' => $token,]);
100106
}
101107

src/Jobs/SaveUserTokenJob.php

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,26 +11,42 @@
1111

1212
use Illuminate\Bus\Queueable;
1313
use Illuminate\Contracts\Queue\ShouldQueue;
14+
use Illuminate\Database\Eloquent\Model;
1415
use Illuminate\Foundation\Bus\Dispatchable;
1516
use Illuminate\Queue\InteractsWithQueue;
1617
use Illuminate\Support\Facades\Cache;
1718

1819
class SaveUserTokenJob implements ShouldQueue
1920
{
2021
use Dispatchable, InteractsWithQueue, Queueable;
22+
23+
/**
24+
* @var Model
25+
*/
2126
protected $user;
27+
28+
/**
29+
* @var string
30+
*/
2231
protected $token;
2332

33+
/**
34+
* @var string
35+
*/
36+
protected $guard;
37+
2438
/**
2539
* Create a new job instance.
2640
*
2741
* @param $user
2842
* @param $token
43+
* @param $guard
2944
*/
30-
public function __construct($user, $token)
45+
public function __construct($user, $token, $guard)
3146
{
3247
$this->user = $user;
3348
$this->token = $token;
49+
$this->guard = $guard;
3450
}
3551

3652
/**
@@ -40,7 +56,9 @@ public function __construct($user, $token)
4056
*/
4157
public function handle()
4258
{
43-
$key = "User.{$this->user->id}:LastToken";
59+
$uid = $this->user->getKey();
60+
// User.api.1:LastToken
61+
$key = sprintf("User.%s-%s:LastToken", $this->guard, $uid);
4462
Cache::forever($key, $this->token);
4563
}
4664
}

src/Middleware/RefreshTokenMiddleware.php

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,30 +24,29 @@ class RefreshTokenMiddleware extends BaseMiddleware
2424
* Handle an incoming request.
2525
* @param $request
2626
* @param Closure $next
27+
* @param null $guard
2728
* @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response|mixed
28-
* @throws JWTException
29-
* @throws TokenInvalidException
3029
*/
31-
public function handle($request, Closure $next)
30+
public function handle($request, Closure $next, $guard = null)
3231
{
3332
// Check token and throws exception
3433
$this->checkForToken($request);
3534

3635
// Get default guard
37-
$presentGuard = Auth::getDefaultDriver();
36+
$presentGuard = $guard ?? Auth::getDefaultDriver();
3837

39-
$token = Auth::getToken();
38+
$token = $this->auth->getToken()->get();
4039

41-
// Get guard from payload by token
42-
$payload = Auth::manager()->getJWTProvider()->decode($token->get());
40+
$authGuard = $this->auth->getClaim('guard');
4341

44-
if (empty($payload['guard']) || $payload['guard'] != $presentGuard) {
45-
throw new TokenInvalidException();
42+
if (!$authGuard || $authGuard != $presentGuard) {
43+
throw new TokenInvalidException('auth guard invalid');
4644
}
4745

4846
try {
4947

50-
if ($this->auth->parseToken()->authenticate()) {
48+
if ($user = auth($authGuard)->authenticate()) {
49+
$request->guard = $authGuard;
5150
return $next($request);
5251
}
5352

@@ -59,11 +58,11 @@ public function handle($request, Closure $next)
5958

6059
$token = $this->auth->refresh();
6160
// Use once login to ensure the success of this request
62-
Auth::onceUsingId($this->auth->manager()->getPayloadFactory()->buildClaimsCollection()->toPlainArray()['sub']);
61+
Auth::guard($authGuard)->onceUsingId($this->auth->getClaim('sub'));
6362

6463
// Save user token in job
65-
$user = Auth::user();
66-
SaveUserTokenJob::dispatch($user, $token);
64+
$user = Auth::guard($authGuard)->user();
65+
SaveUserTokenJob::dispatch($user, $token, $authGuard);
6766

6867
} catch (JWTException $exception) {
6968
// All token not used. need re-login

0 commit comments

Comments
 (0)