栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何以编程方式登录/认证用户?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何以编程方式登录/认证用户?

是的,您可以通过类似于以下内容的方式执行此操作:

use SymfonyComponentEventDispatcherEventDispatcher,    SymfonyComponentSecurityCoreAuthenticationTokenUsernamePasswordToken,    SymfonyComponentSecurityHttpEventInteractiveLoginEvent;public function registerAction(){    // ...    if ($this->get("request")->getMethod() == "POST")    {        // ... Do any password setting here etc        $em->persist($user);        $em->flush();        // Here, "public" is the name of the firewall in your security.yml        $token = new UsernamePasswordToken($user, $user->getPassword(), "public", $user->getRoles());        // For older versions of Symfony, use security.context here        $this->get("security.token_storage")->setToken($token);        // Fire the login event        // Logging the user in above the way we do it doesn't do this automatically        $event = new InteractiveLoginEvent($request, $token);        $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);        // maybe redirect out here    }}

当您在上下文中设置令牌时,最后不会自动触发事件,而通常在使用登录表单或类似方法时触发。因此,将其包含在此处的原因。您可能需要根据使用情况调整使用的令牌的类型-

UsernamePasswordToken
上面显示的是核心令牌,但是如果需要,您可以使用其他令牌。

编辑 :调整了上面的代码以解释’public’参数,并根据下面的Franco的评论将用户的角色添加到令牌创建中。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/430480.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号