I'm building a web app with Spring Framework (-> Java). For testing reasons I've created one user (via SQL statement). Currently I'm working on password encryption, for which I'm using BCyrptPasswordEncoder. I'm wondering, if it's possible, to create this first user with the encoded password.
In other words: can I create a new user via SQL statement using an encrypted password as input? If so, how do I input the encoded password?
I've tried {Bcyrpt}[hash], which I read on some website, but that didn't seem to work...
INSERT INTO USER(USERNAME, PASSWORD) VALUES ('admin', 'passwd')
First a quick clarification on the terminology. The passwords are "hashed" with bcrypt not "encrypted". This means it's a one-way algorithm (you can't un-hash the value).
The value stored in the database is the hashed value (eg. $2a$10$Iewuj5kQFVnUaNbb6M0sAu6a1qbc5bqXAuyc.9fF4cR8xxIOhD0Da
) and not the plain text password.
So all you need to do for your test user is generate a bcrypt hash to put into the INSERT statement. Either run it through BCryptPasswordEncoder
or use an online bcrypt generator.
For example:
INSERT INTO USER(USERNAME, PASSWORD) VALUES ('admin', '$2a$10$Iewuj5kQFVnUaNbb6M0sAu6a1qbc5bqXAuyc.9fF4cR8xxIOhD0Da')
You can use @PostConstruct
annotation to invoke code after spring boots up and add the user with encoded password. But I encourage you to just write a unit test. :)
@Autowired
private PasswordEncoder passwordEncoder;
@Autowired
private UserRepository userRepository;
@PostConstruct
public void addFirstUser(){
User user = new User("[email protected]", passwordEncoder.encode("some-password"));
userRepository.save(user);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With