是的,这就是要走的路。如果您的网络服务可以仅通过用户名为您提供用户,那么您只能在 UserProvider 中执行此操作,因为在它的范围内您只有用户名。如果您必须通过 un/pw 进行查询,那么您必须在身份验证器中进行查询,因为在该范围内您有密码。所以,用简单的形式,它看起来像这样
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
try {
$user = $userProvider->loadUserByUsername($token->getUsername());
} catch (UsernameNotFoundException $e) {
throw new AuthenticationException('Invalid username or password');
}
$encoder = $this->encoderFactory->getEncoder($user);
$passwordValid = $encoder->isPasswordValid(
$user->getPassword(),
$token->getCredentials(),
$user->getSalt()
);
if ($passwordValid) {
return new UsernamePasswordToken(
$user,
$user->getPassword(),
$providerKey,
$user->getRoles()
);
}
// remote users fallback
$webUser = $this->externalUserService->getByUsernamePassword(
$token->getUsername(),
$token->getCredentials()
);
if ($webUser) {
return new UsernamePasswordToken(
$webUser,
$token->getCredentials(),
$providerKey,
$webUser->getRoles()
);
}
throw new AuthenticationException('Invalid username or password');
}
Ofc 在这个类中有太多的 if,它负责不止一件事,所以为了整洁,您可以应用复合模式并拥有 3 个身份验证器、一个通用复合材料、第二个本地数据库身份验证器和第三个外部服务身份验证器,以及像这样从服务配置构建它。
# services.yml
my_app.authenticator.main:
class: MyApp/Security/Core/Authentication/CompisiteAuthenticator
calls:
- [ add, [@my_app.authenticator.locale]]
- [ add, [@my_app.authenticator.remote]]
my_app.authenticator.locale:
class: MyApp/Security/Core/Authentication/LocalAuthenticator
arguments: [@security.encoder_factory]
my_app.authenticator.remote:
class: MyApp/Security/Core/Authentication/RemoteAuthenticator
arguments: [@my_app.remote_user_service]
复合
<?php
namespace MyApp/Security/Core/;
class CompositeAuthenticator implements SimpleFormAuthenticatorInterface
{
/** @var SimpleFormAuthenticatorInterface[] */
protected $children = array();
public function add(SimpleFormAuthenticatorInterface $authenticator)
{
$this->children[] = $authenticator;
}
public function createToken(Request $request, $username, $password, $providerKey)
{
return new UsernamePasswordToken($username, $password, $providerKey);
}
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof UsernamePasswordToken
&& $token->getProviderKey() === $providerKey;
}
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
$result = null;
foreach ($this->children as $authenticator)
{
$result = $authenticator->authenticateToken($token, $userProvider, $providerKey);
if ($result) {
return $result;
}
}
throw new AuthenticationException('Invalid username or password');
}
}
我想现在本地和远程身份验证器是微不足道的