Over a million developers have joined DZone.

Spring Security and Password and Encoding

By being careful enough we will find out that passwords are in plain text. Although this serves well for example purposes in real environments, passwords are always encoded and stored encoded in the database.

Download Forrester’s “Vendor Landscape, Application Performance Management” report that examines the evolving role of APM as a key driver of customer satisfaction and business success, brought to you in partnership with BMC.

In previous posts, we dove into spring security. We implemented security backed by JDBC, security based on custom JDBC queries and security retrieving information from a NoSQL database.

By being careful enough we will find out that passwords are in plain text. Although this serves well for example purposes in real environments, passwords are always encoded and stored encoded in the database.

Spring security supports password encoding in a pretty convenient way. It comes with its own preconfigured password encoders but It also gives us the ability to either create our custom password encoder.

StandardPasswordEncoder, Md5PasswordEncoder and the popular BCryptPasswordEncoder are some of the password encoders that come along with spring security . Please be aware that md5 leads poor security therefore prefer bcrypt.

package com.gkatzioura.spring.security;

import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.StandardPasswordEncoder;

 * Created by gkatzioura on 10/5/16.
public class EncoderTest {

    private static final Logger LOGGER = LoggerFactory.getLogger(EncoderTest.class);

    public void md5Encoder() {

        Md5PasswordEncoder md5PasswordEncoder = new Md5PasswordEncoder();
        String encoded = md5PasswordEncoder.encodePassword("test_pass",null);

        LOGGER.info("Md5 encoded "+encoded);

    public void bcryptEncoder() {

        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String encoded = bCryptPasswordEncoder.encode("test_pass");

        LOGGER.info("Becrypt encoded "+encoded);

    public void standardEncoder() {

        StandardPasswordEncoder standardPasswordEncoder = new StandardPasswordEncoder();
        String encoded = standardPasswordEncoder.encode("test_pass");

        LOGGER.info("Standard encoded "+encoded);


To add password encoding all we have to do is to set a password encoder in our spring configuration.

With jdbc-backed spring security configuration it is pretty easy, we just set the password encoder of our choice. In our case, we will use the bcrypt password encoder.

package com.gkatzioura.spring.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

import javax.sql.DataSource;

 * Created by gkatzioura on 10/5/16.
public class PasswordEncodedSecurityConfig extends WebSecurityConfigurerAdapter {

    private DataSource dataSource;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {

                .passwordEncoder(new BCryptPasswordEncoder())
                .usersByUsernameQuery("SELECT username,password,1 FROM Custom_Users_Encoded_pass where username=?")
                .authoritiesByUsernameQuery("SELECT username,authority FROM Custom_Roles where username=?");

    protected void configure(HttpSecurity http) throws Exception {



Then we will add a user to the database with the encoded password.

drop table if exists Custom_Users_Encoded_pass;
create table Custom_Users_Encoded_pass(id bigint auto_increment, username varchar(255), password varchar(255));
-- real password is test_pass
insert into Custom_Users_Encoded_pass(username,password) values('TestUser','$2a$10$nA8k2TPoXgACwWhCZXhomOlvwtNReWprcVgjRpDiZNAGXN3UMLgSO');

Therefore by trying to access http://localhost:8080/secured will have to give the username TestUser and the password test_pass in the login prompt.

Last but not least we will have to change our gradle.build to set encodedjdbcpassword as our default profile.

bootRun {
    systemProperty "spring.profiles.active", "encodedjdbcpassword"

You can find the source code on GitHub.

See Forrester’s Report, “Vendor Landscape, Application Performance Management” to identify the right vendor to help IT deliver better service at a lower cost, brought to you in partnership with BMC.

spring,password,spring security,performance

Published at DZone with permission of Emmanouil Gkatziouras, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}