Spring Boot Security
M๐ก️ What is Spring Boot Security?
Spring Boot Security (part of Spring Security) is like a security guard for your Spring Boot application. It helps protect your app by:
๐ Requiring login to access certain pages or APIs.
๐ซ Blocking unauthorized access.
๐ Handling authentication (who you are) and authorization (what you're allowed to do).
---
๐ก Why use it?
Imagine you have a blog site:
You want the admin panel to be private.
Only logged-in users should be able to post or edit.
Others can just view posts.
Spring Security makes all that easy without writing everything from scratch.
---
⚙️ How it works (in simple terms):
1. User tries to access a protected page.
2. Spring Security says: “Who are you? Please log in.”
3. Once logged in, it checks: “Are you allowed to see this?”
4. If yes ✅ → access is granted.
5. If no ❌ → access is denied.
---
๐งช Simple Example
Let’s create a tiny Spring Boot app that:
Has one public page
Has one protected page that needs login
---
1. Add dependency in pom.xml:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
---
2. Basic security config (Java-based)
Create a class like this:
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public").permitAll() // No login required
.anyRequest().authenticated() // Everything else needs login
)
.formLogin(); // shows a login form
return http.build();
}
}
---
3. Create 2 controllers
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class MyController {
@GetMapping("/public")
public String publicPage() {
return "This page is public!";
}
@GetMapping("/private")
public String privatePage() {
return "Welcome to the private page! You are logged in.";
}
}
---
4. Default login
When you run the app, Spring Security gives a default login page.
๐ Default user: user
๐ Password: check your console log—it prints it when the app starts.
---
✅ Try it:
Go to: http://localhost:8080/public → You can access without login.
Go to: http://localhost:8080/private → You’ll be asked to log in.
---
๐ Bonus: Custom User & Password
In application.properties:
spring.security.user.name=admin
spring.security.user.password=secret123
---
๐ผ️ Visual Summary
┌──────────────┐
│ /public │◄──── No login needed
└──────────────┘
┌──────────────┐
Login Form │ /private │◄──── Needs login
└──────────────┘
Comments
Post a Comment