php - 如何在 Symfony 4 中使用哈希验证匿名访问者(用户)?
问题描述
我们有一个网站,人们可以使用hash
. 我们没有不同的用户。每个拥有有效哈希的人都可以登录,区分谁登录并不重要。
我已经创建了一个表单来获取控制器中的哈希值。这是简化的代码:
public function index(Request $request) {
if ($request->isMethod('post')) {
$token = $request->request->get('token');
$hash = $request->request->get('hash');
if ($this->isCsrfTokenValid('login', $token) && $this->isHashValid($hash)) {
// redirect
}
// fail
}
return $this->render('login.html.twig', []);
}
现在$this->isHashValid()
我已经可以说哈希是否有效。但我不确定,如何authenticate
手动访问访问者:
isHashValid($hash) {
// pseudo-check for the question
if (in_array($hash, $hashes) {
// How to authenticate the user?
return true;
}
return false;
}
我还更新了security.yaml以将unauthenticated
访问者重定向到已经有效的起始页:
security:
providers:
in_memory: { memory: ~ }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
form_login:
login_path: '/'
access_control:
- { path: ^/secured, allow_if: "is_authenticated()" }
所以我的问题是,我如何在 Symfoy 4 中以编程方式对访问者进行身份验证并随后注销访问者?
User
即使我们没有经典意义上的“真实用户”,我还需要创建一个-class 吗?
解决方案
您将必须创建一个User
实现UserInterface
,但它可以是一个准系统类,不需要您设置任何值。只要确保getRoles()
至少返回,["ROLE_USER"]
其他一切都应该没问题,只返回虚拟数据或空值。
身份验证可以通过多种方式解决。
GuardAuthenticator 似乎是一个很好的解决方案:https ://symfony.com/doc/current/security/guard_authentication.html#step-2-create-the-authenticator-class
FormLoginAuthenticator 非常相似,但有些方法是基于使用登录表单自动处理的,因此实现起来更容易:https ://symfony.com/doc/current/security/form_login_setup.html
在这两种情况下,您基本上都可以这样做:getCredentials
从请求中提取数据,getUser
返回您的虚拟用户对象,然后checkCredentials
调用您的isHashValid
方法,其余部分应该是不言自明的。
推荐阅读
- graphql - 当 GraphiQL 返回数据时,Apollo-react 查询返回 null
- .net-core - Fluent-API 的自定义 DataAnnotations
- c++ - _findnext64 因访问冲突而崩溃
- r - 每次选择后闪亮的 selectizeInput 关闭选择
- excel - 如何在另一个单元格更改时使用 VBA 复制一个单元格并将其粘贴到另一个单元格中作为值
- elasticsearch - 嵌套类型未从父级接收用户输入
- youtube-api - iframe 上 loop=1 的行为不一致
- python - 使用正则表达式匹配指标 (a) (b) 等等
- r - 如何使用 dplyr 对另一个表中的数据进行计算?
- python - Python 旧 Regex.casefold 到 Python3