Authorization

Back

Loading concept...

🏰 The Castle Gatekeeper: Spring Security Authorization

Imagine your application is a magnificent castle. Anyone can walk up to the gate, but only special people can enter specific rooms. That’s what Authorization does!


🎭 The Big Picture: What is Authorization?

Think of a school building:

  • Authentication = The guard checking your student ID at the entrance
  • Authorization = The rules saying which classrooms YOU can enter
You proved WHO you are βœ… (Authentication)
Now we check WHAT you can do βœ… (Authorization)

Real Life Example

🏫 School Building
β”œβ”€β”€ πŸ“š Library β†’ All students allowed
β”œβ”€β”€ πŸ”¬ Science Lab β†’ Only science students
β”œβ”€β”€ 🏒 Staff Room β†’ Only teachers
└── πŸ” Principal Office β†’ Only principal

πŸ›‘οΈ Authorization Concepts

Authorization answers ONE simple question:

β€œIs THIS person allowed to do THAT thing?”

The Three Key Players

graph TD A["πŸ‘€ User/Principal"] --> B{🎭 Has Role?} B -->|Yes| C["βœ… Access Granted"] B -->|No| D["❌ Access Denied"]
Term Simple Meaning Example
Principal The logged-in user β€œJohn”
Authority Permission badge β€œCAN_READ_REPORTS”
Role Job title (group of permissions) β€œADMIN”, β€œUSER”

Code Example: Basic Setup

// User has ROLE_ADMIN
// Can access /admin/** pages

http
  .authorizeHttpRequests()
  .requestMatchers("/admin/**")
  .hasRole("ADMIN");

πŸ›‘ CSRF Protection: The Secret Handshake

What is CSRF?

Imagine someone tricks you into clicking a button that transfers YOUR money to THEIR account. Scary, right?

CSRF = Cross-Site Request Forgery A bad guy makes YOUR browser do bad things without YOU knowing

The Token Solution

graph TD A["πŸ–₯️ Server"] -->|Gives Secret Token| B["πŸ“ Your Form"] B -->|Sends Token Back| C["πŸ” Server Checks"] C -->|Token Matches?| D["βœ… Real Request!"] C -->|No Token?| E["❌ Fake Request!"]

How Spring Helps

// CSRF is ON by default! πŸŽ‰
// Spring adds hidden token to all forms

// Your HTML form gets this automatically:
// <input type="hidden"
//        name="_csrf"
//        value="abc123-secret-token"/>

When to Disable (Rare!)

// Only for REST APIs with JWT tokens
http.csrf().disable();

// WHY? JWT tokens already prevent CSRF
// They're sent in headers, not cookies

πŸͺ Session Management: Remember Me!

What is a Session?

When you log in, the server gives you a visitor badge (session). You show this badge with every request so you don’t have to log in again.

Session Flow

graph TD A["πŸ” Login Success"] --> B["🎫 Get Session ID"] B --> C["πŸͺ Stored in Cookie"] C --> D["πŸ“€ Sent with Every Request"] D --> E["πŸ” Server Recognizes You"]

Spring Session Controls

http.sessionManagement()
    // One login at a time
    .maximumSessions(1)

    // Kick out old session when new login
    .maxSessionsPreventsLogin(false)

    // Session timeout
    .invalidSessionUrl("/login?expired")

    // Create new session after login (security!)
    .sessionFixation().newSession();

Session Settings Explained

Setting What It Does Example
maximumSessions(1) Only 1 device login Can’t login from phone if laptop is active
newSession() Fresh session after login Prevents session hijacking
invalidSessionUrl() Where to go when session dies Redirect to login page

🏷️ Method Security Annotations

The Magic Decorators

Instead of configuring everything in one place, you can protect methods directly!

// First, enable it!
@EnableMethodSecurity
public class SecurityConfig { }

The Three Musketeers πŸ—‘οΈ

1. @PreAuthorize - Check BEFORE running

@PreAuthorize("hasRole('ADMIN')")
public void deleteUser(Long id) {
    // Only admins can delete users
}

2. @PostAuthorize - Check AFTER running

@PostAuthorize("returnObject.owner == principal.username")
public Document getDocument(Long id) {
    // You can only see YOUR documents
    return documentRepo.findById(id);
}

3. @Secured - Simple role check

@Secured("ROLE_MANAGER")
public void approveExpense() {
    // Only managers can approve
}

Quick Reference Table

Annotation When Example Use
@PreAuthorize Before method β€œCan this user even try?”
@PostAuthorize After method β€œCan user see the result?”
@Secured Before (simple) Quick role check

πŸ“œ Authorization Rules

Building Your Security Castle

@Bean
public SecurityFilterChain filterChain(
    HttpSecurity http) throws Exception {

    http.authorizeHttpRequests(auth -> auth
        // 🌍 Public pages (everyone)
        .requestMatchers("/", "/home").permitAll()

        // πŸ‘€ User pages (logged in users)
        .requestMatchers("/profile/**").authenticated()

        // πŸ‘‘ Admin pages (admins only)
        .requestMatchers("/admin/**").hasRole("ADMIN")

        // πŸ”§ API endpoints (specific permission)
        .requestMatchers("/api/reports/**")
            .hasAuthority("VIEW_REPORTS")

        // 🚫 Everything else needs login
        .anyRequest().authenticated()
    );

    return http.build();
}

Rule Priority = ORDER MATTERS! ⚠️

Rules are checked TOP to BOTTOM
First match wins!

βœ… Good Order:
/admin/secret β†’ ADMIN only
/admin/**    β†’ MANAGER or ADMIN
/**          β†’ authenticated

❌ Bad Order:
/**          β†’ authenticated (catches everything!)
/admin/**    β†’ never reached 😱

Common Matchers

Method Meaning
permitAll() Anyone (even strangers)
authenticated() Must be logged in
hasRole("X") Must have ROLE_X
hasAuthority("X") Must have exact permission X
hasAnyRole("A","B") Must have A OR B
denyAll() Nobody (block everything)

πŸ”‘ OAuth2 and JWT Basics

The VIP Pass System

OAuth2 = A way to let users login using Google, Facebook, etc. JWT = A special encoded ticket that contains user info

OAuth2: Login with Others

graph LR A["πŸ‘€ User"] -->|Click 'Login with Google'| B["πŸ”΅ Google"] B -->|Who are you? Password?| A A -->|My Google password| B B -->|Here's proof token| C[🏠 Your App] C -->|Token valid? User info please| B B -->|Yes! Here's email, name| C C -->|Welcome!| A

JWT: The Magic Ticket 🎟️

JWT = Three parts separated by dots

Header.Payload.Signature

eyJhbGc.eyJzdWI.SflKxw
   |         |        |
   |         |        └── πŸ” Signature (proof it's real)
   |         └── πŸ“¦ Payload (user info, expiry)
   └── πŸ“‹ Header (token type, algorithm)

JWT Contains:

{
  "sub": "john@email.com",
  "roles": ["USER", "ADMIN"],
  "exp": 1699999999
}

Spring OAuth2 + JWT Setup

// application.yml
spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-google-id
            client-secret: your-secret
// Security Config for JWT
http
  .oauth2Login()  // Enable Google/FB login
  .and()
  .oauth2ResourceServer()
  .jwt();  // Accept JWT tokens

OAuth2 vs JWT: When to Use?

Feature OAuth2 JWT
Purpose β€œLogin with X” Stateless auth token
Session Yes (usually) No (token has all info)
Best For User-facing apps REST APIs
Example β€œLogin with Google” Mobile app β†’ API

πŸŽ“ Putting It All Together

graph TD A["πŸšͺ Request Arrives"] --> B{πŸ” Authenticated?} B -->|No| C["πŸ“ Login Page"] B -->|Yes| D{🎫 CSRF Valid?} D -->|No| E["❌ Forbidden"] D -->|Yes| F{πŸ“œ Authorized?} F -->|No| G["❌ 403 Access Denied"] F -->|Yes| H["βœ… Process Request"]

Real App Example

@Configuration
@EnableMethodSecurity
public class SecurityConfig {

  @Bean
  SecurityFilterChain security(HttpSecurity http)
      throws Exception {
    return http
      // Session: one device only
      .sessionManagement(s -> s.maximumSessions(1))

      // CSRF: enabled for web, disabled for API
      .csrf(c -> c.ignoringRequestMatchers("/api/**"))

      // Rules
      .authorizeHttpRequests(a -> a
        .requestMatchers("/public/**").permitAll()
        .requestMatchers("/api/**").authenticated()
        .requestMatchers("/admin/**").hasRole("ADMIN")
      )

      // OAuth2 login
      .oauth2Login(Customizer.withDefaults())

      .build();
  }
}

🌟 Key Takeaways

Concept One-Line Summary
Authorization Checking WHAT you can do after knowing WHO you are
CSRF Secret token prevents fake requests
Session Your visitor badge that remembers you
@PreAuthorize Guard before method runs
Authorization Rules URL β†’ Permission mapping
OAuth2 Login with Google/Facebook/etc.
JWT Encoded ticket with user info inside

πŸ’‘ Remember: Authentication says β€œI know who you are.” Authorization says β€œHere’s what you’re allowed to do.”

You’ve just learned how to be the gatekeeper of your Spring castle! 🏰

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.