{"id":28135750,"url":"https://github.com/hanin-mohamed/spring-security-real-steps","last_synced_at":"2026-04-29T14:07:07.408Z","repository":{"id":284094210,"uuid":"953439344","full_name":"hanin-mohamed/Spring-Security-Real-Steps","owner":"hanin-mohamed","description":"This repository contains my attempts and journey in learning Spring Security in a clear and structured way.","archived":false,"fork":false,"pushed_at":"2025-04-10T21:12:32.000Z","size":1181,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-06-22T06:38:02.582Z","etag":null,"topics":["authentication","authorization","hashing","java","jdbc","jsp","spring-data-jpa","spring-mvc","spring-security","spring-security-jwt"],"latest_commit_sha":null,"homepage":"","language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/hanin-mohamed.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2025-03-23T11:25:15.000Z","updated_at":"2025-05-05T04:41:55.000Z","dependencies_parsed_at":"2025-06-22T06:48:14.081Z","dependency_job_id":null,"html_url":"https://github.com/hanin-mohamed/Spring-Security-Real-Steps","commit_stats":null,"previous_names":["hanin-mohamed/spring-security-real-steps"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/hanin-mohamed/Spring-Security-Real-Steps","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanin-mohamed%2FSpring-Security-Real-Steps","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanin-mohamed%2FSpring-Security-Real-Steps/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanin-mohamed%2FSpring-Security-Real-Steps/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanin-mohamed%2FSpring-Security-Real-Steps/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/hanin-mohamed","download_url":"https://codeload.github.com/hanin-mohamed/Spring-Security-Real-Steps/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/hanin-mohamed%2FSpring-Security-Real-Steps/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32428641,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T13:34:34.882Z","status":"ssl_error","status_checked_at":"2026-04-29T13:34:29.830Z","response_time":110,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["authentication","authorization","hashing","java","jdbc","jsp","spring-data-jpa","spring-mvc","spring-security","spring-security-jwt"],"created_at":"2025-05-14T15:19:49.361Z","updated_at":"2026-04-29T14:07:07.393Z","avatar_url":"https://github.com/hanin-mohamed.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"# 📌My Spring Security Guide\n\n## 🔐 What is Spring Security?\nSpring Security is a powerful framework designed to secure Spring-based applications. It provides mechanisms to control access to app, ensuring that only authorized users can interact with it and perform specific actions. Imagine it as a security guard at the entrance of a building \u0026 verifying identities and deciding who can enter and what they can do inside.\n\n# Spring Security focuses on two primary concepts: \n### 1. Authentication (\"Who Are You?\") \nAuthentication is the process of verifying a user’s identity. It ensures that a user is who they claim to be. For example, when a user logs in with a username and password, the system checks if the credentials are correct—that’s authentication.\n\n📍 What Happens During Authentication?\n\nThe user provides credentials (username/password).\nThe system compares these credentials against stored data (e.g., in a database).\nIf the credentials match → user is authenticated. Else → access is denied.\n\n 🗯️ Authentication is the first line of defense for your app. Without it, anyone could impersonate legitimate users.\n\n### 2. Authorization (\"What Can You Do?\") 🔒\nAuthorization happens after authentication. Once the system confirms the user’s identity, authorization determines what they are allowed to do. For example, can they access a specific page? Can they delete data?\n\n📍 What Happens During Authorization?\n\nThe system checks the user’s role (e.g., “user” or “admin”).\nIt evaluates if the role allows the requested action.\nIf permitted → the action is allowed. Else → the user is blocked.\n\n🗯️ Authorization ensures users can only perform actions they are allowed to. For instance, a regular user shouldn’t access an admin dashboard.\n```\nAuthentication: Showing your ID to enter a concert.\n\nAuthorization: Checking if your ticket grants access to the VIP section or just general seating.\n```\n# 🛠️ Key Components of Spring Security\nSpring Security relies on several components to handle authentication and authorization.\n\n### 1. UserDetails: Representing the User 👤\n\nUserDetails is an interface that represents a user in your app. It provides Spring Security with the user’s information for authentication and authorization.\n\n📍 What Does It Contain?\n\nUsername (e.g., “john.doe”).\nPassword (hashed for security).\nAuthorities (roles like “ROLE_USER” or “ROLE_ADMIN”).\nAccount status (e.g., is the account active or locked?).\n\n🗯️Role in the Process:\n\n- Used during authentication to verify credentials.\n\n- Used during authorization to check the user’s roles.\n\n🗯️ Insight (Interview Question):   What if a user has multiple roles?\n\nUserDetails supports multiple roles through its getAuthorities() method, which returns a list of roles (e.g., “ROLE_USER” and “ROLE_EDITOR”).\n\n### 2. UserDetailsService: Fetching User Data 📚\n\nUserDetailsService is an interface that retrieves user information from a data source (e.g., a database) and returns a UserDetails object.\n\n📍 What Does It Do?\n\nFinds a user by their username using the loadUserByUsername method.\nReturns a UserDetails object with the user’s info.\nThrows a UsernameNotFoundException if the user isn’t found.\nRole in the Process:\n\n-  During authentication, Spring Security uses UserDetailsService to fetch the user’s UserDetails for verification.\n\n🗯️ Insight (Interview Question):   How does UserDetailsService connect to the database? \n\nIt relies on your app’s data access layer (e.g., Spring Data JPA). For example, it might use a repository to query the database, with connection details set in application.properties.\n\n### 3. AuthenticationManager: Managing Authentication \n\nAuthenticationManager is the central component that oversees the authentication process in Spring Security.\n\n📍 What Does It Do?\n\nTakes the user’s credentials (e.g., username and password).\nDelegates verification to an AuthenticationProvider.\nReturns an authenticated object if successful, or throws an error if it fails.\n\n🗯️  Role in the Process:  Initiates authentication when a user tries to log in.\n\n📍 How Does AuthenticationManager Select the Right AuthenticationProvider?\n\nAuthen,,ticationManager (via its default implementation, ProviderManager) maintains a list of AuthenticationProviders.\nIt selects the provider that supports the type of authentication request (e.g., username/password or token-based).\nIf multiple providers exist, it tries them in order until one succeeds or all fail.\n\n🗯️ Insight:  This flexibility allows Spring Security to support various authentication methods (e.g., password login, OAuth, etc.) in the same app.\n\n### 4. AuthenticationProvider: Verifying Credentials \nAuthenticationProvider performs the actual authentication logic by verifying the user’s credentials.\n\n📍 What Does It Do?\n\nUses UserDetailsService to fetch the user’s UserDetails.\nCompares the provided credentials with the stored ones.\nReturns an authenticated object if successful, or throws an error if not.\n\nRole in the Process: Handles the core verification step during authentication.\n\n🗯️ Insight (Interview Question):  What if there are multiple AuthenticationProviders?\n\nAuthenticationManager tries each provider in sequence until one authenticates the user or all fail.\n\n### 5. PasswordEncoder: Securing Passwords 🔒\nPasswordEncoder is an interface that handles password hashing and verification to ensure secure storage.\n\n📍 What Does It Do?\n\nHashes passwords during registration (e.g., using BCrypt).\nVerifies passwords during login by comparing the input with the stored hash.\n\nRole in the Process: Ensures passwords are never stored in plain text, protecting them from unauthorized access.\n\n🗯️ Insight (Interview Question):  Why use BCryptPasswordEncoder? \n\nIt uses the BCrypt algorithm, which is slow (to deter brute-force attacks) and adds a random salt to each password for extra security.\n\n### 6. JwtAuthenticationFilter: Validating Tokens \nJwtAuthenticationFilter is a custom filter that validates JSON Web Tokens (JWTs) for protected endpoints.\n\n📍 What Does It Do?\n\nChecks for a JWT in the Authorization header (e.g., Bearer \u003ctoken\u003e).\nValidates the token (e.g., checks if it’s expired).\nSets up the security context if the token is valid, or blocks the request if it’s not.\n\nRole in the Process:  Ensures only users with a valid JWT can access protected resources.\n\n🗯️ Insight (Interview Question):  What happens if the JWT is invalid?\n\nThe filter rejects the request with a 403 Forbidden error, ideally with a message like “Token expired, please log in again.”\n\n📍 How Does Spring Security Connect to the Database?\n\nSpring Security doesn’t directly connect to the database—it relies on your app’s data access layer. Here’s how it works:\n\n# 🔄 The Authentication Flow:\nThis section outlines a typical authentication flow using Spring Security and JWT.\n\n### 1. Signing Up (Register) \n\nA user submits their info (e.g., username, email, password) to /api/auth/register.\n\n📍 How Does It Work?\nThe password is hashed using PasswordEncoder.\nThe user’s data (with a default role like “ROLE_USER”) is saved to the database.\n\n🗯️ Components Involved: PasswordEncoder for hashing the password.\n \n### 2. Logging In (Authenticate) 🔑\n\nThe user submits their username and password to /api/auth/login.\n\n📍How Does It Work?\n\nAuthenticationManager receives the credentials and selects an AuthenticationProvider.\nAuthenticationProvider uses UserDetailsService to fetch the user’s UserDetails.\nPasswordEncoder verifies the password.\nIf successful, a JWT is generated.\n\n🗯️ Components Involved: AuthenticationManager, AuthenticationProvider, UserDetailsService, UserDetails, PasswordEncoder.\n\n### 3. Generating a JWT Token \n\nA JWT is created and sent to the user after successful login.\n\n📍 How Does It Work?\nThe JWT includes the user’s username, roles, and an expiration time (e.g., 24 hours).\n\n🗯️ Components Involved: UserDetails for roles.\n\n### 4. Accessing Protected Resources (Authorization) \nThe user requests a protected endpoint (e.g., /api/home) with their JWT.\n\n📍 How Does It Work?\n\nJwtAuthenticationFilter validates the JWT.\nIf valid, the security context is set up with the user’s roles.\nSpring Security checks if the user’s roles allow access to the endpoint.\nAccess is granted or denied accordingly.\n\n🗯️ Components Involved: JwtAuthenticationFilter, UserDetails.\n\n# The Full Flow \n\nSignup: User submits data → Password hashed → Saved to database.\n\nLogin: Credentials submitted → AuthenticationManager verifies → JWT generated.\n\nAccess Resource: JWT sent → JwtAuthenticationFilter validates → Access granted/denied.\n\n![Full Authentication Flow](https://github.com/hanin-mohamed/Spring-Security-Real-Steps/raw/main/screens/authentication-flow.png)","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhanin-mohamed%2Fspring-security-real-steps","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fhanin-mohamed%2Fspring-security-real-steps","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fhanin-mohamed%2Fspring-security-real-steps/lists"}