Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Wednesday, 4 June 2014

Spring Security - Password Hashing or Password Encoding (Spring MVC + MySql Password Hashing)

In our previous discussions we came across a 'What is spring security' and 'Custom login form with spring security'. In this particular blog we will see how to encode password in java using spring security. We will look into how to insert a hashed or encoded password to database using spring security and how to use that encoded password to authenticate user in a a spring mvn application.

Objective for today's discussion

Saving your password in a simple string form in database is never a good idea, instead one must save his password in some sort of encoded or hashed format. To make password purely protected we mush have some algorithm to identify how to save encoded password in database and how to authenticate user using an encoded password stored in db.
1) How to save hashed or encoded password to database tables using spring security.
2) How to authenticate user with encoded password using spring security.


1) How to save hashed or encoded password to database tables using spring security.


Saving a hashed or encoded password to the database is quit simple, we have to first encode the password using some encryption algorithm and than save it to the database instead of saving simple plain spring. Like old java days we can use 'MD5 password encoder' or 'SHA encryption algorithms', but spring recommend us to use 'BCryptPasswordEncoder' a more stable and strong encryption algorithms. Lets see how to encode a password and save in to database in encoded form.
To encode a password using 'BCryptPasswordEncoder' spring-security provides encode() function of 'BCryptPasswordEncoder' class see the code below:
package com.beingjavaguys.hash;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

public class HashCode {

 public String getHashPassword(String password) {
  BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
  String hashedPassword = passwordEncoder.encode(password);

  System.out.println(hashedPassword);
  return hashedPassword;
 }

}


This function will return an encoded password string, that should be saved to database instead of simple and plain string value. This value can be save as a simple string of type varchar no new thing here.


2) How to authenticate user with encoded password using spring security.


Let us now discuss how retrieve encoded password and how to authenticate user with encoded password in spring-security. To authenticate and user with encoded password we have to add '<password-encoder ref="encoder" />' to '<authentication-provider>' xml tags and everything related to decoding will be handled by spring-security itself. See the 'spring-config.xml' example code below:

\src\main\webapp\WEB-INF\security-config.xml

<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/security
 http://www.springframework.org/schema/security/spring-security-3.2.xsd">

 <http auto-config="true">
  <access-denied-handler error-page="/403page" />
  <intercept-url pattern="/user**" access="ROLE_USER" />
  <intercept-url pattern="/admin**" access="ROLE_ADMIN" />
  <form-login login-page='/login' username-parameter="username"
   password-parameter="password" default-target-url="/user"
   authentication-failure-url="/login?authfailed" />
  <logout logout-success-url="/login?logout" />
 </http>

 <!-- <authentication-manager> <authentication-provider> <user-service> <user 
  name="user" password="user@123" authorities="ROLE_ADMIN" /> </user-service> 
  </authentication-provider> </authentication-manager> -->

 <authentication-manager>
  <authentication-provider>
   <password-encoder ref="encoder" />
   <jdbc-user-service data-source-ref="dataSource"
    users-by-username-query="select username,password, enabled from users where username=?"
    authorities-by-username-query="select username, role from user_roles where username =?  " />
  </authentication-provider>
 </authentication-manager>

 <beans:bean id="encoder"
  class="org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder">
  <beans:constructor-arg name="strength" value="10" />
 </beans:bean>

</beans:beans>


This is all about how to encode and decode password using spring security and how to save an encoded password in database in spring MVC. If you want to see full working code and demonstrate the full functioning of how to save encoded password in database using spring mvc registration form and how to authenticate user with encode password in database, download the full example project from Here.

In upcoming blogs we will see more about Spring, Hibernate, Java and Other opensource technologies.








Thanks for reading !
Being Java Guys Team

Download "Password Hashing or Password Encoding Project" from "SkyDrive"





4 comments:

  1. hai..your post very helpfull..
    maybe you can visit my page..
    Cara membuat web dengan java
    thanks b4

    ReplyDelete
  2. i kept getting this issue:
    org.springframework.beans.factory.xml.XmlBeanDefinitionStoreException: Line 140
    in XML document from ServletContext resource [/WEB-INF/applicationContext-acegi-
    security.xml] is invalid; nested exception is org.xml.sax.SAXParseException: Ele
    ment type "jdbc-user-service" must be declared.
    Caused by:
    org.xml.sax.SAXParseException: Element type "jdbc-user-service" must be declared

    ReplyDelete
  3. I am getting a 404 error after I add the password encoder ref stuff to my xml.

    This is the gist of the error.

    cannot convert value of type [org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder] to required type [org.springframework.security.authentication.encoding.PasswordEncoder] for property 'passwordEncoder': no matching editors or conversion strategy found

    Any idea of the cause?

    ReplyDelete
  4. What about password validation on login ? with Bcrypt it generates new salt everytime a new password is generated. How would you match password if that is correct ?

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft