Social Media
  • You are here:
  • Home »
  • Java »

Auto-generating Spring Security Tutorial – Custom JDBC Realms

This post builds on the set of spring-security posts I have done, and particularly my last post on Default JDBC Realms. The code is available on github, and spring-security-generator and the instructions to run the application are contained in the previous tutorial.

We also have a requirement to use a custom JDBC realm with the structure –

customadmin customadmin ROLE_CUSTOM_ADMIN

Custom JDBC Tables

The tables Ive used in this example are renamed versions of the default tables -

create table custom_users (
  username varchar(256),
  password varchar(256),
  enabled boolean
create table custom_authorities (
  username varchar(256),
  authority varchar(256)
With inserts - 

insert into custom_users (username, password, enabled) values ('customadmin', 'customadmin', true);
insert into custom_authorities (username, authority) values ('customadmin', 'ROLE_CUSTOM_ADMIN');


Using spring-security-generator we now select “JDBC Realm (Custom)” and supply the queries –

select username, password, enabled from custom_users where username = ?
select username, authority from custom_authorities where username = ?

The screen configuration is then –


We then generate the code –

package com.glenware.springboot;

import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;

public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private DataSource dataSource;

    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception {
                   "select username, password, enabled from custom_users where username = ?")
                   "select username, authority from custom_authorities where username = ?");

    protected void configure(HttpSecurity http) throws Exception {

The key difference between this tutorial and the previous is that we supply the SQL directly to the usersByUsernameQuery and authoritiesByUsernameQuery

We can now copy this code to the parkrunpb applicaiton, and login using customadmin/customadmin

About the Author Martin Farrell

My name is Martin Farrell. I have almost 20 years Java experience. I specialize inthe Spring Framework and JEE. I’ve consulted to a range of businesses, and have provide Java and Spring mentoring and training. You can learn more at About or on my consultancy website Glendevon Software

follow me on:

Leave a Comment:

1 comment
Add Your Reply