Spring Security 4 - Simple JDBC Authentication and Authorization

In one of my articles, I explained with a simple example on how to secure a Spring MVC application using Spring Security and with Spri...

In one of my articles, I explained with a simple example on how to secure a Spring MVC application using Spring Security and with Spring Boot for setup. I am going to extend the same example to now use JDBC Authentication and also provide Authorization. To be more specific, in this article I am going to explain how to use Spring Security in a Spring MVC Application to authenticate and authorize users against user details stored in a MySql Database.

I am not going to start from scratch this time, in stead use the existing example from my previous spring security tutorial and modify it to make it fit to our current scenario. So, you can have a look at the article real quick and come back here.

1. First of all download the existing application from here.

2. Import project to eclipse using the Import wizard.

3. Run the following statements in mysql server. This sets up the user table and the user_roles table for us with some initial data to start with.

  username VARCHAR(45) NOT NULL ,
  password VARCHAR(45) NOT NULL ,
  PRIMARY KEY (username));
CREATE TABLE user_roles (
  user_role_id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(45) NOT NULL,
  role varchar(45) NOT NULL,
  PRIMARY KEY (user_role_id),
  UNIQUE KEY uni_username_role (role,username),
  KEY fk_username_idx (username),
  CONSTRAINT fk_username FOREIGN KEY (username) REFERENCES users (username));

INSERT INTO users(username,password,enabled)
VALUES ('priya','priya', true);
INSERT INTO users(username,password,enabled)
VALUES ('naveen','naveen', true);

INSERT INTO user_roles (username, role)
VALUES ('priya', 'ROLE_USER');
INSERT INTO user_roles (username, role)
VALUES ('priya', 'ROLE_ADMIN');
INSERT INTO user_roles (username, role)
VALUES ('naveen', 'ROLE_USER');

Heads Up!

Do not ever use plain text for passwords. The right way to do this is to use password encryption.You can find the link to an updated and detailed tutorial below,

Spring Security JDBC Authentication with Password Encryption

4. Let us get back to our application now. First thing to do is to modify pom.xml file to include spring-jdbc and mysql-connector


<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

  <!-- tag::web[] -->
  <!-- end::web[] -->
        <!-- tag::security[] -->
        <!-- end::security[] -->

        <!-- JDBC -->      

        <!-- MySQL -->


5. Now we have to provide a definition to the mysql datasource in our MvcConfig class which has all necessary information to connect to the database we created before.


package hello;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

public class MvcConfig extends WebMvcConfigurerAdapter {

    public void addViewControllers(ViewControllerRegistry registry) {
    @Bean(name = "dataSource")
 public DriverManagerDataSource dataSource() {
     DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
     return driverManagerDataSource;
 public InternalResourceViewResolver viewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  return resolver;

Note that I have added one more line to addViewControllers method to register a view for "403" (access denied) page.  This page will be displayed whenever an user tries to access a page he/she is not authorized to.

6. Next we have to modify the security configuration class to use the jdbc datasource we have defined for authenticating and authorize users.


package hello;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
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.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 DataSource dataSource;
 public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
   "select username,password, enabled from users where username=?")
   "select username, role from user_roles where username=?");
 protected void configure(HttpSecurity http) throws Exception {


In simple words,

-- First we declare a datasource object annotated with @Autowired. This will look for Datasource definition in all classes under the same package. In this example we have it defined in MvcConfig.java
-- Next we set up two queries for AuthenticationManagerBuilder. One for authentication in usersByUsernameQuery and the other for authorization in authoritiesByUserNameQuery.
-- Finally we configure HttpSecurity to define what pages must be secured, authorized, not authorized, not secured, login page, logout page, access denied page, etc. One important thing to notice here is the order of configuration. Configuration that is specific to certain pages or urls must be placed first than configurations that are common among most urls.

7. Finally, write a jsp page to be displayed whenever access is denied to an user.


<%@ page language="java" contentType="text/html; charset=UTF-8"
<!DOCTYPE html>
<title>Access Denied - ProgrammingFree</title>
<h1>You do not have permission to access this page!
<form action="/logout" method="post">
          <input type="submit" value="Sign in as different user" /> 
          <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

That is all!

To run the application, run as Maven Build,

Once embedded tomcat in the application starts, Open localhost:8080

Welcome Page

Click on the link to see greeting page, you will be redirected to login page,

Login Page

Only admin users are authorized to see the greeting. Login as a Non- Admin user and try to access the greeting page,

Access Denied Page

Logout and sign in as an ADMIN User, then you must be able to access the greeting page,

Greeting Page

How to run the Demo Project

There is one more better way of implementing Spring Security which is using Spring Data JPA. I will probably explain that in one of my upcoming articles. Stay subscribed!

Keep yourself subscribed for getting programmingfree articles delivered directly to your inbox once in a month. Thanks for reading!



Trending 1782149228639510067

Post a Comment

  1. http://www.roytuts.com/spring-security-jdbc-authentication/


  2. is it possible to define datasource bean in xml file inside src/main/resource directory in maven webapp

    1. You can add this to your application.properties file under /src/main/resources

      # database

  3. On that website page, you'll see your description, why not read through this 먹튀검증

  4. This comment has been removed by the author.


  5. In this short tutorial,you have explained it very well..

    Learn software testing. find software testing training in chennai

  6. Really nice and informative blog, keep it up. Thanks for sharing and I have some suggestions.
    if you want to learn Mobile App Development(android, iOS), Join Now Mobile App Training in Bangalore.
    Visit a Website:- Android Training in Bangalore | AchieversIT
    This may help you to find something useful

  7. This Is Most Useful And Give More Knowledge For Me And Let Me Share It For Alot Of People. And Dont Forget Ti Visit Me Back
    Click Here For Visit My Site thanks .

  8. Seo services in Varanasi : Best SEO Companies in Varanasi: Hire Digital Marketing Agency, best SEO Agency in Varanasi who Can Boost Your SEO Ranking, guaranteed SEO Services; SEO Company In Varanasi.

    Digital Marketing Company In India : Kashi Digital Agency is one of the Best Digital Marketing companies in Varanasi, India . Ranked among the Top digital marketing agencies in India. SEO Company In India.

    Cheap Website Design Company In Bangalore : Best Website Design Company in Bangalore : Kashi Digital Agency is one of the Best Social Media Marketing agency in Bangalore which provides you the right services.

    E-commerce Website design company India : e-commerce Company in India : Kashi Digital Agency is one of the best e-commerce development services provider in Varanasi, India. This one of the best service if you want quick ROI.

  9. I really appreciate the effort you made to share the knowledge. The topic here I found was really effective…

    Check this 1. Best Hacking Websites in Hindi

    3. Turbo VPN VIP Apk link Click here to Latest Download