Try to create reset password but i’ve the same message error”: “Invalid or expired reset token.”

I have a project with a front-end in React.js and a back-end in Symfony 6.4 with the API Platform 3. I’m using a reset-password bundle. I’ve tested it with Insomnia, and I’m able to send an email with a link inside that contains a token. However, when I click on the link, I get the error “Invalid or expired reset token.”
I think I have a problem, but I don’t know why. In my database, the token is not complete. For example, the link in the email looks like this:
http://127.0.0.1:8000/reset-password/4ojbHunuRIBs81kHJRyTaR71NgWKgyayceG6ISPg
But in my database, I have a column selector with the beginning of the token: 4ojbHunuRIBs81kHJRyT, and a column with the hashed token.
Maybe it’s not that the problem. I see a other think when i watch the time in my dev.log or in phpmyadmin, i’ve 2 hour différence with the time of my computer but when i watch tape date on the terminal in vs code in my project i’ve the good date and time.
Can you help me fix this?
My entity:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
namespace AppEntity;
use ApiPlatformMetadataGet;
use ApiPlatformMetadataPost;
use DoctrineORMMapping as ORM;
use ApiPlatformMetadataApiResource;
use AppRepositoryResetPasswordRequestRepository;
use SymfonyCastsBundleResetPasswordModelResetPasswordRequestTrait;
use SymfonyCastsBundleResetPasswordModelResetPasswordRequestInterface;
/**
* @IgnoreAnnotation("ORMColumn")
*/
#[ORMEntity(repositoryClass: ResetPasswordRequestRepository::class)]
#[ApiResource(
operations: [
new Post(
uriTemplate: '/reset_password/request',
status: 202,
),
new Get(
uriTemplate: '/reset_password/{token}',
status: 202,
),
],
output: false,
)]
class ResetPasswordRequest implements ResetPasswordRequestInterface
{
use ResetPasswordRequestTrait;
#[ORMId]
#[ORMGeneratedValue]
#[ORMColumn]
private ?int $id = null;
#[ORMManyToOne]
#[ORMJoinColumn(nullable: false)]
private ?User $user = null;
public function __construct(object $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken)
{
$this->user = $user;
$this->initialize($expiresAt, $selector, $hashedToken);
}
public function getId(): ?int
{
return $this->id;
}
public function getUser(): object
{
return $this->user;
}
}
</code>
<code><?php namespace AppEntity; use ApiPlatformMetadataGet; use ApiPlatformMetadataPost; use DoctrineORMMapping as ORM; use ApiPlatformMetadataApiResource; use AppRepositoryResetPasswordRequestRepository; use SymfonyCastsBundleResetPasswordModelResetPasswordRequestTrait; use SymfonyCastsBundleResetPasswordModelResetPasswordRequestInterface; /** * @IgnoreAnnotation("ORMColumn") */ #[ORMEntity(repositoryClass: ResetPasswordRequestRepository::class)] #[ApiResource( operations: [ new Post( uriTemplate: '/reset_password/request', status: 202, ), new Get( uriTemplate: '/reset_password/{token}', status: 202, ), ], output: false, )] class ResetPasswordRequest implements ResetPasswordRequestInterface { use ResetPasswordRequestTrait; #[ORMId] #[ORMGeneratedValue] #[ORMColumn] private ?int $id = null; #[ORMManyToOne] #[ORMJoinColumn(nullable: false)] private ?User $user = null; public function __construct(object $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken) { $this->user = $user; $this->initialize($expiresAt, $selector, $hashedToken); } public function getId(): ?int { return $this->id; } public function getUser(): object { return $this->user; } } </code>
<?php

namespace AppEntity;

use ApiPlatformMetadataGet;
use ApiPlatformMetadataPost;
use DoctrineORMMapping as ORM;
use ApiPlatformMetadataApiResource;
use AppRepositoryResetPasswordRequestRepository;
use SymfonyCastsBundleResetPasswordModelResetPasswordRequestTrait;
use SymfonyCastsBundleResetPasswordModelResetPasswordRequestInterface;

/**
 * @IgnoreAnnotation("ORMColumn")
 */
#[ORMEntity(repositoryClass: ResetPasswordRequestRepository::class)]
#[ApiResource(
    operations: [
        new Post(
            uriTemplate: '/reset_password/request',
            status: 202,
        ),
        new Get(
            uriTemplate: '/reset_password/{token}',
            status: 202,
        ),
    ],
    output: false,
)]
class ResetPasswordRequest implements ResetPasswordRequestInterface
{
    use ResetPasswordRequestTrait;

    #[ORMId]
    #[ORMGeneratedValue]
    #[ORMColumn]
    private ?int $id = null;

    #[ORMManyToOne]
    #[ORMJoinColumn(nullable: false)]
    private ?User $user = null;

    public function __construct(object $user, DateTimeInterface $expiresAt, string $selector, string $hashedToken)
    {
        $this->user = $user;
        $this->initialize($expiresAt, $selector, $hashedToken);
    }

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getUser(): object
    {
        return $this->user;
    }
}

My controller for create token and send a mail:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><?php
namespace AppController;
use AppEntityUser;
use PsrLogLoggerInterface;
use SymfonyComponentMimeEmail;
use SymfonyComponentMimeAddress;
use AppEntityResetPasswordRequest;
use DoctrineORMEntityManagerInterface;
use SymfonyBridgeTwigMimeTemplatedEmail;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentMailerMailerInterface;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentRoutingGeneratorUrlGeneratorInterface;
use SymfonyCastsBundleResetPasswordModelResetPasswordToken;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyCastsBundleResetPasswordResetPasswordHelperInterface;
use SymfonyCastsBundleResetPasswordExceptionResetPasswordExceptionInterface;
class ForgotPasswordController extends AbstractController
{
public function __construct(
private ResetPasswordHelperInterface $resetPasswordHelper,
private EntityManagerInterface $entityManager,
private MailerInterface $mailer,
private LoggerInterface $logger
) {
}
#[Route('/reset-password', name: 'app_forgot_password_request', methods: ['POST'])]
public function request(Request $request): Response
{
$requestParams = $request->toArray();
$email = $requestParams['email'] ?? null;
$this->logger->info('Forgot password request email:', ['email' => $email]);
if (!$email) {
return new JsonResponse('No email provided.', Response::HTTP_BAD_REQUEST);
}
// Vérifier que l'email correspond à un utilisateur existant
$user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
$this->logger->info('Found user:', [
'email' => $user?->getEmail(),
'id' => $user?->getId(),
]);
if (!$user) {
return new JsonResponse('No user found for this email address.', Response::HTTP_BAD_REQUEST);
}
try {
$resetToken = $this->resetPasswordHelper->generateResetToken($user);
} catch (ResetPasswordExceptionInterface $e) {
$this->logger->error('Error generating reset token:', ['exception' => $e]);
return new JsonResponse(sprintf(
'%s - %s',
ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
$e->getReason()
), Response::HTTP_BAD_REQUEST);
}
try {
$emailMessage = $this->sendPasswordResetEmail($email, $this->mailer, $resetToken);
$this->logger->info('Password reset email:', [
'email' => $email,
'message' => $emailMessage ? 'Email sent' : 'Email not sent',
]);
} catch (Exception $e) {
$this->logger->error('Error sending password reset email:', ['exception' => $e]);
return new JsonResponse('An error occurred while processing your request.', Response::HTTP_INTERNAL_SERVER_ERROR);
}
return new JsonResponse(['message' => 'Password reset email sent'], Response::HTTP_OK);
}
private function sendPasswordResetEmail(string $email, MailerInterface $mailer, ResetPasswordToken $resetToken)
{
$emailMessage = (new Email())
->from(new Address('[email protected]', 'admin bot'))
->to($email)
->subject('Your password reset request')
->text(sprintf(
'To reset your password, please visit the following link: %s. This link will expire in %s.',
$this->generateUrl('reset_password', ['token' => $resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL),
$resetToken->getExpirationMessageKey()
));
try {
$mailer->send($emailMessage);
} catch (Exception $e) {
$this->logger->error('Error sending password reset email:', ['exception' => $e]);
return null;
}
return $emailMessage;
}
}
</code>
<code><?php namespace AppController; use AppEntityUser; use PsrLogLoggerInterface; use SymfonyComponentMimeEmail; use SymfonyComponentMimeAddress; use AppEntityResetPasswordRequest; use DoctrineORMEntityManagerInterface; use SymfonyBridgeTwigMimeTemplatedEmail; use SymfonyComponentHttpFoundationRequest; use SymfonyComponentMailerMailerInterface; use SymfonyComponentHttpFoundationResponse; use SymfonyComponentRoutingAnnotationRoute; use SymfonyComponentHttpFoundationJsonResponse; use SymfonyComponentRoutingGeneratorUrlGeneratorInterface; use SymfonyCastsBundleResetPasswordModelResetPasswordToken; use SymfonyBundleFrameworkBundleControllerAbstractController; use SymfonyCastsBundleResetPasswordResetPasswordHelperInterface; use SymfonyCastsBundleResetPasswordExceptionResetPasswordExceptionInterface; class ForgotPasswordController extends AbstractController { public function __construct( private ResetPasswordHelperInterface $resetPasswordHelper, private EntityManagerInterface $entityManager, private MailerInterface $mailer, private LoggerInterface $logger ) { } #[Route('/reset-password', name: 'app_forgot_password_request', methods: ['POST'])] public function request(Request $request): Response { $requestParams = $request->toArray(); $email = $requestParams['email'] ?? null; $this->logger->info('Forgot password request email:', ['email' => $email]); if (!$email) { return new JsonResponse('No email provided.', Response::HTTP_BAD_REQUEST); } // Vérifier que l'email correspond à un utilisateur existant $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]); $this->logger->info('Found user:', [ 'email' => $user?->getEmail(), 'id' => $user?->getId(), ]); if (!$user) { return new JsonResponse('No user found for this email address.', Response::HTTP_BAD_REQUEST); } try { $resetToken = $this->resetPasswordHelper->generateResetToken($user); } catch (ResetPasswordExceptionInterface $e) { $this->logger->error('Error generating reset token:', ['exception' => $e]); return new JsonResponse(sprintf( '%s - %s', ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE, $e->getReason() ), Response::HTTP_BAD_REQUEST); } try { $emailMessage = $this->sendPasswordResetEmail($email, $this->mailer, $resetToken); $this->logger->info('Password reset email:', [ 'email' => $email, 'message' => $emailMessage ? 'Email sent' : 'Email not sent', ]); } catch (Exception $e) { $this->logger->error('Error sending password reset email:', ['exception' => $e]); return new JsonResponse('An error occurred while processing your request.', Response::HTTP_INTERNAL_SERVER_ERROR); } return new JsonResponse(['message' => 'Password reset email sent'], Response::HTTP_OK); } private function sendPasswordResetEmail(string $email, MailerInterface $mailer, ResetPasswordToken $resetToken) { $emailMessage = (new Email()) ->from(new Address('[email protected]', 'admin bot')) ->to($email) ->subject('Your password reset request') ->text(sprintf( 'To reset your password, please visit the following link: %s. This link will expire in %s.', $this->generateUrl('reset_password', ['token' => $resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL), $resetToken->getExpirationMessageKey() )); try { $mailer->send($emailMessage); } catch (Exception $e) { $this->logger->error('Error sending password reset email:', ['exception' => $e]); return null; } return $emailMessage; } } </code>
<?php

namespace AppController;

use AppEntityUser;
use PsrLogLoggerInterface;
use SymfonyComponentMimeEmail;
use SymfonyComponentMimeAddress;
use AppEntityResetPasswordRequest;
use DoctrineORMEntityManagerInterface;
use SymfonyBridgeTwigMimeTemplatedEmail;
use SymfonyComponentHttpFoundationRequest;
use SymfonyComponentMailerMailerInterface;
use SymfonyComponentHttpFoundationResponse;
use SymfonyComponentRoutingAnnotationRoute;
use SymfonyComponentHttpFoundationJsonResponse;
use SymfonyComponentRoutingGeneratorUrlGeneratorInterface;
use SymfonyCastsBundleResetPasswordModelResetPasswordToken;
use SymfonyBundleFrameworkBundleControllerAbstractController;
use SymfonyCastsBundleResetPasswordResetPasswordHelperInterface;
use SymfonyCastsBundleResetPasswordExceptionResetPasswordExceptionInterface;

class ForgotPasswordController extends AbstractController
{
    public function __construct(
        private ResetPasswordHelperInterface $resetPasswordHelper,
        private EntityManagerInterface $entityManager,
        private MailerInterface $mailer,
        private LoggerInterface $logger
    ) {
    }

    #[Route('/reset-password', name: 'app_forgot_password_request', methods: ['POST'])]
    public function request(Request $request): Response
    {
        $requestParams = $request->toArray();
        $email = $requestParams['email'] ?? null;
        $this->logger->info('Forgot password request email:', ['email' => $email]);

        if (!$email) {
            return new JsonResponse('No email provided.', Response::HTTP_BAD_REQUEST);
        }

        // Vérifier que l'email correspond à un utilisateur existant
        $user = $this->entityManager->getRepository(User::class)->findOneBy(['email' => $email]);
        $this->logger->info('Found user:', [
            'email' => $user?->getEmail(),
            'id' => $user?->getId(),
        ]);

        if (!$user) {
            return new JsonResponse('No user found for this email address.', Response::HTTP_BAD_REQUEST);
        }

        try {
            $resetToken = $this->resetPasswordHelper->generateResetToken($user);
        } catch (ResetPasswordExceptionInterface $e) {
            $this->logger->error('Error generating reset token:', ['exception' => $e]);
            return new JsonResponse(sprintf(
                '%s - %s',
                ResetPasswordExceptionInterface::MESSAGE_PROBLEM_HANDLE,
                $e->getReason()
            ), Response::HTTP_BAD_REQUEST);
        }

        try {
            $emailMessage = $this->sendPasswordResetEmail($email, $this->mailer, $resetToken);
            $this->logger->info('Password reset email:', [
                'email' => $email,
                'message' => $emailMessage ? 'Email sent' : 'Email not sent',
            ]);
        } catch (Exception $e) {
            $this->logger->error('Error sending password reset email:', ['exception' => $e]);
            return new JsonResponse('An error occurred while processing your request.', Response::HTTP_INTERNAL_SERVER_ERROR);
        }

        return new JsonResponse(['message' => 'Password reset email sent'], Response::HTTP_OK);
    }

    private function sendPasswordResetEmail(string $email, MailerInterface $mailer, ResetPasswordToken $resetToken)
    {
        $emailMessage = (new Email())
            ->from(new Address('[email protected]', 'admin bot'))
            ->to($email)
            ->subject('Your password reset request')
            ->text(sprintf(
                'To reset your password, please visit the following link: %s. This link will expire in %s.',
                $this->generateUrl('reset_password', ['token' => $resetToken->getToken()], UrlGeneratorInterface::ABSOLUTE_URL),
                $resetToken->getExpirationMessageKey()
            ));

        try {
            $mailer->send($emailMessage);
        } catch (Exception $e) {
            $this->logger->error('Error sending password reset email:', ['exception' => $e]);
            return null;
        }

        return $emailMessage;
    }
}

And my controller for go to the page to update password and update the password

I’ve tried to modify the lifetime of the token, but nothing has changed. I’ve also tried to store the entire token in a single column in the database, but that didn’t work either.
I’ve tried to modify the timezone, which seemed to work fine since I found the same time, but it still didn’t solve the issue. And since this project is intended to be international, I can’t stay in the French time zone.
I would like the token link to work properly. After that, I need to implement the update functionality.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật