在没有数据库的情况下在 Symfony 3 中验证用户
Authenticate User in Symfony 3 without Database
我有一个应用程序,其中登录进程针对外部 API 运行。 API 给了我一个 JSON 返回我存储在我的用户实体中。(称之为成员)
用户 Class 实现了 AdvancedUserInterface。
还有我的登录过程。
$firewall = 'main';
$token = new UsernamePasswordToken($member, null, $firewall, $member->getRoles());
$this->tokenStorage->setToken($token);
$this->session->set('_security_'.$firewall, serialize($token));
$request = new \Symfony\Component\HttpFoundation\Request();
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch("security.interactive_login", $event);
但这行不通。现在我读到 here 这个过程需要数据库中的用户。我的应用程序没有用户数据库。有没有办法在没有它的情况下登录用户。
您可以定义一个自定义保护验证器:How to Create a Custom Authentication System with Guard。我将快速浏览此处的主要步骤,但请查看 link,因为它更深入地解释了这些步骤。
首先您需要创建一个用户class和一个相应的用户提供者。看起来你已经这样做了。如果您以后不在身份验证器 class 中使用它,您也可以跳过用户提供程序 class(或创建一个假的)。
接下来创建您的身份验证器 class(比方说 AppBundle\Security\ExternalApiAuthenticator
)。它只是一个普通的 symfony 服务,扩展 Symfony\Component\Security\Guard\AbstractGuardAuthenticator
。关于 class 的评论很好地解释了如何实现它,因此您应该检查它们,但有一件事可能会有所帮助:您已经可以使用 API 中的 [=] 检查凭据13=] 方法,然后在 checkCredentials
.
中总是 return true
最后给 app/config/security.yml
添加一些配置:
# app/config/security.yml
security:
# ...
firewalls:
# ...
main:
anonymous: ~
logout: ~
guard:
authenticators:
- AppBundle\Security\ExternalApiAuthenticator
我有一个应用程序,其中登录进程针对外部 API 运行。 API 给了我一个 JSON 返回我存储在我的用户实体中。(称之为成员)
用户 Class 实现了 AdvancedUserInterface。
还有我的登录过程。
$firewall = 'main';
$token = new UsernamePasswordToken($member, null, $firewall, $member->getRoles());
$this->tokenStorage->setToken($token);
$this->session->set('_security_'.$firewall, serialize($token));
$request = new \Symfony\Component\HttpFoundation\Request();
$event = new InteractiveLoginEvent($request, $token);
$this->eventDispatcher->dispatch("security.interactive_login", $event);
但这行不通。现在我读到 here 这个过程需要数据库中的用户。我的应用程序没有用户数据库。有没有办法在没有它的情况下登录用户。
您可以定义一个自定义保护验证器:How to Create a Custom Authentication System with Guard。我将快速浏览此处的主要步骤,但请查看 link,因为它更深入地解释了这些步骤。
首先您需要创建一个用户class和一个相应的用户提供者。看起来你已经这样做了。如果您以后不在身份验证器 class 中使用它,您也可以跳过用户提供程序 class(或创建一个假的)。
接下来创建您的身份验证器 class(比方说 AppBundle\Security\ExternalApiAuthenticator
)。它只是一个普通的 symfony 服务,扩展 Symfony\Component\Security\Guard\AbstractGuardAuthenticator
。关于 class 的评论很好地解释了如何实现它,因此您应该检查它们,但有一件事可能会有所帮助:您已经可以使用 API 中的 [=] 检查凭据13=] 方法,然后在 checkCredentials
.
最后给 app/config/security.yml
添加一些配置:
# app/config/security.yml
security:
# ...
firewalls:
# ...
main:
anonymous: ~
logout: ~
guard:
authenticators:
- AppBundle\Security\ExternalApiAuthenticator