如何解决Symfony 5 - 使用 json_login 登录;登录过程不起作用;
首先我想让你知道,我是 Symfony 的新手。 我正在将我的 PHP 项目从我自己的“基本”MVC 转移到 Symfony。该项目已经运行并运行良好,但我在适应 Symfony 时遇到了一些问题。
我从基本框架开始,make:user 和 make:auth。该模板运行良好。 但我未能将登录过程转换为 AJAX 和 JSON。
我遵循了这个官方教程:https://symfonycasts.com/screencast/api-platform-security/json-login 以及 https://symfony.com/doc/current/security/json_login_setup.html
这是我的 security.yaml
security:
encoders:
App\Entity\User:
algorithm: auto
# https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
providers:
# used to reload user from session & other features (e.g. switch_user)
app_user_provider:
entity:
class: App\Entity\User
property: email
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
lazy: true
provider: app_user_provider
json_login:
check_path: app_login
username_path: email
password_path: password
guard:
authenticators:
- App\Security\UserAuthenticator
logout:
path: app_logout
# where to redirect after logout
target: home
这是我的控制器:
class SecurityController extends AbstractController
{
// methods={"POST"}
/**
* @Route("/api/login",name="app_login")
*/
public function login(Request $request): Response
{
return $this->json([
'user' => $this->getUser() ? $this->getUser()->getId(): null,'error' => 1,'content' => $request->getmethod()
]);
}
由于请求方法的问题,我删除了“methods={"POST"}”。
第一个问题
curl -X POST -H "Content-Type: application/json" https://127.0.0.1:8000/api/login -d '{"email": "test@test.de","password": "1234"}
返回
<!DOCTYPE html>
<html>
<head>
<Meta charset="UTF-8" />
<Meta http-equiv="refresh" content="0;url='/api/login'" />
<title>Redirecting to /api/login</title>
</head>
<body>
Redirecting to <a href="/api/login">/api/login</a>.
</body>
</html>
内容总是返回“GET”
'content' => $request->getmethod()
用户总是返回NULL '用户' => $this->getUser() ? $this->getUser()->getId(): null,
服务器终端输出:
[PHP ] [Thu Mar 25 16:05:13 2021] 127.0.0.1:60846 [302]: POST /api/login
[PHP ] [Thu Mar 25 16:05:13 2021] 127.0.0.1:60846 Closing
[PHP ] [Thu Mar 25 16:05:13 2021] 127.0.0.1:60848 Accepted
[PHP ] [Thu Mar 25 16:05:13 2021] [info] Matched route "app_login".
[PHP ]
[PHP ] [Thu Mar 25 16:05:13 2021] [debug] Checking for guard authentication credentials.
[PHP ]
[PHP ] [Thu Mar 25 16:05:13 2021] [debug] Checking support on guard authenticator.
[PHP ]
[PHP ] [Thu Mar 25 16:05:13 2021] [debug] Guard authenticator does not support the request.
我的错误在哪里?
<?PHP
namespace App\Security;
use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;
use Symfony\Component\Security\Core\Exception\InvalidCsrftokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Csrf\Csrftoken;
use Symfony\Component\Security\Csrf\CsrftokenManagerInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractformLoginAuthenticator;
use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class UserAuthenticator extends AbstractformLoginAuthenticator implements PasswordAuthenticatedInterface
{
use TargetPathTrait;
public const LOGIN_ROUTE = 'app_login';
private $entityManager;
private $urlGenerator;
private $csrftokenManager;
private $passwordEncoder;
public function __construct(EntityManagerInterface $entityManager,UrlGeneratorInterface $urlGenerator,CsrftokenManagerInterface $csrftokenManager,UserPasswordEncoderInterface $passwordEncoder)
{
$this->entityManager = $entityManager;
$this->urlGenerator = $urlGenerator;
$this->csrftokenManager = $csrftokenManager;
$this->passwordEncoder = $passwordEncoder;
}
public function supports(Request $request)
{
return self::LOGIN_ROUTE === $request->attributes->get('_route')
&& $request->isMethod('POST');
}
public function getCredentials(Request $request)
{
$credentials = [
'email' => $request->request->get('email'),'password' => $request->request->get('password'),'csrf_token' => $request->request->get('_csrf_token'),];
$request->getSession()->set(
Security::LAST_USERNAME,$credentials['email']
);
return $credentials;
}
public function getUser($credentials,UserProviderInterface $userProvider)
{
$token = new Csrftoken('authenticate',$credentials['csrf_token']);
if (!$this->csrftokenManager->isTokenValid($token)) {
throw new InvalidCsrftokenException();
}
$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $credentials['email']]);
if (!$user) {
// fail authentication with a custom error
throw new CustomUserMessageAuthenticationException('Email Could not be found.');
}
return $user;
}
public function checkCredentials($credentials,UserInterface $user)
{
return $this->passwordEncoder->isPasswordValid($user,$credentials['password']);
}
/**
* Used to upgrade (rehash) the user's password automatically over time.
*/
public function getpassword($credentials): ?string
{
return $credentials['password'];
}
public function onAuthenticationSuccess(Request $request,TokenInterface $token,string $providerKey)
{
if ($targetPath = $this->getTargetPath($request->getSession(),$providerKey)) {
return new RedirectResponse($targetPath);
}
return new RedirectResponse($this->urlGenerator->generate('home'));
}
protected function getLoginUrl()
{
return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}
}
解决方法
在 UserAuthenticator.php 中我修改了该行
public const LOGIN_ROUTE = 'app_login';
到
public const LOGIN_ROUTE = '';
它解决了请求方法和登录过程的问题。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。