实施自定义双因素提供程序
开始使用
一个好的起点是在代码库中可用的 Google Authenticator、TOTP 和电子邮件身份验证实现。请查看以下文件
- src/google-authenticator/Security/TwoFactor/Provider/Google/GoogleAuthenticatorTwoFactorProvider.php
- src/totp/Security/TwoFactor/Provider/Totp/TotpAuthenticatorTwoFactorProvider.php
- src/email/Security/TwoFactor/Provider/Email/EmailTwoFactorProvider.php
您将了解如何实现自定义双因素方法的基本思路。
TwoFactorProviderInterface
您必须创建一个服务,该服务实现 Scheb
接口。它需要以下方法
beginAuthentication
1
public function beginAuthentication(AuthenticationContextInterface $context): bool;
该方法在成功登录后调用。它接收一个 AuthenticationContextInterface
对象作为参数(参见类 Scheb
),其中包含请求对象、身份验证令牌、用户实体和其他信息。
该方法必须决定是否应向用户请求来自该提供程序的双因素身份验证。在这种情况下,返回 true
,否则返回 false
。
1
public function prepareAuthentication(object $user): void;
此方法是您应该为双因素提供程序执行准备工作的地方。例如,email 提供程序正在生成代码并将其发送给用户。
validateAuthenticationCode
1
public function validateAuthenticationCode(object $user, string $authenticationCode): bool;
此方法负责验证用户输入的身份验证代码。如果代码正确,则返回 true
;如果代码错误,则返回 false
。
getFormRenderer
1
public function getFormRenderer(): TwoFactorFormRendererInterface;
此方法必须提供一个服务来呈现身份验证表单。此类服务必须实现 Scheb
接口
1
public function renderForm(Request $request, array $templateVars): Response;
如何呈现表单完全取决于您。唯一重要的是返回一个 Response
,它也可以是一个 RedirectResponse
重定向到外部服务。使用 Twig 呈现表单的默认实现以 Scheb
的形式提供。
注册提供程序
现在,您必须将您的双因素提供程序类注册为服务。
名为 scheb_two_factor.provider
的标签将使您的提供程序可用于该捆绑包。标签属性 alias
必须设置,并且必须是应用程序范围内的身份验证提供程序的唯一标识符。
注意
别名 google
、totp
和 email
由捆绑包中包含的身份验证方法保留。
1 2 3 4 5 6 7
# config/services.yaml
services:
# ...
acme.custom_two_factor_provider:
class: Acme\Demo\MyTwoFactorProvider
tags:
- { name: scheb_two_factor.provider, alias: acme_two_factor_provider }