symfony - Symfony 手动登录用户
问题描述
页面存在于创建用户实体的位置(这在正常注册流程之外)。
创建用户时,他们应该登录,guardHandler 与验证器一起使用,如下所示。
use App\Security\FakeAuthenticator;
use Symfony\Component\Security\Guard\GuardAuthenticatorHandler;
$response = $guardHandler->authenticateUserAndHandleSuccess(
$user, // the User object you just created
$request,
$authenticator, // authenticator whose onAuthenticationSuccess you want to use
'main' // the name of your firewall in security.yaml
);
但是验证器是一团糟,它只是为一种方法创建的onAuthenticationSuccess
。
use Symfony\Component\Security\Guard\AbstractGuardAuthenticator;
class FakeAuthenticator extends AbstractGuardAuthenticator
{
public function supports(Request $request)
{
return false;
}
public function getCredentials(Request $request)
{
throw new \RuntimeException('Unreachable code');
}
public function getUser($credentials, UserProviderInterface $userProvider)
{
throw new \RuntimeException('Unreachable code');
}
public function checkCredentials($credentials, UserInterface $user)
{
throw new \RuntimeException('Unreachable code');
}
public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
{
return null;
}
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
throw new \RuntimeException('Unreachable code');
}
public function start(Request $request, AuthenticationException $authException = null)
{
throw new \RuntimeException('Unreachable code');
}
public function supportsRememberMe()
{
return true;
}
}
必须实现许多方法,因为该方法handleAuthenticationSuccess
需要一个实现AuthenticatorInterface
.
该代码有效并且用户已登录,但感觉不是最干净的解决方案,是否有另一种登录用户的方法?
FosUserBundle 正在项目中使用,以下确实有效,但我不确定是否支持 loginManager 上的调用方法,我在文档中找不到任何内容,我不希望我的代码依赖于可以改变。
\FOS\UserBundle\Security\LoginManagerInterface::logInUser('main', $user, $response);
解决方案
我决定使用loginManager
它的公共方法logInUser
,它是最干净的解决方案,无需为单个方法创建额外的类。
use FOS\UserBundle\Security\LoginManager;
...
public function createUserInControllerAction(LoginManagerInterface $loginManager): Response
{
$user = new User(); // create user however you like
$loginManager->logInUser('main', $user, $response);
return $this->json(['success']);
}
推荐阅读
- javascript - ThreeJS:如何仅向一个方向移动背景?
- dialogflow-es - DialogFlow:训练短语数超过 10
- json - ASP Classic For Each 在普通 JSON 行之后迭代行,它们包含来自 json2 库的代码
- javascript - 我目前正在开发一个显示任何值的机器人,如果没有参数,我如何将值设置为 1
- jenkins-pipeline - 从 Git 存储库中的子文件夹加载共享库
- python - 我如何在同一个 VPS Python 上托管多个应用程序
- sql - 如何使用 SQL 查找 EXASOL 服务器版本
- c++ - 在 printf_s 函数中将整数输出为浮点数
- php - 如何在 MYSQL 中快速更新 100 万行
- java - Android Studio - 如何从 RecyclerView 中的 EditText 获取数据并将它们放入主活动中的 ArrayList 中?