我正在尝试使用带有防护功能的自定义身份验证系统为我的API用户设置身份验证。
认证成功后,在onAuthenticationSuccess()中,我尝试使用$ token-> getUser()在响应中发送我的用户对象,但得到的只是一个空对象。
虽然我在调用$ token-> getUserName()时确实得到了预期的结果
以下是我的TokenAuthenticator类的摘录
class TokenAuthenticator extends AbstractGuardAuthenticator
{
private $em;
// [...]
public function getUser($credentials, UserProviderInterface $userProvider)
{
$token = $credentials;
if (null === $token) {
return;
}
$client = new Google_Client(['client_id' => 'my_client_id']);
$payload = $client->verifyIdToken($token);
if ($payload)
{
$userid = $payload['sub'];
$domain = $payload['hd'];
$email = $payload['email'];
if($domain === 'mydomain.com')
{
$userRepo = $this->em->getRepository(User::class);
$user = $userRepo->findOneBy(['googleId' => $userid])?
$userRepo->findOneBy(['googleId' => $userid]):
$userRepo->findOneBy(['email' => $email]);
if(!$user)
{
$user = new User();
$user->setFirstname($payload['given_name']);
$user->setLastname($payload['family_name']);
$user->setEmail($email);
$user->setRoles(['ROLE_TEACHER']);
$user->setCreated(new DateTime('NOW'));
}
if(!$user->getGoogleId())
{
$user->setGoogleId($userid);
$user->setModified(new DateTime('NOW'));
$user = $this->em->persist($user);
$this->em->flush();
}
return $user;
}
else
{
return false;
}
}
else
{
return false;
}
}
public function checkCredentials($credentials, UserInterface $user)
{
// return true to cause authentication success
return true;
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
$user = $token->getUser();
return new JsonResponse($user, Response::HTTP_OK);
}
// [...]
}
还有我的security.yaml文件
security:
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
# used to reload user from session & other features (e.g. switch_user)
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: ~
guard:
authenticators:
- App\Security\TokenAuthenticator