Spring Security Basics and Configuration

Jun 28, 2024

Spring Security Lecture Notes

Introduction

  • Objective: Understand Spring Security with respect to theory and practical application
  • Previous Class Recap: Discussed need for application security, importance of authentication and authorization for API endpoints

Spring Security Overview

  • Broad range of Spring projects: Spring Boot, Spring Framework, Spring Security, etc.
  • Key Concepts:
    • All API endpoints must be authenticated
    • Authorization to limit access

Practical Example

  1. Basic Application Development
    • Create endpoints
    • Add Spring Security later for seeing the effect
  2. Setting Up Spring Project
    • Fresh Spring project with necessary dependencies: Web, JPA, MySQL

Spring Security Basics

  • Default Behavior: All endpoints are secure, requiring username and password
  • Dependencies: Add Spring Security dependency in pom.xml
  • Default Authentication: Generated username (user) and password (logged in console)
    • Can customize in application.properties
    • Example: spring.security.user.name=user, spring.security.user.password=user

Customizing Security Configuration

  • Creating a Configuration Class
    • Marked with @Configuration and @EnableWebSecurity
    • Define a security filter chain using SecurityFilterChain bean
         @Bean
         public SecurityFilterChain securityFilterChain(HttpSecurity http) { 
             // security configurations
             return http.build(); 
         }
      
  • URL Management
    • Permit all for some URLs
    • Require authentication for others based on roles
    • Example: http.authorizeRequests().antMatchers("/public/**").permitAll().antMatchers("/admin/**").hasRole("ADMIN");

Storing Users in Database

  • Database Configuration
    • Define User entity
    • Create JPA repository
    • Use CommandLineRunner to preload user data
  • Configuring Password Encoding
    • Use BCryptPasswordEncoder
    • Ensure passwords are stored in encoded format in database
    • Example: passwordEncoder.encode(password)
  • Loading Users from Database
    • Find user by username using JPA repository method
    • Convert database users to Spring Security UserDetails
    • Example: User.withUsername(dbUser.getUsername()).password(dbUser.getPassword()).roles(dbUser.getRoles()).build();

Method Level Security

  • Enabling Method Level Security
    • Add @EnableMethodSecurity annotation in configuration class
    • Use @PreAuthorize on methods to specify role-based access
    • Example: @PreAuthorize("hasRole('ADMIN')")

Practical Considerations

  • Store encrypted passwords
  • Use roles for controlling access to different endpoints
  • Read and follow Spring Security documentation for detailed features

Summary

  • Spring Security is essential for protecting API endpoints
  • Allows customization of security configurations
  • Supports database-backed user authentication and authorization
  • Method level security provides granular control over endpoint access

Additional Features

  • JWT, OAuth2, API keys, and more advanced authentication mechanisms are also supported by Spring Security as per the documentation.