Невозможно получить атрибут сеанса «resetToken» в логике смены пароляJAVA

Программисты JAVA общаются здесь
Ответить
Anonymous
 Невозможно получить атрибут сеанса «resetToken» в логике смены пароля

Сообщение Anonymous »


В настоящее время я реализую логику забывания пароля в своем приложении Spring. Этот процесс включает в себя создание токена, отправку его по электронной почте и одновременную установку атрибута сеанса с именем «resetToken» с помощью специального класса UserResetToken. Однако когда я пытаюсь получить этот атрибут сеанса во время процесса смены пароля, он постоянно возвращает ноль. Вот соответствующие фрагменты кода:
Отправка электронной почты и установка атрибута сеанса:

Код: Выделить всё

public void sendMail(String to,HttpServletRequest request) {
HttpSession session = request.getSession(true);
User user = userRepository.findByEmailIgnoreCase(to);
if (user == null) {
throw new NoSuchElementException("User with email " + to + " not found");
}
String token = generateToken(to);
Instant creationTime = Instant.now();
Instant expirationTime = creationTime.plusSeconds(220);
UserResetToken userResetToken = new UserResetToken(to, token, creationTime, expirationTime);
session.setAttribute("resetToken", userResetToken);
String htmlContent;
try {
String templatePath = "Mypath/email.html";
htmlContent = new String(Files.readAllBytes(Paths.get(templatePath)));
} catch (Exception e) {
throw new RuntimeException("Failed to read HTML template", e);
}
String resetLink = "http://localhost:4200/changepassword?token=" + token;
htmlContent = htmlContent.replace("{{resetLink}}", resetLink);
try {
MimeMessage mimeMessage = javaMailSender.createMimeMessage();
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
mimeMessageHelper.setFrom(fromEmail);
mimeMessageHelper.setTo(to);
mimeMessageHelper.setSubject("Password Reset");
mimeMessageHelper.setText(htmlContent, true);
javaMailSender.send(mimeMessage);
} catch (Exception e) {
throw new RuntimeException("Failed to send email", e);
}
}
private String generateToken(String email) {

SecretKey secretKey = SecretKeyGenerator.generateSecretKey();
long expirationMillis = System.currentTimeMillis() + (2  60  60 * 1000);
Date expirationDate = new Date(expirationMillis);

String token = Jwts.builder()
.setSubject(email)
.setExpiration(expirationDate)
.signWith(SignatureAlgorithm.HS256, secretKey)
.compact();

return token;
}
public boolean isTokenExpired(UserResetToken userResetToken) {
Instant now = Instant.now();
Instant expirationTime = userResetToken.getExpirationTime();
return now.isAfter(expirationTime);
}
Метод смены пароля:

Код: Выделить всё

@Override
public void changePassword(UserDto dto, HttpServletRequest request) {
HttpSession session = request.getSession();
UserResetToken userResetToken = (UserResetToken) session.getAttribute("resetToken");
if (userResetToken == null || isTokenExpired(userResetToken)) {
throw new RuntimeException("Password reset link has expired");
}
User user = userRepository.findByUsernameIgnoreCaseOrEmailIgnoreCase(dto.getUsername(),dto.getEmail());
if (user == null) {
throw new NoSuchElementException("User with username " + dto.getUsername() + " not found");
}
if (dto.getPassword() != null && !passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
throw new IllegalArgumentException("Entered password does not match the current password");
}
user.setPassword(passwordEncoder.encode(dto.getNewPassword()));
user.setLastModifiedDatetime(new Date());
user.setLastModifiedBy(user.getUsername());
userRepository.save(user);
}
Класс UserResetToken:

Код: Выделить всё

package com.project.officeadministrationsystem.dto;

import java.io.Serializable;
import java.time.Instant;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

@Data
@NoArgsConstructor
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false, of = { "email"  })

public class UserResetToken implements Serializable {
private static final long serialVersionUID = 1L;
private String email;
private String resetToken;
private Instant creationTime;
private Instant expirationTime;
}
Дополнительная информация:
Сеанс настроен для хранения данных в базе данных JDBC (таблица: Spring_session_attributes) с таймаутом 3600 секунд

Код: Выделить всё

`session:
store-type: jdbc
jdbc:
initialize-schema: always
timeout:
seconds: 3600`
The UserResetToken class implements Serializable and has appropriate getters and setters
No exceptions or errors are thrown during the email sending process.
The application is running on a local server (http://localhost:4200).
Question:
Why am I unable to retrieve the session attribute "resetToken" during the change password process? Is there any mistake in my implementation that could be causing this issue? Any insights or suggestions would be greatly appreciated. Thank you!


Источник: https://stackoverflow.com/questions/781 ... word-logic
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «JAVA»