使用了jwt之后的登陆方法:
public function store(AuthorizationRequest $request)
{
$username = $request->username;
filter_var($username, FILTER_VALIDATE_EMAIL) ?
$credentials['email'] = $username :
$credentials['phone'] = $username;
$credentials['password'] = $request->password;
if (!$token = \Auth::guard('api')->attempt($credentials)) {
throw new AuthenticationException('用户名或密码错误');
}
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
'expires_in' => \Auth::guard('api')->factory()->getTTL() * 60
])->setStatusCode(201);
}
其中有句代码看不懂:
$token = \Auth::guard('api')->attempt($credentials)
后来找了半天资料,看到的解释如下,做个备份:
这部分是 laravel guard 的知识
我们在 config/auth 中设置了不同的 guard
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
'api' => [
'driver' => 'jwt',
'provider' => 'users',
],
],
\Auth::guard (‘api’) 意思是使用 api guard,根据配置使用的 driver 是 jwt,provider 是 users。
driver jwt 在 jwt-auth 这个扩展中定义了
vendor/tymon/jwt-auth/src/Providers/AbstractServiceProvider.php
.
.
.
protected function extendAuthGuard()
{
$this->app['auth']->extend('jwt', function ($app, $name, array $config) {
$guard = new JwtGuard(
$app['tymon.jwt'],
$app['auth']->createUserProvider($config['provider']),
$app['request']
);
$app->refresh('request', $guard, 'setRequest');
return $guard;
});
}
.
.
.
你会看到最终是执行的 vendor/tymon/jwt-auth/src/JwtGuard.php 中的 attempt 方法
public function attempt(array $credentials = [], $login = true)
{
$this->lastAttempted = $user = $this->provider->retrieveByCredentials($credentials);
if ($this->hasValidCredentials($user, $credentials)) {
return $login ? $this->login($user) : true;
}
return false;
}
所以最后返回了 token