Spring Boot Basic Authentication step by step implementation

Suresh
Nov 16, 2020

Welcome back friends in this video we will going to talk about Spring Boot Basic.

What is Basic Authentication in Rest API?
This is the easiest and straight forward authentication mechanism in the Rest API Authorization technique. The client sends the credential in the following format
username: password
This credential encrypted using Base64. This is the encoding technique followed in Basic Authentication. The client must encode the above-formated credential using Base64 and send it to Server for authorization. The encrypted format should like below. The encrypted string prefixed with “Basic”
Basic c3VyZXNoOnN1cmVzaA==

Now we will be going to implement Basic authentication in our Spring Boot Application.

Make sure your Spring Boot Application is having the following Artifact in your pom.xml file. It is a spring boot starter Project. This starter project enables Spring Security in your App.

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

Following two key classes required to implement Basic Authentication.

OncePerRequestFilter
WebSecurityConfigurerAdapter
UserDetailsService

I have implemented following two methods in my UserController.java. one is “getUser()” and “getUserWithAuthContext()”. I am planning to protect these two methods using Basic Authorization.

@GetMapping()
public ResponseEntity<String> getUser() {
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
System.out.println("The Logged in User name is " + userDetails.getUsername());
return new ResponseEntity<String>
("This is simple user controller", HttpStatus.OK);
}

@GetMapping("/authcontext")
public ResponseEntity<String> getUserWithAuthContext() {
UserDetails userDetails = (UserDetails)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
return new ResponseEntity<String>
("The current logged in User is " + userDetails.getUsername(), HttpStatus.OK);
}

For further reading please click the below link
Spring Boot Basic Authentication

--

--