Basic Authentication setup code for Spring Boot, focusing only on implementing Basic Authentication without additional features:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
Create the following packages:
org.niteshsynergy.security
(For Security Configuration)org.niteshsynergy.controller
(For Controller)SecurityConfig
in the package org.niteshsynergy.security
.Add the following code:
SecurityConfig.java
:
package org.niteshsynergy.security;
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.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.csrf().disable() // Disable CSRF for simplicity.
.authorizeRequests()
.anyRequest().authenticated() // Require authentication for all endpoints.
.and()
.httpBasic(); // Enable Basic Authentication.
return http.build();
}
}
application.properties
file located in src/main/resources
.Add the username, password, and role:
application.properties
:
spring.security.user.name=admin
spring.security.user.password=password
spring.security.user.roles=USER
HelloController
in the package org.niteshsynergy.controller
.Add the following code:
HelloController.java
:
package org.niteshsynergy.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, Authenticated User!";
}
}
Run
button in IntelliJ IDEA or from the main
method in the Spring Boot application class.http://localhost:8080/hello
http://localhost:8080/hello
.admin
password
.
Response:
Hello, Authenticated User! ser!
Note: Even if your not adding 3. Write the Security Configuration code then also username & password will ask while calling hello api.