Spring security note – Create a simple authentication-manager by get user from DB table – 2

By WZH. Sept 2016

When you use the Spring Security, you system could save user define in many kinds of places, such as dummy test account , DB table, or LDAP. So you just need to have different user service supply to spring security’s  authentication-manager, as far as you meet the needs defined by the authentication-manager.

authentication-manager in fact needs a UserDetails object to contain the user name, password and Authorities. Here I show you one example that just use XML to define a DB access user service :

<security:authentication-manager id="directDBAuthManager">
            <security:password-encoder hash="md5" />
                data-source-ref="myDataSource" id="userDetailsDBService"
                users-by-username-query="SELECT username, password, enabled FROM abc_DB.usertable WHERE username=?"
                authorities-by-username-query="SELECT username, role FROM abc_DB.usertable where username =?  " />


myDataSource is a datasource define in the spring, refer to datasource define docs. Then  you just need to use it at here to access DB.

users-by-username-query must be a SQL to return the user name , password and enable(true/false) in this order to the system(no need to be these names). So you can see that my DB of abc_DB has a table called usertable to contain the user data and return these data to system.

authorities-by-username-query in fact returns the user and and roles to the system to create the authorities.

Spring internal in fact uses there two query to get data and create the method of
public UserDetails loadUserByUsername(String username)  for the UserDetailsService.

<security:password-encoder hash=”md5″ /> this is a note that password format in fact is a MD5. So when the authentication-manager get the UserDetails, it will compare the login input’s password with password from UserDetails in the MD5 format.

id=”userDetailsDBService” – with this ID here, you can look up this bean by ID in the java code to call this UserDetailsService. so that when you need to UserDetails in java code, you can just call this user service directly.