首页 > 解决方案 > 使用 EquatableUserInterface 的安全缺点

问题描述

为了防止用户的用户角色更改后自动注销,我想使用 EquatableUserInterface 并集成我自己的 isEqualTo() 方法(https://symfony.com/doc/current/security/user_provider.html#comparing -users-manually-with-equatableinterface)。此方法与 Symfony Core 中的方法基本相同,只是我删除了带有角色的部分:

public function isEqualTo(UserInterface $user): bool
{
    if (!$user instanceof self) {
        return false;
    }

    if ($this->getPassword() !== $user->getPassword()) {
        return false;
    }

    if ($this->getSalt() !== $user->getSalt()) {
        return false;
    }

    /* Remove this part
    $currentRoles = array_map('strval', (array) $this->getRoles());
    $newRoles = array_map('strval', (array) $user->getRoles());
    $rolesChanged = \count($currentRoles) !== \count($newRoles) || \count($currentRoles) !== \count(array_intersect($currentRoles, $newRoles));
    if ($rolesChanged) {
        return false;
    }*/

    if ($this->getUsername() !== $user->getUsername()) {
        return false;
    }

    if ($this->isAccountNonExpired() !== $user->isAccountNonExpired()) {
        return false;
    }

    if ($this->isAccountNonLocked() !== $user->isAccountNonLocked()) {
        return false;
    }

    if ($this->isCredentialsNonExpired() !== $user->isCredentialsNonExpired()) {
        return false;
    }

    if ($this->isEnabled() !== $user->isEnabled()) {
        return false;
    }

    return true;
}

出于安全原因有任何顾虑吗?假设我只会相互比较 ID,这会比比较几个属性更不安全吗?或者有没有更好的方法来允许在不注销的情况下更改登录用户的角色?

标签: symfony

解决方案


几分钟前我遇到了这个问题并实现了我的 isEqualTo 方法,例如:

public function isEqualTo(UserInterface $user): bool
{
    return $this->username === $user->getUsername() && $this->password === $user->getPassword();
}

这取决于您使用的属性。就我而言,检查这些属性就足够了。Imo 最安全的方法是您的片段没有角色检查。id 不是UserInterface.


推荐阅读