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 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛