今天是个好日子 .
我需要扩展身份验证机制以满足我的需求 . 要做到这一点,我创建了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));
}
}
当我尝试验证用户 - 我成功登录,但我没有看到除黑色 Headers 和分析器之外的任何东西 . Profiler说我,我已登录为USER_NAME(黄色),未经过身份验证(红色) . 你能给我一个建议 - 如何工作?还有一个问题 - 如何在此验证器类中检索用户的组织?
1 回答
如果您检查UsernamePasswordToken构造函数,您将看到它要求您传递$ roles以使其经过身份验证
parent::setAuthenticated(count($roles) > 0);
并且在setAuthenticated之后无法更改authenticate标志(请参阅代码原因) .
还要检查UserAuthenticationProvider类以了解发生了什么 .
我希望这有帮助 .