如何解决如何根据 Symfony 5 中使用的身份验证机制更改用户的访问权限
假设我有两种身份验证机制。我如何允许/拒绝用户访问内容,具体取决于他们使用哪种身份验证机制对自己进行身份验证。
例如,假设我有:
- 两种类型的用户:
admin
和user
使得所有admin
都是user
而user
不是admin
- 两种身份验证机制:
admin_login
和user_login
我想让 admin
必须通过 admin_login
进行身份验证才能获得管理员访问权限。这意味着如果他通过 user
进行身份验证,他将被视为普通 user_login
。
我首先考虑使用防火墙上下文,但很快意识到它行不通,因为我需要一个防火墙来支持多个上下文:
# config/packages/security.yaml
security:
# ...
firewalls:
admin:
# ...
context: // not currently supported
- admin
- user
user:
# ...
context: user
我想到的另一个想法是在 is_allow_admin
类中创建一个名为 User
的属性,并使用它通过在 admin_login
身份验证器中设置它来更改检索角色的方式:
// src/Entity/User.php
// ...
class User implements UserInterface
{
// ...
private $is_allow_admin = false;
// ...
public function setIsAllowAdmin(bool $is_allow_admin)
{
$this->is_allow_admin = $is_allow_admin ;
}
public function getRoles(): array
{
if (!$this->is_allow_admin) {
return ['ROLE_USER'];
}
//...
return $roles;
}
// ...
}
// src/Security/AdminAuthenticator.php
class AdminAuthenticator extends AbstractFormLoginAuthenticator
{
//...
public function getUser($credentials,UserProviderInterface $userProvider): ?UserInterface
{
$user = $userProvider->loadUserByUsername($credentials['username']);
if (!$user) {
throw new CustomUserMessageAuthenticationException('username could not be found.');
}
$user->setIsAllowAdmin(true); // <-
return $user;
}
//...
}
不幸的是,这不起作用。验证器一切顺利,onAuthenticationSuccess
被触发。但不知何故,最终没有用户通过身份验证。
我知道它与 $this->setIsAllowAdmin(true);
有关,因为当我删除该行时它可以正常工作。
还有其他方法可以解决这个问题吗?
提前致谢。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。