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.

CREATE  TABLE users (
  username VARCHAR(45) NOT NULL ,
  password VARCHAR(45) NOT NULL ,
  enabled TINYINT NOT NULL DEFAULT 1 ,
  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

pom.xml


<?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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.programmingfree</groupId>
    <artifactId>pf-securing-web-jdbc</artifactId>
    <version>0.1.0</version>
 <packaging>war</packaging>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.2.2.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
      <groupId>org.apache.tomcat.embed</groupId>
      <artifactId>tomcat-embed-jasper</artifactId>
      <scope>provided</scope>
  </dependency>
  <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>jstl</artifactId>
  </dependency>
  <!-- tag::web[] -->
  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
  <!-- end::web[] -->
        <!-- tag::security[] -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <!-- end::security[] -->

        <!-- JDBC -->      
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            </dependency>

        <!-- MySQL -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
    </dependencies>


    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

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.

MvcConfig.java


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;

@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        registry.addViewController("/home").setViewName("home");
        registry.addViewController("/").setViewName("home");
        registry.addViewController("/hello").setViewName("hello");
        registry.addViewController("/login").setViewName("login");
        registry.addViewController("/403").setViewName("403");
    }
    
    @Bean(name = "dataSource")
 public DriverManagerDataSource dataSource() {
     DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource();
     driverManagerDataSource.setDriverClassName("com.mysql.jdbc.Driver");
     driverManagerDataSource.setUrl("jdbc:mysql://localhost:3306/userbase");
     driverManagerDataSource.setUsername("root");
     driverManagerDataSource.setPassword("root");
     return driverManagerDataSource;
 }
    
    @Bean
 public InternalResourceViewResolver viewResolver() {
  InternalResourceViewResolver resolver = new InternalResourceViewResolver();
  resolver.setPrefix("/WEB-INF/jsp/");
  resolver.setSuffix(".jsp");
  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.

WebSecurityConfig.java


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;

@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

 @Autowired
 DataSource dataSource;
 
 @Autowired
 public void configAuthentication(AuthenticationManagerBuilder auth) throws Exception {
  
   auth.jdbcAuthentication().dataSource(dataSource)
  .usersByUsernameQuery(
   "select username,password, enabled from users where username=?")
  .authoritiesByUsernameQuery(
   "select username, role from user_roles where username=?");
 } 
 
 @Override
 protected void configure(HttpSecurity http) throws Exception {

   http.authorizeRequests()
  .antMatchers("/hello").access("hasRole('ROLE_ADMIN')")  
  .anyRequest().permitAll()
  .and()
    .formLogin().loginPage("/login")
    .usernameParameter("username").passwordParameter("password")
  .and()
    .logout().logoutSuccessUrl("/login?logout") 
   .and()
   .exceptionHandling().accessDeniedPage("/403")
  .and()
    .csrf();
 }
 
}

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.

403.jsp

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

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!

Subscribe to GET LATEST ARTICLES!


Related

Trending 1782149228639510067

Post a Comment

  1. Replies
    1. Lodha Hinjewadi project greatest and most great made 2/3/BHK luxury real estate project with the greatest project , facilities, and amenities is the Lodha project. Lodha is where your Pune luxury brand project apartments and flats are available. Lodha Hinjewadi premium businesses. Lodha Hinjewadi most famous project is one that you really should see make pune.
      Lodha Hinjewadi class project brands premium project new flats.
      Lodha Hinjewadi project liked construction of houses Lodha Hinjewadi. All of Pune's luxury projects and top-notch amenities can be found in the Lodha Hinjewadi branded project. Residential Pune at modestly priced flats and apartments.
      Lodha Hinjewadi Pune Amenities:-

      Bank & ATM
      Intercom Facility
      Swimming Pool
      State of the Art Gym
      Kids Play Areas
      Temple Area
      Yoga Court
      For More Information calls us: - 020-71178598
      Visit:-https://www.tumblr.com/rajkumarvistar/708942484873625600/lodha-hinjewadi-phase-1-upcoming-residential

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

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

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

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

      # database
      spring.datasource.url=jdbc:mysql://localhost:3306/test
      spring.datasource.username=john
      spring.datasource.password=pwd
      spring.datasource.driver-class-name=com.mysql.jdbc.Driver

      Delete
  4. This comment has been removed by the author.

    ReplyDelete

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

    Learn software testing. find software testing training in chennai
    sources

    ReplyDelete
  6. 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 .

    ReplyDelete
  7. 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
    2. BLINK HTML GOOGLE TRICK

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

    ReplyDelete

  8. It was nice to read your blog. If anyone needs any type of case study and assignment help at the cheapest price then visit our website:- My Case Study Help. We are the best Assignment Help Australia website, provide all types of services for MBA Assignment Help, Nursing Case Study Help, Law Case Study Help and Engineering students. Avail Assignment Writing Service with the world's most trusted and no1 company for Case Study and Assignment Help in Australia. Get professionally prepared assignment by our amazing Case Study Writers with 100% quality check and plagiarism free paper.

    ReplyDelete
  9. Thanks for sharing such a great blog. It is very informative for me as I was looking for the same one. I hope you will post more information regarded to this.


    Visit: https://www.mysavinghub.com/store/microperfumes-com-coupons

    ReplyDelete
  10. web design agency in vizag
    Consider your website as the mechanical core of your company. Could you choose to recognize a particularly organised face to greet them and make them feel loved if someone walked through your actual neighborhood? A revived and modern site design is equivalent to a highly arranged face greeting your new visitors.
    The requirement for a responsive game plan is more now than it was in the past because to advancements in cells. A wide range of devices, such as PDAs, tablets, and laptops, will be used by your audience to access your website. You should make sure that everyone has a good experience if you believe that these leads should stay on your website.

    ReplyDelete
  11. The security level provided by using this authentication system is remarkable. It uses an advanced hashing algorithm which makes it practically impossible for anyone to gain access to your user data without proper authorization. Plus, I found that the process of configuring the authentication process was quite straightforward; allowing me to configure everything in just a few minutes.

    ReplyDelete
  12. Thank you so much for sharing. I have found it extremely helpful! Furthermore, If you are Looking for a perfect Residential Roof Service in Leming TX, LEO'S ROOFING is at your service!

    ReplyDelete
  13. This is a fantastic resource for anyone looking to learn more about digital marketing agency london

    ReplyDelete
  14. Great article ! I really appreciated the depth of analysis and the clarity of the writing.

    ReplyDelete
  15. I got here much interesting stuff. The post is great! Thanks for sharing it!

    ReplyDelete
  16. I really enjoyed reading your post. It was well-written and engaging

    ReplyDelete
  17. great article, i wish i can do like this join and teach me in CAIRTOGEL

    ReplyDelete

  18. Well done, buddy, and thanks for sharing your excellent research strategy. I'll definitely use it in my segment. Macbook Screen Replacement

    ReplyDelete
  19. What a comprehensive and insightful exploration of twin gear pumps in Qatar's industrial scene! This blog truly highlights how innovation in pumping technology, like twin gear pumps, plays a pivotal role in advancing various sectors.
    dholeratriangle.
    website: https://www.dholeratriangle.com/

    ReplyDelete
  20. Wow, what an insightful article! I've always been curious about this topic, and you've explained it so clearly. Your writing style makes it easy for someone like me, who's not an expert, to grasp the concepts. I particularly liked how you provided real-life examples to illustrate your points. It's evident that you've done thorough research, and I appreciate the effort you've put into this. Looking forward to reading more of your work! Keep up the great job! ūüĆüūüďö
    indiantradebird.
    website: https://www.indiantradebird.com/product/non-woven-bag-making-machine

    ReplyDelete
  21. "Wow, this article really struck a chord with me! The insights shared here are truly refreshing and thought-provoking. It's evident that the author has a deep understanding of the topic and has managed to present it in such an engaging way. I especially loved how the personal anecdotes woven into the content added a relatable touch. It's not every day that you come across such well-researched and eloquently written pieces. Kudos to the author for shedding light on this issue from a perspective that's both insightful and unique. Looking forward to reading more content like this in the future!"
    indiantradebird.
    website: https://www.indiantradebird.com/product/flexographic-printing-machine

    ReplyDelete
  22. Great read! Thanks for sharing such insightful information. Keep up the good work! biggbossvoting

    ReplyDelete
  23. The simplicity and flexibility of JDBC authentication and authorization make it an excellent choice for developers seeking to enhance application security with minimal setup.https://hexacorp.com/moving-from-on-premises-to-azure






    ReplyDelete
  24. Are you looking to embark on a journey into the dynamic world of full-stack development with Python? Look no further! Gautham Digital Learning offers comprehensive Python full-stack training in Hyderabad.

    ReplyDelete
  25. Are you looking to embark on a journey into the dynamic world of full-stack development with Python? Look no further! Gautham Digital Learning offers comprehensive Python full-stack training in Hyderabad.

    gautham digital learning

    ReplyDelete
  26. Die Einnahme von Natriumpentobarbital kann gef√§hrlich sein und sollte nur unter √§rztlicher Aufsicht erfolgen. √úberdosierungen k√∂nnen zu schwerwiegenden Nebenwirkungen wie Koma und sogar zum Tod f√ľhren. Deshalb sind wir hier, um Ihnen zu helfen. Besuchen Sie unseren Shop oder sprechen Sie online mit uns
    https://nembutalkaufen.com/fr/produit/nembutal-fluide-pour-prendre/
    https://nembutalkaufen.com/
    natrium pentobarbital kaufen
    natrium pentobarbital kaufen ohne rezept
    pentobarbital amazon
    nembutal kaufen
    https://nembutalkaufen.com/fr/
    natrium pentobarbital bestellen
    pentobarbital kaufen ohne rezept
    nembutal online kopen
    natrium pentobarbital kaufen preis
    pentobarbital natrium kaufen
    natrium pentobarbital kaufen deutschland
    nembutal pentobarbital natrium kaufen
    natrium-pentobarbital kaufen
    pentobarbital kaufen
    https://pentobarbitalkaufen.com/
    waar nembutal kopen
    nembutal kaufen schweiz
    wo kann ich natrium pentobarbital kaufen
    buy nembutal pentobarbital sodium
    pentobarbital for sale
    pentobarbital kopen
    nembutal kopen
    buy natrium pentobarbital
    nembutal bestellen
    pentobarbital-natrium online kaufen
    nembutaal te koop
    solution de nembutal buvable
    nembutal-pillen, injektion und pulver zum verkauf
    barbiturate kaufen
    buy nembutal online
    natriumpentothal
    pentobarbital gdzie kupińá
    kaufen sie nembutal-kapseln online
    hoe pentobarbital te kopen
    nembutal pentobarbital
    natrium pentobarbital pulver
    morbital gdzie kupińá
    kaufen pentobarbital
    barbituraat kopen
    barbiturat kaufen
    kaufen sie nembutal-pillen online
    pijnloze zelfmoord
    nembutal online kaufen
    buy sodium pentobarbital
    natrium pentobarbital acheter
    pentobarbital natrium bestellen
    order nembutal online

    https://kokainbestellen.com/fr/
    https://kokainbestellen.com/

    ReplyDelete

emo-but-icon

SUBSCRIBE


item