By WZH. Aug 2016
We want authenticate user against with a DB rather from a hard code user service with username and password. So system can work like a production system.
Refer to this article and its code:
Here is key points:
"select username,password, enabled from users where username=?"
"select username, role from user_roles where username =? " />
users-by-username-query and users-by-username-query are two queries that to get user + password and user + role from DB. You do not need to use exactly field names for these in DB define , but SQL return data should there 3 items in order for users and 2 items in order for authorities.
After you make this part correct and your DB ok, you should be able to implement authenticate from DB easily. But this password could be clear pass save in DB.
Question – what if your password field is MD5 of real password in DB to ensure security how to do it in Spring security?
Let me show you one example that what you should do, add this line at <authentication-provider> first:
"select loginId, password, true from users where loginId=?"
"select loginId, authority from user_roles where loginId =? " />
<password-encoder hash=”md5″/> will tell spring security that password read from DB is MD5 hash. So spring will compare MD5 of the LoginForm input password with the MD5 read out from DB to do the authentication. But when you create/ register a new user into your DB, you need to calculate the MD5 by your code. You have to ensure your MD5 hash result is same with Spring.
Remember this piece of code:
PasswordEncoder encoder = new Md5PasswordEncoder();
String hashedPass = encoder.encodePassword("origClearPassword", null);
then you can save hashedPass to you DB as the “password” for hashed authentication.