x Java Java 8 JUnit JSON
  • XML
  • JDBC Spring Boot Microservices React Contact Us

    Spring Boot Security REST API Basic authentication

    To protect a REST API being invoked by any unwanted users, you need to have a security mechanism like BASIC authenciation. This tutorial explains how to secure a REST API with Basic Authentication using Spring Boot security. We will use in-memory authentication configuration which means we will keep user credentials to verify in the memory.

    Step 1) Create pom.xml

    In the pom.xml add below 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>           

    Step 2) Create Novel POJO class which contains a Novel details

    package com.example.demo;
    
    public class Novel {
    
        private String title;
    	private String author;
        
        // removed constructor, getter and setter for brevity
    
    }    

    Step 3) Create NovelRestController class which exposes /novels GET API

    package com.example.demo;
    import java.util.ArrayList;
    import java.util.List;
    
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class NovelRestController {
    	
        List<Novel> novels = new ArrayList<>();
            
        public NovelRestController() {
        	novels.add(new Novel("The Fountainhead", "Ayn Rand"));
        	novels.add(new Novel("Murder on the Orient Express", "Agatha Christie"));
        }
    
        @GetMapping("/novels") 
        public List<Novel> getNovels() {
            return novels;
        }
    }  

    Step 4) Create NovelApplication class

    package com.example.demo;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
    
    @SpringBootApplication
    @EnableWebSecurity
    public class NovelApplication {
    
        public static void main(String[] args) {
            SpringApplication.run(NovelApplication.class, args);
        }
    } 

    Step 5) Create CustomerSecurityConfig class which is used to configure security for the REST API.

    To enable basic authentication in the REST API, we need to override WebSecurityConfigurerAdapter. When a user submits user and password, BasicAuthenticationFilter creates a UsernamePasswordAuthenticationToken by extracting user/password from HttpServletRequest, UsernamePasswordAuthenticationToken is then authenciated by AuthenticationManager. If authentication is successful, BasicAuthenticationFilter invokes FilterChain.dofilter to continue the flow.

    In configure method, we will enable http basic authenciation using httpBasic() call. Also csrf is disabled using csrf() call.

    package com.example.demo;
    
    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.EnableWebSecurity;
    import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
    
    @Configuration
    @EnableWebSecurity
    public class CustomerSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http.csrf().disable().authorizeRequests().anyRequest().authenticated().and().httpBasic();
        }
    
        @Autowired
        public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
            auth.inMemoryAuthentication().withUser("user").password("{noop}password").roles("USER");
        }
    	
        // The {noop} in the password field means that encryption has not been applied to the stored password
    
    }      

    Step 7) Testing REST API Basic Authentication

    Open any browser and launch http://localhost:8080/novels. You will get a login pop to enter user credentials. Enter the user, password as user & password, you will see list of novels. You can also post the request using POSTMAN.

    basic

    basic












    basic

    basic
















    basic

    basic


















    References :

    Spring Security Architecture

    Spring Security

    Comments

    Leave a Reply

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











    Share This