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...




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.

DOWNLOAD

How it works




Keep yourself subscribed for getting programmingfree articles delivered directly to your inbox once in a month. Thanks for reading!

Subscribe to GET LATEST ARTICLES!


Related

Trending 7496506812751949135

Post a Comment

  1. please post spring mvc with maven and db connectivity program

    ReplyDelete
  2. 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

    ReplyDelete
  3. crazykrush is new dating apps free for dating with other people

    ReplyDelete
  4. Thanks for sharing this, I actually appreciate you taking the time to share with everybody.
    Best Data Science Course In Hyderabad

    ReplyDelete
  5. Use Assignment Helper administrations in the event that you don't discover anything to form your scholarly paper or schoolwork. Now and again, you can't focus on your investigations in view of being occupied with numerous exercises and discover hard to compose your assignment.

    ReplyDelete
  6. We are the best website for providing Programming Assignment Help. Our years of knowledgeable team experts will help and guide students regarding their assignments.

    Programming Assignment Help


    ReplyDelete
  7. NICE BLOG
    That's Great & Giving so much information after reading your blog.For RentaPC : Laptop on Rent | PC | Tablets | Macbooks
    Great thanks to you
    Laptop on Rent
    Latest News

    BT Mail

    ReplyDelete
  8. Don’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.

    ReplyDelete
  9. Are 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.

    ReplyDelete
  10. Prepare to harvest your audience information from user registration to live comments, post comments or questions asked during the session.assignment expert

    ReplyDelete
  11. Kuchi Jewels is a project of Gem & Gems which is a leading exporter since 2005 to onwards in all over the world. Our company has experienced, educated and motivated staff. Our main goal is to meet the international standard B2C and B2B export target with competitive prices and high quality products. pearl necklace canada , pearl necklace australia

    ReplyDelete
  12. Global Translation Help is a USA-based translation company that provides Academic Document Translation Services all over the world. We have a large team of ATA-certified translators who are able to provide international students with a certified letter accompanying each of our translations. Our specialist academic translators have years of experience to translate academic documents, such as assignments, case studies, and many others in more than 200 languages. To get the best academic translation services, don’t think twice and contact us.

    ReplyDelete
  13. I am reading it with keen interest but is not difficult to reset password if you have encrypted it. Assignment writing services

    ReplyDelete
  14. Great post! I am seeing the great contents and step by step read really nice information. I am gathered this concept and more information.
    Data Science Training in Hyderabad
    Data Science Course in Hyderabad

    ReplyDelete
  15. Hi. Do you need A-rated Programming Assignment Help tutors that will only give As to their students? If the answer is yes, I strictly need an A from one of them. It's my last assignment at the university in my pursuit of a Computer Science Degree, and grade A is the only thing that can prevent me from scoring bad end-semester results. If I get a reliable C++ Homework Help tutor and then his/her solutions get me the grade, I'll heavily reward you.

    ReplyDelete
  16. 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.

    ReplyDelete
  17. While others are recounting their fast delivery experiences, I'm here to raise a delay issue that I experienced with the previous order. But,The Matlab Assignment Help expert did want to respond to my questions about the progress of my order. In the end, he delivered the emergency order in twenty minutes. I was Happy to receive my Matlab Homework Help paper. You will try to cushion me with a small refund.

    ReplyDelete
  18. You make remote learning look simple and smooth. I was assigned an experienced Economics Homework Help tutor that was very organized and punctual, leave alone straight to the point and slow enough for me to grasp the concepts. I must commend and recommend his invaluable services to all students looking for the same assistance as myself. I'll keep using your Economics Assignment Help until I get the best out of it. Meanwhile, cheers!

    ReplyDelete
  19. Most 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.

    ReplyDelete
  20. This comment has been removed by the author.

    ReplyDelete
  21. Hello? May I know if you also have Ph.D Programming Homework Help tutors? If yes, I'd love to interact with one of them onlineJava Homework Help. Such an expert cannot fail anyone with his/her solutions. If you need extra pay for allowing me to have access to him/her, I'm ready to pay for it.

    ReplyDelete
  22. I forgot that I had an Statistics assignment that was almost due until a classmate asked me if I'd solved one of the questions that he'd found challenging. I'd also not studied sufficiently for the same assignment. So I asked forStatistics Assignment Help from the experts on statisticshomeworkhelper.com, and my order was awarded to this user. While he wasn't very communicative throughout the two days, he ended up sending me the best solutions that I'm sure will get me a leading grade. I recommend his Statistics Homework Help.

    ReplyDelete
  23. I need a few samples before I can use the Matlab Assignment Help service. I think that can help me evaluate their ability more accurately than just going by the reviews. It's my first time here, and I'm being cautious this way because I got conned on the previous website. If you're able to do so, kindly let me know so that I can place an order for them with Matlab Homework Help services ASAP.

    ReplyDelete
  24. The Answer is Yes. We at Do My Homework Help are looking for opportunities to help you complete your homework on time so that you do not miss any of your assignment submissions. We are here to help you achieve balance in your life and make you enjoy what you like without worrying about completing your assignments. Our team is well educated and expert in writing different types of assignments and doing homework for all the fields, including commerce, Management, Accounting, Business, Science, Computer Science and many more.
    domyhomework

    ReplyDelete

emo-but-icon

SUBSCRIBE


item