EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials Spring Tutorial Spring Boot Basic Authentication
Secondary Sidebar
Spring Tutorial
  • Spring Boot
    • What is Spring Boot
    • Spring Boot flyway
    • Spring Boot framework
    • Spring Boot Logback
    • Spring Boot actuator endpoints
    • Spring Boot gRPC
    • Spring Boot jdbctemplate example
    • Spring Boot ehcache
    • Spring Boot Architecture
    • Spring Boot Port
    • Introduction of spring boot
    • Spring Boot ide
    • Spring Boot Netty
    • Spring Boot ORM
    • Spring Boot Versions
    • Spring Boot JUnit
    • Spring Boot Keycloak
    • Spring Boot gradle
    • Spring Boot Lombok
    • Spring Boot autowired
    • Spring Boot bean
    • Spring Boot hibernate
    • Spring Boot integration test
    • Spring Boot jdbc
    • Spring Boot MongoDB
    • Spring Boot postgresql
    • Spring Boot rest
    • Spring Boot swagger
    • Spring Boot thymeleaf
    • Spring Boot Unit Test
    • Spring Boot Webflux
    • Spring Boot webclient
    • Spring Boot kubernetes
    • Spring Boot Properties
    • Spring Boot Validation
    • Spring Boot Feature
    • Spring Boot Application
    • Spring Boot email
    • Spring Boot MVC
    • Spring Boot Exception Handling
    • Spring Boot Starter Parent
    • Spring Boot Docker
    • Spring Boot Logging
    • Spring Boot Query
    • Spring Boot Multiple Data Sources
    • Spring Boot Basic Authentication
    • Spring Boot Test
    • Spring Boot jwt
    • Spring Boot Liquibase
    • Spring Boot Prometheus
    • Spring Boot debug
    • Spring Boot GraalVM
    • Spring Boot Batch
    • Spring Boot controller
    • Spring Boot CLI
    • Spring Boot file upload
    • Spring Boot interceptor
    • Spring Boot Service
    • Spring Boot Configuration
    • Spring Boot Datasource Configuration
    • Spring Boot Annotations
    • Spring Boot Starter We
    • Spring Boot Actuator
    • Spring Boot DevTools
    • Spring Boot Repository
    • Spring Boot Dependencies
    • Spring Boot Path Variable
    • Spring Boot Microservices
    • Spring Boot Run Command
    • Spring Boot application.properties
    • Spring Boot Transaction Management
    • Spring Boot Banner
    • Spring Boot JPA
    • Spring Boot Change Port
    • Spring Boot RestTemplate
    • Spring Boot cors
    • Spring Boot HTTPS
    • Spring Boot OAuth2
    • Spring Boot Profiles
    • Spring Boot Interview Questions
    • Spring Boot filter
    • Spring boot logging level
    • Spring Boot Cache
    • Spring Boot Advantages
    • Spring Boot Scheduler
    • Spring Boot Initializr
    • Spring Boot Maven
    • Spring Boot Admin
    • Spring Boot Tomcat
    • Spring Boot WebSocket
    • Spring Boot Executable Jar
    • Spring Boot CommandLineRunner
    • Spring Boot DataSource
    • Spring Batch Scheduler
    • Spring Batch Example
    • Spring Batch Tasklet
    • Spring Batch Admin
    • Spring Batch
    • Spring Boot Qualifier
    • Spring Boot War
    • Spring Boot Test Configuration
  • Spring
    • What is Spring Framework?
    • Spring Architecture
    • What is Spring Integration?
    • IoC Containers
    • What is AOP?
    • Spring Modules
    • Spring Batch Processing
    • Spring Batch Partitioner
    • Spring Batch Job
    • Spring AOP
    • Spring Expression Language
    • Dependency Injection in Spring
    • Spring Batch Architecture
    • Spring framework Interview Questions
  • Spring Cloud Basics
    • What is Spring Cloud
    • Spring Cloud Contract
    • Spring Cloud Components
    • Spring Cloud Version
    • Spring Cloud Data Flow
    • Spring cloud stream
    • Spring Cloud Dependencies
    • Spring cloud microservices
    • spring cloud gateway
    • Spring Cloud Config
    • Spring Cloud Kubernetes
    • Spring Cloud Sleuth

Related Courses

Spring Boot Certification Course

Spring Framework Course Training

All in One Data Science Course

Spring Boot Basic Authentication

Spring Boot Basic Authentication

Definition of Spring Boot Basic Authentication

Spring boot basic authentication is defined as a methodology through which authentication to web services is achieved in the most basic form. In a web service, Spring Boot REST APIs might have different clients who access the same from different locations, and some of these APIs need to provide sensitive and confidential information and in such scenarios, it becomes equally important and makes itself the highest priority to secure the APIs and share the information only to the authorized set of clients. In this article, we will focus on basic authentication, but one must be mindful of other advanced authentication methodologies such as digest authentication, OAuth, and OAuth2 authentication.

Syntax:

The spring boot basic authentication refers to the methodology to secure the space of APIs against any fraudulent attacks that requires user login credentials to be passed as HTTP request header which makes it ideal for authentication REST clients. In this section, we will learn about spring boot basic authentication from the angle of syntax so that while we learn about how basic authentication is performed and its working methodology, mapping back to the syntax will allow readers to look at the complete and bigger picture of the topic in the discussion of the article.

Building JAR file using Maven:

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

mvn clean install

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,754 ratings)

Running JAR file through command line:

java -jar <Name of the JAR file>

How to perform basic authentication in Spring boot?

By now we know that basic authentication is a standardized methodology which is a standard HTTP header where the user and password are encoded in a base64 format and the encoded format is username: password. The reason it is termed as a basic authentication is that the username and password are only and only encoded by using base64 but is neither encrypted nor hashed. Though this makes the application easier and more prone to being compromised, only encoding makes way for many use cases where complex advanced authentication is not required as not much sensitive data is shared and this makes the application easier to build and maintain and obviously scale!

Now in order to understand how to perform basic authentication in spring, there are some pre-requisites that will be required in order to fulfill the task at hand. BasicAuthenticationFilter is the class we use in order to fulfill the required task of processing basic authentication by presenting the credentials into an HTTP header and the result after the authentication back into the SecurityContextHolder. In order to perform basic authentication, we should be mindful of a few things listed below:

• JDK
• Spring Boot
• IDE (preferably eclipse, but one may choose as per the convenience)
• Maven

Now we would need to incorporate the maven dependencies without which building an HTTP authentication is baseless. The first one is spring-boot-starter-parent which takes care of providing useful maven defaults. The dependency management section is provided so that the developer can omit any version tags of dependencies that are existing. The other one is spring-boot-starter-web which takes care of dependencies that are required to build a web app and finally spring-boot-starter-security which takes care of the security portion or in other words the basic authentication (for the purpose of the article). Once the dependencies are loaded, the bean needs to be configured post which the main configuration for spring security needs to be defined. @EnableWebSecurity is the decorator that enables the security service and the developer can extend adapters to override some spring features. Next, we would need to define the authentication entry point. This class makes sure to send responses when the credentials are no longer valid. In case the authorization is successful or non-attempted because of the HTTP header not containing supported request type the flow will continue.

Now that the back-end portion of setting up the authentication layer is complete; we would need to define the controller class where the APIs are exposed. Through the expose of API, one can easily look at the basic authentication at work! But the story is still incomplete as without a log-out implementation the authentication object that contains the credentials, roles, principles, and so on might be at risk of compromise. Hence the clearing of this context is an inevitable step and for this spring provides a SecurityContextLogoutHandler that takes care of the logout task and this is achieved by modifying the SecurityContextHandler.

Once the above pointers are followed in order to perform the basic authentication, we would need to run the application as a java application and let the code written do its job. In order to test, we can use a postman to carry out some GET or POST requests so as to see if the application is performing the required task! In the next section, we will look at a simple example of the implementation of basic authentication.

Examples

Defining the java files:

Syntax:

BasicauthConfig .java
package com.demo.educba.basicauth;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
@Configuration
@EnableWebSecurity
public class BasicauthConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/", "/home").permitAll()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll();
}
@Bean
@Override
public UserDetailsService userDetailsService() {
UserDetails user =
User.withDefaultPasswordEncoder()
.username("eduCBA_premium")
.password("pa55word@")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
WebConfigCustom.java
package com.demo.educba.basicauth;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfigCustom implements WebMvcConfigurer {
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/home").setViewName("home");
registry.addViewController("/").setViewName("home");
registry.addViewController("/hello").setViewName("hello");
registry.addViewController("/login").setViewName("login");
}
}
SecuringWebApplication.java
package com.demo.educba.basicauth;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SecuringWebApplication {
public static void main(String[] args) throws Throwable {
SpringApplication.run(SecuringWebApplication.class, args);
}
}

Output:

Build JAR file using maven and running it:

Home Page

spring 1

Entering the wrong username and password

username

username 1

Entering correct username (eduCBA_premium) and password (pa55word@)

spring authetication

spring authetication 1

Sign out

sign out

Conclusion

To conclude, in this article we have learned the usage of basic authentication using spring boot along with hands-on execution. Next, we encourage readers to try more example hands-on and take it a step forward with advanced authentication.

Recommended Articles

This is a guide to Spring Boot Basic Authentication. Here we discuss definition, syntax, How to perform Spring Boot Basic Authentication? examples with code implementation. You may also have a look at the following articles to learn more –

  1. Spring Boot Actuator
  2. Spring Boot Path Variable
  3. Spring Boot Dependencies
  4. Spring Boot Repository
Popular Course in this category
Spring Boot Training Program (2 Courses, 3 Project)
  2 Online Courses |  3 Hands-on Projects |  22+ Hours |  Verifiable Certificate of Completion
4.5
Price

View Course

Related Courses

Spring Framework Training (4 Courses, 6 Projects)4.9
All in One Data Science Bundle (360+ Courses, 50+ projects)4.8
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more