doufu6196 2012-04-11 14:40
浏览 43
已采纳

使用会话变量进行编程验证

I'm trying to get authentication working in Symfony2.

My users use a login form somewhere else on the site that is not controlled by symfony2.

what I would like is Symfony to detect the users are already logged in and authenticated by reading a session variable and comparing against the DB.

I don't want to reimplement a login form on the symfony part of the website.

In symfony 1.x, for example, I would simply overload the BasicSecurityUser class and use the setAuthenticated method, but it seems this is not possible in Symfony2.

Is there any simple way of achieving the same result?

Thank you!

  • 写回答

1条回答 默认 最新

  • douqian2334 2012-04-11 16:06
    关注

    Once you know the user name of the authenticated user, you can log them in with:

    use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
    
    class MyController {
    
    // Takes either userName or an actual user object
    protected function setUser($userName)
    {
        if (is_object($userName)) $user = $userName;
        else
        {
            $userProvider = $this->get('zayso_core.user.provider');
            // Need try/catch here
            $user = $userProvider->loadUserByUsername($userName);
        }
        $providerKey = 'secured_area';
        $providerKey = $this->container->getParameter('zayso_area.provider.key'); // secured_area
    
        $token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
        $this->get('security.context')->setToken($token);
        return $user;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥30 基于信创PC发布的QT应用如何跨用户启动后输入中文
  • ¥20 非root手机,如何精准控制手机流量消耗的大小,如20M
  • ¥15 远程安装一下vasp
  • ¥15 自己做的代码上传图片时,报错
  • ¥15 Lingo线性规划模型怎么搭建
  • ¥15 关于#python#的问题,请各位专家解答!区间型正向化
  • ¥15 unity从3D升级到urp管线,打包ab包后,材质全部变紫色
  • ¥50 comsol温度场仿真无法模拟微米级激光光斑
  • ¥15 上传图片时提交的存储类型
  • ¥15 VB.NET如何绘制倾斜的椭圆