实施逻辑以检查旧密码

问题描述 投票:1回答:1
@Autowired
private PasswordEncoder passwordEncoder;

@Autowired
private OldPasswordsService oldPasswordsService;

Optional<OldPasswords> list = oldPasswordsService.findEncryptedPassword(passwordEncoder.encode("new password entered form web reset form"));
            OldPasswords value = list.get();
            boolean matches = passwordEncoder.matches("new password entered form web reset form", value.getEncryptedPassword());

            if (matches)
            {
                return new ResponseEntity<>("PASSWORD_ALREADY_USED", HttpStatus.BAD_REQUEST);
            }
            else
            {
                OldPasswords oldPasswords = new OldPasswords();
                oldPasswords.setEncryptedPassword(passwordEncoder.encode(resetDTO.getPassword()));
                oldPasswordsService.save(oldPasswords);
            }

旧密码表:

@Table(name = "old_passwords")
public class OldPasswords implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id", unique = true, updatable = false, nullable = false)
    private int id;

    @Column(name = "encrypted_password", length = 255)
    private String encryptedPassword;

但是我得到了java.util.NoSuchElementException: No value present。您知道我如何实现比较旧密码和新密码的逻辑吗?

java spring spring-boot spring-security spring-security-oauth2
1个回答
1
投票

您的问题出在该行OldPasswords value = list.get();上,您试图从get取值Optional而不验证其是否存在。

我也建议您看看Spring的DelegatingPasswordEncoder

编辑这是使用您的代码的示例示例(伪代码):

Optional<OldPasswords> list = oldPasswordsService.findEncryptedPassword(passwordEncoder.encode("new password entered form web reset form"));
list.ifPresent(value -> {
    boolean matches = passwordEncoder.matches("new password entered form web reset form", value.getEncryptedPassword());
    if (matches) {
        return new ResponseEntity<>("PASSWORD_ALREADY_USED", HttpStatus.BAD_REQUEST);
    }
}).orElse(() -> {
   OldPasswords oldPasswords = new OldPasswords();
   oldPasswords.setEncryptedPassword(passwordEncoder.encode(resetDTO.getPassword()));
   oldPasswordsService.save(oldPasswords);
});
© www.soinside.com 2019 - 2024. All rights reserved.