Spring Security


🧠 What Is Spring Security?

👉 Spring Security is a powerful authentication and authorization framework that comes as part of the Spring ecosystem.
It helps protect your Java and Spring Boot applications from unauthorized access, by managing:

  • Who can access your app (Authentication ✅)
  • What they can do once logged in (Authorization 🔒)

⚙️ Why We Need Spring Security

Without security:

  • Anyone can call your APIs
  • No protection against attackers
  • No control over user access

With Spring Security, you get:

  • Login/logout mechanisms
  • Role-based access control
  • Token-based authentication (JWT, OAuth2)
  • Protection from common attacks (CSRF, XSS, Clickjacking)

🔑 Two Core Concepts

1️⃣ Authentication

“Who are you?”

It verifies the identity of a user.
Example: username + password login, JWT token, OAuth2.

Authentication auth = authenticationManager.authenticate(
    new UsernamePasswordAuthenticationToken(username, password)
);

2️⃣ Authorization

“What can you do?”

It checks whether an authenticated user has permission to perform an action.

Example:

@PreAuthorize("hasRole('ADMIN')")
public String getAllUsers() { ... }

🧩 How Spring Security Works (Flow)

  1. You make a request (e.g. GET /api/data)
  2. The Security Filter Chain intercepts it
  3. If you’re not authenticated → it blocks or redirects you
  4. If authenticated → it checks your roles/permissions
  5. If authorized → the controller executes

🔒 Example

Default Behavior

If you add spring-boot-starter-security to your project and run it:

  • Every endpoint becomes secured by default
  • Spring creates a default user with a generated password in logs
  • You can log in at /login

That’s how Spring Security ensures “secure by default”.


🧱 Common Use Cases

ScenarioSpring Security Feature
Login formUsernamePasswordAuthenticationFilter
JWT Token AuthenticationCustom Filter + Stateless Security
OAuth2 Login (Google, GitHub)spring-boot-starter-oauth2-client
Method-level security@PreAuthorize, @Secured
Protect REST APIsStateless Authentication with JWT

🔐 Example Configuration

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated()
            )
            .formLogin(Customizer.withDefaults());
        return http.build();
    }
}

/public/** → accessible to all
🔒 all others → require authentication


🧠 In Short

ConceptMeaning
AuthenticationVerifying identity
AuthorizationGranting access based on roles
Filter ChainIntercepts every request
Security ContextStores authenticated user details
Stateless AuthCommon for REST APIs using JWT

🚀 Why Developers Use It

  • Works seamlessly with Spring Boot
  • Highly customizable
  • Integrates with databases, LDAP, JWT, OAuth2
  • Enterprise-grade security with minimal setup

Read other awesome articles in Medium.com or in akcoding’s posts.

OR

Join us on YouTube Channel

OR Scan the QR Code to Directly open the Channel 👉

AK Coding YouTube Channel

Share with