1. Overview

This article contains Spring boot 2 Spring security 5 in-memory Basic Authentication Example. Spring boot 2 by default supports Spring Security 5. This example contains in-memory authentication with static username and password. We will learn how we can secure Spring boot API using spring security 5 basic authentication.

 2. Example

Spring security 5 in-memory Basic Authentication Example

Spring security 5 in-memory Basic Authentication Example

2.1 pom.xml

We have used here spring-boot-starter-parent-2.0.0.RELEASE version for spring boot 2. Spring boot 2 by default support Spring security 5 so no need to maintain version in spring-boot-starter-security dependency.

<?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</artifactId>
    <version>1.0-SNAPSHOT</version>
    <description>Spring security 5 in-memory Basic Authentication Example</description>
    <!-- Inherit defaults from Spring Boot -->
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.0.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>
            <artifactId>spring-boot-starter-security</artifactId>
        </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>

2.2 SpringBootConfig

It normal like other spring boot application.

package com.javadeveloperzone;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

/**
 * Created by JavaDeveloperZone on 07-04-2018.
 */

@SpringBootApplication
@ComponentScan // 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
    }
}

2.3 SecurityConfiguration

After spring security 5 multiple password encryption is supported. So password will be stored like {EncoderType}PasswordText . If the password is not encrypted then {noop} must be there, {noop}indicates plain text password. There is no encryption written before password then it will throw an exception  java.lang.IllegalArgumentException: There is no PasswordEncoder mapped for the id "null" while the user tries to log in.

Let’s define a configuration which extends  WebSecurityConfigurerAdapter where:

Using HttpSecurity we can define security type as basic or form-based authentication, exclude or include URLs for security.  Here we have used in-memory authentication, generally, if we have few users then we can use in-memory authentication otherwise database authentication is preferable.

package com.javadeveloperzone;

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;


/**
 * Created by JavaDeveloperZone on 07-04-2018.
 */
@Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired      // here is configuration related to spring boot basic authentication
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()                   // for inMemory Authentication
            .withUser("zone").password("{noop}password").roles("USER")          // {noop} for plain text
            .and()
            .withUser("zone3").password("{noop}password").roles("USER");
    }

    @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();      // to disable csrf
    }
}

2.4 DemoController

This controller contains two API one is /index which does not contain any security. another one is secureAPI to access it requires basic authentication.

package com.javadeveloperzone.controller;

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

/**
 * Created by JavaDeveloperZone on 07-04-2018.
 */
@RestController             // to generate JSON Response
public class DemoController {

    @GetMapping(value = "index")
    public String index(){
        return "This is index API and It's without Security";
    }

    @GetMapping(value = "secureAPI")
    public String secureAPI() {
        return "Spring security 5 in-memory Basic Authentication Example";
    }
}

2.5 Output:

Let’s access secure API with basic authentication using POSTMAN tools :  http://localhost:8080/secureAPI

 

Spring security 5 in-memory Basic Authentication Example - Call Secure API

Spring security 5 in-memory Basic Authentication Example – Call Secure API

 

If anyone tries to access http://localhost:8080/secureAPI without basic authentication then it will throw 401 (Unauthorized) like:

Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.

Sat Apr 07 10:40:19 IST 2018
There was an unexpected error (type=Unauthorized, status=401).
Unauthorized

3. Conclusion

In this article, we have seen that how we can configure Spring boot 2 and Spring Security 5 to secure API with basic authentication.

4. References

5. Source Code

Spring security 5 in-memory Basic Authentication Example (46 KB)

 

 

 

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

Leave a Reply

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