Introduction to Spring Security

Spring Security is a powerful and customizable framework used to secure Java applications. It provides authentication, authorization, and protection against common security threats.

Introduction to Spring Security:

Spring Security is a framework that provides:

  • Authentication (Who are you?)
  • Authorization (What are you allowed to do?)
  • Protection against common security threats like CSRF, XSS, and Session Fixation.

Key Features

Secure endpoints with minimal configuration

Support for various authentication methods (DB, LDAP, OAuth2, JWT)

Method-level security (@PreAuthorize, @PostAuthorize)

Built-in password hashing (BCrypt, PBKDF2)

Adding Spring Security to a Spring Boot Project

Spring Boot simplifies security by auto-configuring it when you add the dependency.

Step 1: Add Mavendependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
Step 2: Add controller
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/users")
public class UserController {
@GetMapping("/search")
public String searchUsers(){
return "Success";
}
}

Testing the REST API with Postman:

Once the application is running, test the endpoints:


Default Security Behavior in Spring Boot

When you add spring-boot-starter-security, Spring Boot:

  • Enables Basic AuthenticationThe default username is "user", and the password is randomly generated (logged in the console).
  • Protects all endpointsIf you try to access any URL without authentication, you’ll get a 401 Unauthorized error.
  • Uses Form-based LoginIf you're using a web application, a default login page is provided.

Default Login Credentials Check the generated password in logs:

Testing the REST API with Postman:

Once the application is running, test the endpoints:

Set Basic Auth Username and Password


Understanding SecurityAutoConfiguration

Spring Boot auto-configures security through SecurityAutoConfiguration, which:

  • Creates a default user
  • Enables form login
  • Applies a default security filter chain

How does it work? Spring Boot detects spring-boot-starter-security and applies the default security settings.

🔹 To customize security, you must override the default security configuration.


Disabling Default Security Configurations

If you want to disable security (not recommended in production):

🔹 Method 1: Exclude SecurityAutoConfiguration

Add this to your application.properties file:

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Or exclude it in the main class:

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@SpringBootApplication(exclude = {SecurityAutoConfiguration.class})
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}

🔹 Method 2: Define a Custom Security Configuration

A better approach is to override the default security settings using SecurityFilterChain will explain later topics.

@Configuration
public class SecurityConfig {

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth.anyRequest().permitAll()) // Allow all requests
.csrf(csrf -> csrf.disable()) // Disable CSRF (only for APIs)
.formLogin(login -> login.disable()); // Disable default login

return http.build();
}
}

✅ This will disable the default security but allows you to implement custom authentication.


Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.