Spring Security JDBC Authentication with Password Encryption
I published a basic level tutorial on how to implement JDBC Authentication and Authorization using Spring Security last week. There a...

https://www.programming-free.com/2015/09/spring-security-password-encryption.html
I published a basic level tutorial on how to implement JDBC Authentication and Authorization using Spring Security last week. There are few best practices to be followed while implementing security. One such important thing to do is Password Encryption and I am going to cover all this in this article.
I updated the project I implemented for the previous tutorial to cover the following best practices,
1. Edited mysql queries to use userid as foreign key instead of username. This will help in case if the username needs to be changed in future.
2. Replaced passwords in database that are stored as plain text with encrypted passwords. This is very very important. If the database ever gets hacked, all the plain text passwords will be exposed and that would be a great disaster. So, passwords must be encrypted with a good hashing algorithm which will be very hard for any hacker to crack. Spring Security supports one of the best password hashing algorithm which is bcrypt. I found an interesting article about using bcrypt here, you can read it if you want to have a quick look at what this is.
3. Used Spring Security's default BCryptPassword Encoder to handle bcrypt encoded passwords.
4. Separated database, authentication and authorization related configuration from mvc configuration.
Let me now go step by step and explain the changes to be made.
1. First download the existing project from here.
2. Execute below mysql queries,
DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS user_roles; CREATE TABLE users ( userid VARCHAR(5) NOT NULL, username VARCHAR(45) NOT NULL , password VARCHAR(60) NOT NULL , enabled TINYINT NOT NULL DEFAULT 1 , PRIMARY KEY (userid)); CREATE TABLE user_roles ( user_role_id int(11) NOT NULL AUTO_INCREMENT, userid varchar(5) NOT NULL, role varchar(45) NOT NULL, PRIMARY KEY (user_role_id), UNIQUE KEY uni_username_role (role,userid), KEY fk_username_idx (userid), CONSTRAINT fk_username FOREIGN KEY (userid) REFERENCES users (userid)); INSERT INTO users(userid,username,password,enabled) VALUES ('001','priya','$2a$04$CO93CT2ObgMiSnMAWwoBkeFObJlMYi/wzzOnPlsTP44r7qVq0Jln2', true); INSERT INTO users(userid,username,password,enabled) VALUES ('002','naveen','$2a$04$j3JpPUp6CTAe.kMWmdRNC.Wie58xDNPfcYz0DBJxWkucJ6ekJuiJm', true); INSERT INTO user_roles (userid, role) VALUES ('002', 'ROLE_USER'); INSERT INTO user_roles (userid, role) VALUES ('001', 'ROLE_ADMIN'); INSERT INTO user_roles (userid, role) VALUES ('001', 'ROLE_USER');
Note that I have converted plain text passwords to encrypted passwords. I used this online bcrypt calculator for converting the passwords to bcrypt encoded hash values. You can do the same or use this small utility method to find out,
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; public class EncryptPassword{ public static void main(String args[]) throws Exception { String cryptedPassword = new BCryptPasswordEncoder().encode("password"); System.out.println(cryptedPassword); } }
3. Add a new class in hello package to have all authentication related configuration to have a better clarity,
AuthenticationProvider.java
package hello; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.jdbc.JdbcDaoImpl; @Configuration public class AuthenticationProviderConfig { @Bean(name = "dataSource") public DriverManagerDataSource dataSource() { DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(); driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver"); driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/userbase"); driverManagerDataSource.setUsername("root"); driverManagerDataSource.setPassword("root"); return driverManagerDataSource; } @Bean(name="userDetailsService") public UserDetailsService userDetailsService(){ JdbcDaoImpl jdbcImpl = new JdbcDaoImpl(); jdbcImpl.setDataSource(dataSource()); jdbcImpl.setUsersByUsernameQuery("select username,password, enabled from users where username=?"); jdbcImpl.setAuthoritiesByUsernameQuery("select b.username, a.role from user_roles a, users b where b.username=? and a.userid=b.userid"); return jdbcImpl; } }
4. Remove datasource configuration from MvcConfig.java. MvcConfig must now look clean with only mvc related configuration like this,
MvcConfig.java
package hello; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.view.InternalResourceViewResolver; @Configuration public class MvcConfig extends WebMvcConfigurerAdapter{ @Override public void addViewControllers(ViewControllerRegistry registry) { registry.addViewController("/home").setViewName("home"); registry.addViewController("/").setViewName("home"); registry.addViewController("/hello").setViewName("hello"); registry.addViewController("/login").setViewName("login"); registry.addViewController("/403").setViewName("403"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver resolver = new InternalResourceViewResolver(); resolver.setPrefix("/WEB-INF/jsp/"); resolver.setSuffix(".jsp"); return resolver; } }
5. Now add password encoder to security configuration class.
WebSecurityConfig.java
package hello; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; @Configuration @EnableWebMvcSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { @Autowired UserDetailsService userDetailsService; @Autowired public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception { auth.userDetailsService(userDetailsService).passwordEncoder(passwordencoder());; } @Override protected void configure(HttpSecurity http) throws Exception { http.authorizeRequests() .antMatchers("/hello").access("hasRole('ROLE_ADMIN')") .anyRequest().permitAll() .and() .formLogin().loginPage("/login") .usernameParameter("username").passwordParameter("password") .and() .logout().logoutSuccessUrl("/login?logout") .and() .exceptionHandling().accessDeniedPage("/403") .and() .csrf(); } @Bean(name="passwordEncoder") public PasswordEncoder passwordencoder(){ return new BCryptPasswordEncoder(); } }
Its very simple. Just create an object of Spring Security's default BCryptPasswordEncoder, set it to the AuthenticationManagerBuilder and we are done!
The user will type plain text for password on the website, spring security validates the bcrypt encoded version of the password entered by the user.
You can download this updated project from the link below.
Good Article
ReplyDeletereally informative content
Deletedo check out List Of Over 60+ Fun Jobs That Pay Well & Tips On How to Get Them
https://www.janbasktraining.com/blog/fun-jobs-that-pay-well/
really informative content
Deletedo check out Top 45 Highest Paying IT Jobs (With Average Salaries)
Visit W3Schools.com!
please post spring mvc with maven and db connectivity program
ReplyDeletereally informative content
Deletedo check out Top 45 Highest Paying IT Jobs (With Average Salaries)
janbasktraining.com!
Hi This is very good example and works well. I am just new and learning this. How can i add a new regisration page after welcome page. I created jsp and made mvc config changes but not sure how to change settings in websecurityconfig.java. can you please help me
ReplyDeletebusiness assignment help
ReplyDeletedo my business assignment
english homework help
ReplyDeleteThis is great. Brother Printer Drivers. Thank you so much.
ReplyDeleteDon’t be a fool to take assistance from any writing services because most writing websites are providing uneducated writers who are unknown with the aspects of writing that’s why the majority of the students are falling in their academic paper. In this scenario, students should contact academic service who are fully aware of the aspects of an academic paper and also resolves the inquiry of the student for years.
ReplyDeleteProgramming assignment help
ReplyDeleteAre you tired after a lot of attempts? Since most of the students are falling down in their papers due to incomplete knowledge that’s why they found helping hands of homework help writers gulf who are professional in the field of academic writing and also known with the aspects of it. Furthermore, they enjoy the best discount offers offered by them and also receive the required paper at the given deadline.
ReplyDeletehappy birthday message for employee
ReplyDeleteI am reading it with keen interest but is not difficult to reset password if you have encrypted it. Assignment writing services
ReplyDeleteGreat post! I am seeing the great contents and step by step read really nice information. I am gathered this concept and more information.
ReplyDeleteData Science Training in Hyderabad
Data Science Course in Hyderabad
I couldn't imagine a better Statistics Homework Help than the one administered to me by this expert. He got me a good grade at a very affordable price despite my short notice. And when I checked the order for plagiarism and noticed that it was 99% unique, I concluded that this is the best Statistics Assignment Help provider for me. He has enough experience and insight necessary to nail down challenging statistics tasks in time. I'll order from him frequently from today.
ReplyDeleteMost of the Java Assignment Help online isn't often up to conventionally excellent standards. But with them in the industry for several years, there's no doubt that they offer excellent programming help. To me, they are the best. The group of programmers behind the Programming Assignment Help website is more than amazing. I trust all of them because each time I always get my assignment done by a different expert without failing. Please continue in the same spirit.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis is a very useful and important information, it was so useful to me and other readers, thank you for always feeding the readers with interesting and useful information, your blog is indeed doing very well, kudos, meanwhile you can checkout this cut off mark for marine engineering in fupre
ReplyDeleteThis blog has enlightened me on what I suppose to know about. As a matter of fact, it has shown me the necessary steps I should take. You can still click here to see noun cut off mark for jamb
ReplyDeleteThanks for this amazing article, I believe it will be of great benefit to students also. Small Business Grants 2020
ReplyDeleteThis is a very unique and magnificent post with readable and informative content, I'm absolutely impressed. Thank you for sharing these amazing reads..... coeikwo departmental cut off mark
ReplyDeleteThis is a good time to make long term plans and it's timely.
ReplyDeleteHave fun. I have read this post, and if you will excuse me, I would like to advise you on interesting topics or tips.
You can write the following articles on this topic.
I want to read more topics on this topic!
english stories english short stories with moral value What is the factorial of 100
Dissertations are one of the hardest assignments that can be done. Its goal is to text the upper limits of a student's data gathering skills and knowledge. We at Dissertation help London provide the best of the best academic writing help available. With our hard working and experienced team of writers and scholars we can deliver the dissertations on time with high quality guarantee. Through this we have built our reputation of being the best online Dissertation help in London. Moreover, we have also become known for our affordable services that have enabled many students to be able to come to us for help.
ReplyDeleteI often hear about different document translation agencies. It's great and makes people's lives easier. But recently I discovered a video translation and dubbing service - Service vidby. This is important to me because I'm one of those people who doesn't like subtitles because they distract from the plot of the video. Taking into account the fact that the time of machine voice acting is much less than for human voice acting, this saves time and money.
ReplyDeleteExcellent for this specific beneficial blog post. I am surprisingly happy to seek out this form of relevant information. lautech past questions and answers
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteGreat Blogs,Every thing needs security,Thats whyLifeLong Wealth Managemet provide securing advising for your future
ReplyDeleteThis blog describe all major security points, Gladwell Care Canada is also secure patient with adult diapers
ReplyDeleteEVERYONE Get ready for #MISS SUPERMODEL GLOBE, INDIA 2022, SEASON 3
ReplyDeleteMISS #SUPERMODEL #GLOBAL, INDIA 2022, SEASON 3 is the ideal opportunity for you to boost your self-esteem and accomplish your objectives. Join us in promoting cancer awareness among women in India and changing lives.
SEMI FINALE is scheduled on 12th MARCH 2023 in DELHI
However slots are filling up quickly, so don't wait to register.
https://www.supermodelglobe.com/register.html
SUPERMODEL GLOBE wishes #Heartiest Congratulation to the GUWAHATI State finalist Miss Neha Mili. You have the chance of a lifetime to take advantage of it with her
There is not much time left!
Don't wait until it's too late to take advantage of this opportunity.
ReplyDeleteGreat Dubai is a First Global Platform where you can rent a Car on Cheap Rates. Get the Best Offers and Discounts on Rent a Car Dubai for all kinds of automobiles like Top 4 Best Nissan Maxima Cars for Rent in Downtown Dubai and other Economy, Luxury and Sports Cars.
Hi I am really impressed by the effort that you had put in. Keep going!
ReplyDeleteconcisemedico.co.uk
To activate your BBC visit bbc.com/account/tv and follow the activation process.
ReplyDeletebbc.com/account/tv
bbc.com/account/tv
To activate your BBC visit bbc. com/account/tv enter code and follow the activation process.
bbc. com/account/tv enter code
bbc. com/account/tv enter code
To activate your BBC visit bbc. com/account/tv/ and follow the activation process.
ReplyDeletebbc. com/account/tv/
bbc. com/account/tv/
To activate your american express/confirm card visit americanexpress.com/confirmcard and follow the activation process.
ReplyDeleteamericanexpress.com/confirmcard
americanexpress.com/confirmcard
To activate your american express/confirm card visit americanexpress.com/confirmcard and follow the activation process.
americanexpress.com/confirmcard
americanexpress.com/confirmcard
To activate your vudu tv visit vudu.com/start and follow the activation process.
ReplyDeletevudu.com/start
vudu.com/start
To activate your vudu tv visit vudu.com/start and follow the activation process.
vudu.com/start
vudu.com/start
To activate your vudu tv visit vudu.com/start and follow the activation process.
ReplyDeletevudu.com/start
vudu.com/start
To activate your TNT drama visit tntdrama.com/activate and follow the activation process.
tntdrama.com/activate
tntdrama.com/activate
Malone Painting Company is equipped and prepared to handle any size job. From small rsidential repaints and re-models, to large commercial projects, we are confident we have the resources and know-how to get the job done. Interior Painting St-Louis
ReplyDeletereally like the content
ReplyDeleteWhat a comprehensive and insightful exploration of twin gear pumps in Qatar's industrial scene! This blog truly highlights how innovation in pumping technology, like twin gear pumps, plays a pivotal role in advancing various sectors.
ReplyDeletedigitalphotolab.
website: https://www.digitalphotolab.in/
"Wow, this article really opened my eyes to a new perspective! I love how you explained such a complex topic in such a simple way. Looking forward to reading more from you. Keep up the great work!"
ReplyDeleteindiantradebird.
website: https://www.indiantradebird.com/product/magnetic-drum-separator
ReplyDelete"Wow, this article really opened my eyes to a new perspective! I love how you explained such a complex topic in such a simple way. Looking forward to reading more from you. Keep up the great work!"
amordesigninstitute.
website: https://www.amordesigninstitute.com/
we
ReplyDeleteWow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also My Name Alex I Work We Make Custom Burger Boxes For More Info Visit My Site...https://acustomboxes.com/custom-burger-boxes/
ReplyDelete