Newsletter

Spring Boot + Spring Security – RESTful Web Service with Database Authentication

Spring-Boot-Tutorials » on May 17, 2018 { 5 Comments } By Sivateja

This article describes how to implement database authentication for your RESTful web services using Spring Boot and Spring Security. Let me start with the required dependencies..

Dependencies

<!-- Related to Database -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- Related to Database End-->

<!-- Related to Spring security -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<!-- Related to Spring security End -->

Final pom.xml

<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>com.java4s</groupId>
    <artifactId>SpringBootSpringSecurityBasicAuthWithDB</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.6.RELEASE</version>
    </parent>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>
    <properties>
        <java.version>1.8</java.version>
    </properties>
</project>

SpringBootApp.java

package com.java4s.app;

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

@SpringBootApplication
public class SpringBootApp {
    public static void main(String[] args) {

        SpringApplication.run(SpringBootApp.class, args);

    }
}

application.properties

# Applicationn context name
server.contextPath=/springbootauth

# Here 'test' is the database name
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=java4s
spring.datasource.password=java4s
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

SpringSecurityConfig.java

package com.java4s.app.configs;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
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;

@Configuration
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private DataSource ds;

    @Bean
    @ConfigurationProperties("spring.datasource")
    public DataSource ds() {
        return DataSourceBuilder.create().build();
    }

    /* Spring Security Configurations Start */
    @Autowired
    public void configureAMBuilder(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(ds)
            .authoritiesByUsernameQuery("select email, role FROM USERS where email=?")
            .usersByUsernameQuery("select email,userPassword, 1 FROM USERS where email=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .httpBasic()
            .and()
            .authorizeRequests()
            .anyRequest().authenticated();
        http.csrf().disable();
    }
    /* Spring Security Configurations End */
}

/*
   
    FYI.

  	CREATE TABLE Users (
	    id int,
	    userName varchar(255),
	    email varchar(255),
	    userPassword varchar(255),
	    role varchar(10),
	    created timestamp
	);

	insert into users (id, userName, email, userPassword, role, created) values(1,'java4s', 'java4s@java4s.com', 'java4spassword','ADMIN', CURRENT_TIMESTAMP)
	insert into users (id, userName, email, userPassword, role, created) values(1,'siva', 'siva@java4s.com', 'sivapassword','USER', CURRENT_TIMESTAMP)

 */

SpringJava4sController.java

package com.java4s.app.controller;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SpringJava4sController {

    @RequestMapping("/login")
    public String userValidation() {
        return "User: Successfully logged in!";
    }
}

// URL: http://localhost:8080/springbootauth/login

Just start the application and hit http://localhost:8080/springbootauth/login

Friends, IΒ haven’t explained any thing as its pretty straight forwardΒ πŸ™‚ feel free to comment if you have any questions, I will get back to you as soon as I can.

Note: We can control the login using the user roles as well which I haven’t shown in this tutorial. But I will definitely cover that area in the coming articles.

​ ​​

You Might Also Like

  ::. About the Author .::

Java4s_Author
Sivateja Kandula - Java/J2EE Full Stack Developer
Founder of Java4s - Get It Yourself, A popular Java/J2EE Programming Blog, Love Java and UI frameworks.
You can sign-up for the Email Newsletter for your daily dose of Java tutorials.

Comments

5 Responses to “Spring Boot + Spring Security – RESTful Web Service with Database Authentication”
  1. Gayathri says:

    Hi,

    I am getting circular "dependency exception" can someone help me out.
    used same code as here given, exact issue is

    "org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'ds': Requested bean is currently in creation: Is there an unresolvable circular reference?"

  2. suman says:

    Hi Sir,

    Thanks for your tutorial. Can you please explain that how to use the tokens in spring boot rest api to maintain the sessions?

    Thanks in advance.

  3. srinath says:

    Could you please post article on Oauth2

  4. Mahesh Ghatage says:

    Could you please post article on JWT Auth

Name*
Mail*
Website



By posting your answer, you agree to our comments policy.
Most Recent Posts from Top Categories
Spring Boot Hibernate Spring
Contact | About Us | Privacy Policy | Advertise With Us

© 2010 - 2024 Java4s - Get It Yourself.
The content is copyrighted to Sivateja Kandula and may not be reproduced on other websites.