Over a million developers have joined DZone.

Spring Boot With Spring Security and JDBC

DZone's Guide to

Spring Boot With Spring Security and JDBC

This article showcases the combination of Spring Security with JDBC with a simple Gradle application.

· Database Zone ·
Free Resource

RavenDB vs MongoDB: Which is Better? This White Paper compares the two leading NoSQL Document Databases on 9 features to find out which is the best solution for your next project.  

Spring Security is a wonderful framework, saving lots of time and effort for developers.

Working with JDBC and Spring Security is pretty easy — many actions are automated. This will be a minimal showcase.

The Gradle file contains dependencies such as spring-security, spring-jdbc, and h2 database

group 'com.gkatzioura'
version '1.0-SNAPSHOT'

buildscript {
    repositories {
    dependencies {

apply plugin: 'java'
apply plugin: 'idea'
apply plugin: 'spring-boot'

sourceCompatibility = 1.8

repositories {

dependencies {
    testCompile "junit:junit:4.11"

Tables containing certain information must be created. Those tables will have the default name and column names that Spring Security lookups in order to get information.

drop table if exists users;
create table users(id bigint auto_increment, username varchar(255), password varchar(255), enabled boolean);
insert into users(username,password,enabled) values('steve','steve',true);
insert into users(username,password,enabled) values('john','john',true);
drop table if exists authorities;
create table authorities(username  varchar(255),authority  varchar(255), UNIQUE(username,authority));
insert into authorities(username,authority) values('steve','admin');
insert into authorities(username,authority) values('john','superadmin');

Those sql statements will reside on resources/schema.sql.

First step is to create our Application class

package com.gkatzioura.spring.security;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

 * Created by gkatzioura on 9/2/16.
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);


In order to get started quickly, the database will be an h2 database.

package com.gkatzioura.spring.security.config;

import org.h2.jdbcx.JdbcDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.nio.file.Files;

 * Created by gkatzioura on 9/2/16.
public class DataSourceConfig {

    public DataSource createDataSource() {

        JdbcDataSource dataSource = new JdbcDataSource();

        return dataSource;


By specifying the h2 database, I set the directory to be inside the temporary directory. Therefore, once you restart your OS, the database will be gone. As mentioned previously, once the datasource bean has been initialized, spring-jdbc will automatically lookup on the resource folder for a schema.sql file. In case the file exists, spring-jdbc will try to execute the statements that the schema.sql contains.

The next step is to define our security configuration. We have to specify that our security will be based on JDBC. We must also define the endpoints that will have to be secure.

package com.gkatzioura.spring.security.config;

import org.springframework.beans.factory.annotation.Autowired;
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 javax.sql.DataSource;

 * Created by gkatzioura on 9/2/16.
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private DataSource dataSource;

    public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {

    protected void configure(HttpSecurity http) throws Exception {


Last but not least, we will add a controller with a secured endpoint and a non-secured endpoint

package com.gkatzioura.spring.security.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

 * Created by gkatzioura on 9/2/16.
public class GreetController {

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

    @RequestMapping(path = "/public",method = RequestMethod.GET)
    public String sayFreeHi() {
        return "Greeting";

    @RequestMapping(path = "/secured",method = RequestMethod.GET)
    public String saySecureHi() {
        return "Secured";


Once you try to access the secured endpoint, the default Spring Security login screen will be displayed. Proceed with one of the users specified in the SQL statements (for example username: steve password: steve). In case you want to log out, just hit the /login?logout endpoint.

Run the application with:

gradle bootRun

That's it! You can find the source code on GitHub.

Get comfortable using NoSQL in a free, self-directed learning course provided by RavenDB. Learn to create fully-functional real-world programs on NoSQL Databases. Register today.

spring security ,spring ,application ,datasource

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}