• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Spring Boot Security Basic Authentication – Secure REST API

January 9, 2019 by javainterviewpoint Leave a Comment

In this post, we will learn how to secure REST API using Spring Boot Security Basic Authentication. With the security in place our application will be providing the data to the user who is authenticated through Basic Authentication.

In order to access a secured resource the user has to provide the request to our API with the header information containing the username and password to access the resource.

Folder Structure:

Spring Boot Security Basic Authentication

  1. Create a Maven project (maven-archetype-quickstart) “SpringBootBasicAuth” and create a package for our source files “com.javainterviewpoint” under  src/main/java 
  2. Now add the following dependency in the 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.javainterviewpoint</groupId>
    	<artifactId>SpringBootBasicAuth</artifactId>
    	<version>0.0.1-SNAPSHOT</version>
    	<packaging>jar</packaging>
    
    	<name>SpringBootBasicAuth</name>
    	<url>http://maven.apache.org</url>
    
    	<properties>
    		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    		<java.version>1.8</java.version>
    	</properties>
    
    	<parent>
    		<groupId>org.springframework.boot</groupId>
    		<artifactId>spring-boot-starter-parent</artifactId>
    		<version>2.0.7.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-security</artifactId>
    		</dependency>
    
    		<dependency>
    			<groupId>org.hibernate</groupId>
    			<artifactId>hibernate-validator</artifactId>
    			<version>5.2.4.Final</version>
    		</dependency>
    	</dependencies>
    
    </project>
  3. Create the Java classes Application.java, HelloController.java and SpringSecurityConfig.java under com.javainterviewpoint folder.

The spring-boot-starter-parent is a special starter, it provides useful Maven defaults. Since we are developing a web application, we also need to add spring-boot-starter-web dependency.This will add dependencies such Tomcat, Jackson, Spring boot etc which are required for our application. spring-boot-starter-security dependency adds all the security related dependencies.

Other interesting articles which you may like …

  • Spring Boot @ConfigurationProperties Example
  • Spring Boot auto-configuration @SpringBootApplication
  • Spring Boot Thymeleaf Example
  • Spring Boot JPA Tutorial
  • Spring Boot Tomcat JDBC Connection Pool
  • Spring Boot Logging – Logback
  • Spring Boot Log4j2 Example
  • Spring Boot HikariCP Connection Pool
  • Spring Boot JDBC Connection Pool
  • Spring Boot RESTful Web Services Example
  • Spring Boot Kotlin RESTful Web Services
  • Spring Boot with Kotlin Hello World Example
  • Spring Boot Hello World Example with Maven
  • Spring Boot Hello World Example in Eclipse
  • How to Create Deployable WAR | Spring Boot | SpringBootServletInitializer
  • Spring Boot Change Embedded Tomcat default port
  • Spring Boot CRUDRepository Example- Spring Data JPA
  • Fix missing src/main/java folder in Eclipse Maven Project
  • Spring MVC CRUD Example with MySql + JdbcTemplate
  • RESTful Java Client With Jersey Client
  • RESTEasy Hello World Example with Apache Tomcat
  • RESTful Java client with RESTEasy client
  • Spring RESTful Web Services Hello World XML Example
  • Springfox Swagger 2 for Spring RESTful Web Services

Spring Boot Security Basic Authentication – Secure REST API

Dependency Tree

[INFO] ------------------------------------------------------------------------
[INFO] Building SpringBootBasicAuth 0.0.1-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] 
[INFO] --- maven-dependency-plugin:3.0.2:tree (default-cli) @ SpringBootBasicAuth ---
[INFO] com.javainterviewpoint:SpringBootBasicAuth:jar:0.0.1-SNAPSHOT
[INFO] +- org.springframework.boot:spring-boot-starter-web:jar:2.0.7.RELEASE:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter:jar:2.0.7.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot:jar:2.0.7.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-autoconfigure:jar:2.0.7.RELEASE:compile
[INFO] |  |  +- org.springframework.boot:spring-boot-starter-logging:jar:2.0.7.RELEASE:compile
[INFO] |  |  |  +- ch.qos.logback:logback-classic:jar:1.2.3:compile
[INFO] |  |  |  |  +- ch.qos.logback:logback-core:jar:1.2.3:compile
[INFO] |  |  |  |  \- org.slf4j:slf4j-api:jar:1.7.25:compile
[INFO] |  |  |  +- org.apache.logging.log4j:log4j-to-slf4j:jar:2.10.0:compile
[INFO] |  |  |  |  \- org.apache.logging.log4j:log4j-api:jar:2.10.0:compile
[INFO] |  |  |  \- org.slf4j:jul-to-slf4j:jar:1.7.25:compile
[INFO] |  |  +- javax.annotation:javax.annotation-api:jar:1.3.2:compile
[INFO] |  |  +- org.springframework:spring-core:jar:5.0.11.RELEASE:compile
[INFO] |  |  |  \- org.springframework:spring-jcl:jar:5.0.11.RELEASE:compile
[INFO] |  |  \- org.yaml:snakeyaml:jar:1.19:runtime
[INFO] |  +- org.springframework.boot:spring-boot-starter-json:jar:2.0.7.RELEASE:compile
[INFO] |  |  +- com.fasterxml.jackson.core:jackson-databind:jar:2.9.7:compile
[INFO] |  |  |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO] |  |  |  \- com.fasterxml.jackson.core:jackson-core:jar:2.9.7:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jdk8:jar:2.9.7:compile
[INFO] |  |  +- com.fasterxml.jackson.datatype:jackson-datatype-jsr310:jar:2.9.7:compile
[INFO] |  |  \- com.fasterxml.jackson.module:jackson-module-parameter-names:jar:2.9.7:compile
[INFO] |  +- org.springframework.boot:spring-boot-starter-tomcat:jar:2.0.7.RELEASE:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-core:jar:8.5.35:compile
[INFO] |  |  +- org.apache.tomcat.embed:tomcat-embed-el:jar:8.5.35:compile
[INFO] |  |  \- org.apache.tomcat.embed:tomcat-embed-websocket:jar:8.5.35:compile
[INFO] |  +- org.hibernate.validator:hibernate-validator:jar:6.0.13.Final:compile
[INFO] |  +- org.springframework:spring-web:jar:5.0.11.RELEASE:compile
[INFO] |  |  \- org.springframework:spring-beans:jar:5.0.11.RELEASE:compile
[INFO] |  \- org.springframework:spring-webmvc:jar:5.0.11.RELEASE:compile
[INFO] |     +- org.springframework:spring-context:jar:5.0.11.RELEASE:compile
[INFO] |     \- org.springframework:spring-expression:jar:5.0.11.RELEASE:compile
[INFO] +- org.springframework.boot:spring-boot-starter-security:jar:2.0.7.RELEASE:compile
[INFO] |  +- org.springframework:spring-aop:jar:5.0.11.RELEASE:compile
[INFO] |  +- org.springframework.security:spring-security-config:jar:5.0.10.RELEASE:compile
[INFO] |  |  \- org.springframework.security:spring-security-core:jar:5.0.10.RELEASE:compile
[INFO] |  \- org.springframework.security:spring-security-web:jar:5.0.10.RELEASE:compile
[INFO] \- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile
[INFO]    +- javax.validation:validation-api:jar:2.0.1.Final:compile
[INFO]    +- org.jboss.logging:jboss-logging:jar:3.3.2.Final:compile
[INFO]    \- com.fasterxml:classmate:jar:1.3.4:compile
[INFO] ------------------------------------------------------------------------

Spring Boot Security Configuration

package com.javainterviewpoint;

import org.springframework.beans.factory.annotation.Autowired;
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.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
@EnableWebSecurity
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
        http.httpBasic().and().authorizeRequests()
        .antMatchers("/user").hasRole("USER")
        .antMatchers("/admin").hasRole("ADMIN")
        .and()
        .csrf().disable();
    }
  
    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception
    {
        auth.inMemoryAuthentication()
        .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
        .and()
        .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}
  • @EnableWebSecurity annotation enables spring security configuration which is defined in WebSecurityConfigurerAdapter
  • We have extended WebSecurityConfigurerAdapter, which allows us to override spring’s security default feature. In our example we want all the requests to be authenticated using HTTP Basic authentication.
  • configure() method configures the HttpSecurity class which authorizes each HTTP request which has been made. In our example ‘/user’ should be allowed for the user with USER role  and ‘/admin’ should be allowed for the user with USER (or) ADMIN role.
    • .httpBasic() –> Tells spring to use the HTTP Basic Authentication method to authenticate the user
    • authorizeRequests() .antMatchers(“/user”).hasRole(“USER”) .antMatchers(“/admin”).hasRole(“ADMIN”) –> All requests to the endpoint must be authorized or else they should be rejected.
    • .csrf().disable() –> Disables CSRF protection
@Override
protected void configure(HttpSecurity http) throws Exception
{
   http.httpBasic()
      .and().authorizeRequests()
    .antMatchers("/user").hasRole("USER")
    .antMatchers("/admin").hasRole("ADMIN")
        .and()
    .csrf().disable();
    }
  • configureGlobal() method configures the AuthenticationManagerBuilder class with the valid user credentials and the allowed roles. The AuthenticationManagerBuilder class creates the AuthenticationManger which is responsible for authenticating the credentials. In our example we have used the inMemoryAuthentication, you can choose other authentication types such JDBC, LDAP.
  • In Spring Boot 2, we need to pass the encoded password to the password() method, since we have used BCryptPasswordEncoder we are directly encoding the password using encode() method.
@Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth)
            throws Exception
    {
      auth.inMemoryAuthentication()
        .withUser("user").password(passwordEncoder().encode("password")).roles("USER")
          .and()
        .withUser("admin").password(passwordEncoder().encode("password")).roles("USER", "ADMIN");
    }
  • We have registered our passwordEncoder as BCryptPasswordEncoder
   @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

Whenever we have not mapped any PasswordEncoder then SpringBoot will throw the “There is no PasswordEncoder mapped for the id \”null\” error

{
    "timestamp": "2019-01-08T17:03:44.813+0000",
    "status": 500,
    "error": "Internal Server Error",
    "message": "There is no PasswordEncoder mapped for the id \"null\"",
    "path": "/user"
}

HelloController.java

package com.javainterviewpoint;

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

@RestController
public class HelloController
{
    @RequestMapping("/user")
    public String welcomeUser()
    {
        return "User has successfully logged in!!!";

    }

    @RequestMapping("/admin")
    public String welcomeAdmin()
    {
        return "Admin has successfully logged in!!!";
    }
}
  • We have annotated our “HelloController” class with @RestController, @RestController annotation is introduced in Spring 4 it is a combination of @Controller + @ResponseBody. So when using @RestController, you do not need to use @ResponseBody it is optional now
  • We have two methods
    • welcomeUser() –> This method will be called when the request is /user
    • welcomeAdmin() –> This method will be called when the request is /admin

Application.java

package com.javainterviewpoint;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;
import org.springframework.context.annotation.ComponentScan;

@ComponentScan(basePackages = "com.javainterviewpoint")
@SpringBootApplication
public class Application extends SpringBootServletInitializer
{
    public static void main(String[] args)
    {
        SpringApplication.run(Application.class, args);
    }
}

The Application class main() method is the triggering point of our application, it in-turn calls Spring Boot’s SpringApplication class run() method which bootstrap our Application and starts the tomcat server. We need to pass our Applicaion.class as an argument to our run() method.

Output

In POSTMAN,  select GET method and give the url as “http://localhost:8080/user”. In the Authorization tab select the Type as “Basic Auth” and key in the invalid username /password. You will be getting 401 Unauthorized error

Spring Boot Security Basic Authentication 2

Now pass the valid username and password [user/password (or) admin/password]

Spring Boot Security Basic Authentication 1

    Download Source Code

Filed Under: Java, Spring, Spring Boot, Spring Security Tagged With: Basic Authentication, BCryptPasswordEncoder, Secure REST API, Spring Boot, Spring Boot 2, Spring Boot Security, Spring Boot Security Basic Authentication

Leave a Reply Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·