美好的一天,每个人。
我需要为我的需求扩展身份验证机制。 为此,我创建了Custom Form Password Authenticator
1)我更改了防火墙设置
main:
...
#organization-form-login:
simple_form:
authenticator: my_authenticator
csrf_provider: form.csrf_provider
check_path: oro_user_security_check
login_path: oro_user_security_login
...
2)我为my_authenticator
创建了服务services:
...
my_authenticator:
class: OQ\SecurityBundle\Security\MyAuthenticator
arguments:
- @oro_organization.organization_manager
...
3)这是MyAuthenticator的代码
namespace OQ\SecurityBundle\Security;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimpleFormAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\UserProviderInterface;
Use Oro\Bundle\SecurityBundle\Authentication\Token\UsernamePasswordOrganizationToken;
use Oro\Bundle\OrganizationBundle\Entity\Manager\OrganizationManager;
class MyAuthenticator implements SimpleFormAuthenticatorInterface
{
/** @var OrganizationManager */
protected $manager;
public function __construct(OrganizationManager $manager)
{
$this->manager = $manager;
}
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey)
{
// Here will be my special checks
//Here i try to get username and force authentication
try {
$user = $userProvider->loadUserByUsername($token->getUsername());
} catch (UsernameNotFoundException $e) {
throw new AuthenticationException('This user not allowed');
}
// If everythin' is ok - create a token
if ($user) {
return new UsernamePasswordOrganizationToken(
$user,
$user->getPassword(),
$providerKey,
$this->manager->getOrganizationById(1)
);
} else {
throw new AuthenticationException('Invalid username or password');
}
}
public function supportsToken(TokenInterface $token, $providerKey)
{
return $token instanceof UsernamePasswordOrganizationToken
&& $token->getProviderKey() === $providerKey;
}
public function createToken(Request $request, $username, $password, $providerKey)
{
//UsernamePasswordOrganizationToken
return new UsernamePasswordOrganizationToken($username, $password, $providerKey, $this->manager->getOrganizationById(1));
}
}
当我尝试验证用户时 - 我成功登录,但除了黑色标题和分析器之外我什么也看不见。 Profiler说我,我记录为USER_NAME(黄色),未经过身份验证(红色)。 你能给我一个建议 - 如何工作? 还有一个问题 - 如何在此验证器类中检索用户的组织?
答案 0 :(得分:3)
如果您检查UsernamePasswordToken构造函数,您将看到它要求您传递$ roles以使其经过身份验证
parent::setAuthenticated(count($roles) > 0);
在setAuthenticated之后无法更改身份验证标志(请参阅代码原因)。
还要检查UserAuthenticationProvider类,以了解发生了什么。
我希望这会有所帮助。