Back to Spring Boot Course

Spring Boot Course

screenshot of the app

Basic authentication is a simple authentication scheme built into the HTTP protocol.

The client sends HTTP requests with the Authorization header that contains the word Basic word followed by a space and a base64-encoded string username:password.

For Basic Authentication, we need to code the below and then restart the app

package com.praveen.employee.config; 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.web.SecurityFilterChain; import static org.springframework.security.config.Customizer.withDefaults; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(authorizeRequests -> authorizeRequests .requestMatchers("/") .permitAll() .anyRequest() .authenticated() ) .httpBasic(withDefaults()); return http.build(); } }

Let's invoke the endpoint URL http://localhost:8080/api/v1/employees in postman, you will see 401 unauthorized exception

screenshot of the app

Now, let's pass the user credentials that we configured in the application.yml file under the 'Auth' tab using Basic Auth in Postman and , and you will be able to access the endpoint successfully now.

spring: application: name: emp-mgmt-service security: user: name: praveen password: m13~Tj,finAZ

screenshot of the app