Here is spring boot basic authentication database using Spring security. During REST full web service development basic authentication is too much require to secure API which needs to only accessible from authenticated users only. Spring Security provides basic authentication using JDBC database authentication. Here is a complete example of spring boot basic authentication database using spring security.

Technology

  • Spring Boot
  • Spring Security (Basic authentication)
  • MySQL
  • Maven
  • Java 8

Project Structure

spring boot basic authentication database project structure

spring boot basic authentication database project structure

Source Code

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>spring-boot-example</groupId>
    <artifactId>spring-boot-basic-authentication-database</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>spring boot basic authentication database</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.4.RELEASE</version>
    </parent>
    <properties>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>  <!--starter require for spring boot spring security-->
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>           <!-- Its related to mysql-->
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
    </dependencies>

    <!-- Package as an executable jar -->
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

application.properties

It’s data source properties which contain information related to connecting with a database. app.datasource is base properties name. which has been used when autowire @ConfigurationProperties("app.datasource").

app.datasource.url=jdbc:mysql://localhost/demo_database
app.datasource.username=root
app.datasource.password=
app.datasource.driver-class-name=com.mysql.jdbc.Driver

SpringBootConfig

It’s spring boot startup file. Here datasource has been created which will be passed to spring security authentication object.

package com.javadeveloperzone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
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.ComponentScan;

import javax.sql.DataSource;

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */

@SpringBootApplication
@ComponentScan({"com.javadeveloperzone"})

// Using a root package also allows the @ComponentScan annotation to be used without needing to specify a basePackage attribute
public class SpringBootConfig {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(SpringBootConfig.class, args);            // it wil start application
    }

    @Bean(value = "datasource")
    @ConfigurationProperties("app.datasource")
    public DataSource dataSource() {
        return DataSourceBuilder.create().build();
    }
}

SecurityConfiguration

It contains all spring security configuration related to basic authentication. Spring security by default secure all pages. Here has DataSource been autowire which contains all properties related to database connection and pass that object to Spring security authentication builder.

package com.javadeveloperzone;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
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.context.annotation.Primary;
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.stereotype.Component;

import javax.sql.DataSource;

/**
 * Created by JavaDeveloperZone on 04-08-2017.
 */
@Configuration
@Component
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("datasource")
    private DataSource dataSource;

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication().dataSource(dataSource)
            .authoritiesByUsernameQuery("select employeeName, employeeRole FROM employee where employeeName=?")
            .usersByUsernameQuery("select employeeName,employeePassword as password,1 FROM employee where employeeName=?");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .httpBasic()                      // it indicate basic authentication is requires
                .and()
                .authorizeRequests()
                 .antMatchers( "/index").permitAll() // /index will be accessible directly, no need of any authentication
                .anyRequest().authenticated();    // it's indicate all request will be secure

        http.csrf().disable();

    }
}

SpringBootExampleController

package com.javadeveloperzone.controller;

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

/**
 * Created by JavaDeveloperZone on 19-07-2017.
 */
@RestController
public class SpringBootExampleController {

    @RequestMapping("/")
    public String SpringBootHello() {
        return "spring boot basic authentication database";
    }
}

Demo

spring boot basic authentication database login

 

spring boot basic authentication database

spring boot basic authentication database

spring boot basic authentication database login success

spring boot basic authentication database login success

spring boot basic authentication database login success

spring boot basic authentication database login failed

spring boot basic authentication database login failed

spring boot basic authentication database login failed

References:

Spring Boot Security Documents

 

Was this post helpful?
Let us know, if you liked the post. Only in this way, we can improve us.
Yes
No
Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *