if (! $token = auth()->attempt($credentials)) {
return response()->json([‘error’ => ‘账号或密码错误’], 401);
}
这部分是 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
来源:https://learnku.com/laravel/t/10822/auth-guard-api-attempt-credentials-what-exactly-is-it