Home  >  Spring Security

How to Use Password Encoder in Spring Security

By Arvind Rai, December 20, 2013
This page will help you to understand how to use spring security with encoded password. Encoded password is necessary in the application where security is more concern. To add password encoder we need to use the <password-encoder/> inside <authentication-provider>. Find more detail on <password-encoder/>.

<password-encoder/>

<password-encoder/> has the attribute hash that can be assigned encoding algorithm. In our example we are using SHA 1 encoding configure the below line to add password encoder.
<password-encoder hash="sha"/>
 
If we have a user concretepage and password con1234, then we will configure it as
<http auto-config="true">
	<intercept-url pattern="/login" access="ROLE_USER" />
	<logout logout-success-url="/login" />
</http>
<authentication-manager>
  <authentication-provider>
    <password-encoder hash="sha"/>
    <user-service>
      <user name="concretepage" password="0733824cc1549ce36139e8c790a9344d1e385cd2"
            authorities="ROLE_USER" />
    </user-service>
  </authentication-provider>
</authentication-manager>
 

Password Encoder in Spring Security using Database

If we are interested to use database to keep user login information. Then we can achieve it as below.
    <http auto-config="true">
		<intercept-url pattern="/login" access="ROLE_USER" />
		<logout logout-success-url="/login" />
	</http>
	<authentication-manager>
     <authentication-provider>
      <password-encoder hash="sha"/>
       <jdbc-user-service data-source-ref="dataSource" authorities-by-username-query="SELECT username, authority FROM authorities WHERE username = ?"
            users-by-username-query="SELECT username, password, enabled FROM users WHERE username = ?"/>
     </authentication-provider>
   </authentication-manager>
   <beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <beans:property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <beans:property name="url" value="jdbc:mysql://localhost:3306/test"/>
        <beans:property name="username" value="root"/>
        <beans:property name="password" value=""/>
   </beans:bean>

 
In our example we have used password encoder with database. Use URL http://localhost:8080/SpringSecurity/login to run the example. To understand table schema, go to the link Spring Security Login Example with Database

Output UI

How to Use Password Encoder in Spring Security

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS



Copyright ©2017 concretepage.com, all rights reserved |Privacy Policy | Contact Us