简体   繁体   中英

JPA Repository & Spring Security - updating object makes password invalid

I'm trying to update a field of my user DTO, but every time I update by doing userService.save(user), my login credentials become invalid in the database, because when I first get the user I get the encrypted password in the password field of my DTO, and when I save the user again I'm re-encrypting the encrypted password making the password different than before.

How can I go about fixing this? Should I decrypt the password when I first query the database in my user service? Is that safe?

Edit: found out you can't decode the password (I'm using BCryptPasswordEncoder) anyways. Is there a way to update all my fields without affecting the password?

Have you tried to update only the column without saving the entire entity? There is an example of how to create such a query in the Spring Data JPA documentation:
https://docs.spring.io/spring-data/jpa/docs/2.1.1.RELEASE/reference/html/#jpa.modifying-queries
Addition:
If there is a way to save only the password without re-encrypting it? If so, you could perhaps try to:
- Obtain the encrypted password.
- Update the user entity (resulting in the encrypted password being encrypted a second time).
- Overwrite only the password in the user with the encrypted password obtained in step 1.

You should use entity listeners.

Look here https://www.concretepage.com/java/jpa/jpa-entitylisteners-example-with-callbacks-prepersist-postpersist-postload-preupdate-postupdate-preremove-postremove

Create entity listener class, implement preUpdate method.

You should inject applicationContext into class. You can find bean "passwordEncoder". Spring use it to encode password.

In pre update method you get your raw password, create encoded version like passwordEncoder.encode(password) and set it back to the entity.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM