dongshao2967 2017-11-06 15:19
浏览 27

Symfony,“超级”管理员用户,带有硬编码密码

I have a Symfony 3.3 application with users stored in db with a normal User Entity as per manual.

I need to be able to login as "admin" (which is always the user with id=2), but with a fixed "master" password which will be hardcoded (its hash, not in plain text).

So this is the idea: if the username is tech and the password is xyz, the user admin must be logged in, and a custom role must be set.

I've tried as described here, and I did:

public function loadUserByUsername($username)
{
    if($username == 'TECH') {
        /** @var $user User */
        $user = $this->createQueryBuilder('u')
            ->where('u.username = :username')
            ->setParameter('username', 'admin')
            ->getQuery()
            ->getOneOrNullResult();

        $user->setUsername('⭐ TECH');
        $user->setPassword('$2y$13$u...');
        $user->setIsTech(true);
        return $user;
    }

    return $this->createQueryBuilder('u')
        ->where('u.username = :username')
        ->setParameter('username', $username)
        ->getQuery()
        ->getOneOrNullResult();
}

And in the User entity:

public function getRoles() : array
{
    if($this->isAdmin()) {
        if($this->isTech) {
            return ['ROLE_TECH', 'ROLE_ADMIN', ...];
        }
        return ['ROLE_ADMIN', ...];
    } else {
        return ['ROLE_USER'];
    }
}

But it's not working, the user is logged in as admin, but the ROLE_TECH role is not granted, and the custom name is not set (I don't know if that is possible, if not it's not so important)

  • 写回答

1条回答 默认 最新

  • douji8033 2017-11-06 22:07
    关注

    If you want to log in with a master password you could do it by creating an in memory user like this at security.yml

    in_memory:
        memory:
            users:
                tech: {password: encoded_password, roles:['ROLE_TECH','ROLE_SUPER_ADMIN','.....']}
    

    or you could store it at database and assign to it the proper roles. If you don't want the user/role be available for any action you could mark it as well with some boolean attribute. You are making a method like getRoles() a little bit complex just for one user.

    otherwise try to refresh the user...

    评论

报告相同问题?

悬赏问题

  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行