Dung (Donny) Nguyen

Senior Software Engineer

Authentication & Authorization

Two words that sound alike, get used interchangeably, and mean completely different things. Getting them straight is the foundation of every secure application.

You always authenticate first, then authorize. A user proves they are alice, and only then does the system decide whether alice can delete an order.


Authentication: Proving Identity

Authentication is the act of confirming that a request comes from who it claims to come from. The common approaches:


Authorization: Granting Access

Once identity is established, authorization decides what the authenticated principal may access. The main models:


How They Work Together in Spring Boot

Spring Security wires both concerns into a single filter chain. A typical stateless JWT setup looks like this:

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .sessionManagement(session ->
                session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .authorizeHttpRequests(auth -> auth
                // Public endpoints — no authentication required
                .requestMatchers("/api/auth/**", "/api/public/**").permitAll()
                // Authorization by role
                .requestMatchers("/api/admin/**").hasRole("ADMIN")
                .requestMatchers(HttpMethod.DELETE, "/api/**").hasRole("ADMIN")
                // Everything else — authentication required
                .anyRequest().authenticated()
            )
            .addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);

        return http.build();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }
}

Method-Level Authorization

Beyond URL rules, you can secure individual methods with annotations:

@Service
public class OrderService {

    // Only admins can call this
    @PreAuthorize("hasRole('ADMIN')")
    public void deleteOrder(Long orderId) {
        // ...
    }

    // A user can only read their own orders
    @PreAuthorize("#userId == authentication.principal.id or hasRole('ADMIN')")
    public List<Order> getOrders(Long userId) {
        // ...
    }
}

A Typical Login Flow (JWT)

  1. The client sends credentials to POST /api/auth/login.
  2. The server authenticates them against the stored (hashed) password.
  3. On success, the server signs and returns a JWT containing the user’s identity and roles.
  4. The client stores the token and attaches it to every request: Authorization: Bearer <token>.
  5. On each request, a filter validates the token’s signature and expiry — this re-establishes authentication without a database hit.
  6. Spring Security then checks the user’s roles against the endpoint’s rules — this is authorization.

Best Practices


Summary

  Authentication Authorization
Question Who are you? What can you do?
Purpose Verify identity Verify permissions
Happens First After authentication
Example Logging in with a password Checking if you have the ADMIN role
Data used Credentials, tokens, biometrics Roles, permissions, attributes

Get authentication right and you know who is knocking. Get authorization right and you control what they can touch. Both together are the backbone of application security.