The Programmer's Guide
  • About
  • Algorithm
    • Big O Notation
      • Tree
      • Problems
    • Basic Notes
    • Data Structure Implementation
      • Custom LinkedList
      • Custom Stack
      • Custom Queue
      • Custom Tree
        • Binary Tree Implementation
        • Binary Search Tree Implementation
        • Min Heap Implementation
        • Max Heap Implementation
        • Trie Implementation
      • Custom Graph
        • Adjacency List
        • Adjacency Matrix
        • Edge List
        • Bidirectional Search
    • Mathematical Algorithms
      • Problems - Set 1
      • Problems - Set 2
    • Bit Manipulation
      • Representation
      • Truth Tables
      • Number System
        • Java Program
      • Problems - Set 1
    • Searching
    • Sorting
    • Array Algorithms
    • String Algorithms
    • Tree
      • Tree Traversal Techniques
      • Tree Implementation
      • Applications of Trees
      • Problems - Set 1
    • Graph
      • Graph Traversal Techniques
      • Shortest Path Algorithms
      • Minimum Spanning Tree (MST) Algorithms
    • Dynamic Programming
      • Problems - Set 1
    • Recursion
    • Parallel Programming
    • Miscellaneous
      • Problems - Set 1
  • API
    • API Basics
      • What is an API?
      • Types of API
        • Comparison - TBU
      • Synchronous vs Asynchronous API
    • API Architecture
      • Synchronous & Asynchronous Communication
    • API Specification
  • Cloud Computing
    • Cloud Fundamentals
      • Cloud Terminology
      • Core Terminology
      • Cloud Models
      • Cloud Service Models
      • Benefits, Challenges and Risk of Cloud Computing
      • Cloud Ecosystem
  • Database
    • DBMS
      • Types of DBMS
        • Relational DBMS (RDBMS)
        • NoSQL DBMS
        • Object-Oriented DBMS (OODBMS)
        • Columnar DBMS
        • In-Memory DBMS
        • Distributed DBMS
        • Cloud-Based DBMS
        • Hierarchical DBMS
      • DBMS Architecture
      • DBMS Structure
    • SQL Databases
      • Terminology
      • RDBMS Concepts
        • Entity Relationship Diagram (ERD)
          • ERD Examples
        • Normalization
        • Denormalization
        • ACID & BASE Properties
          • ACID Properties
          • BASE Properties
        • Locking and Unlocking
      • SQL Fundamentals
        • SQL Commands
          • DDL (Data Definition Language)
          • DML (Data Manipulation Language)
          • DCL (Data Control Language)
          • TCL (Transaction Control Language)
          • DQL (Data Query Language)
        • SQL Operators
          • INTERSECT
          • EXCEPT
          • MINUS
          • IN and NOT IN
          • EXISTS and NOT EXISTS
        • SQL Clauses
          • Joins
          • OVER
          • WITH
          • CONNECT BY
          • MODEL
          • FETCH FIRST
          • KEEP
          • OFFSET with FETCH
        • SQL Functions
          • Oracle Specific
        • SQL Data Types
          • Numeric Types
          • Character Types
          • Date & Time Types
          • Large Object Types
        • Others
          • Indexing
      • Vendor Specific Concepts
        • Oracle Specific
          • Data Types
          • Character Set
          • Rownum, Rowid, Urowid
          • Order of Execution of the query
          • Keys
          • Tablespace
          • Partition
      • Best Practice
      • Resources & References
        • O’Reilly SQL Cookbook (2nd Edition)
          • 1. Retrieving Records
          • 2. Sorting Query Results
          • 3. Working with Multiple Tables
          • 4. Inserting, Updating, and Deleting
          • 5. Metadata Queries
          • 6. Working with Strings
          • 7. Working with Numbers
          • 8. Date Arithmetic
          • 9. Date Manipulation
          • 10. Working with Ranges
          • 11. Advanced Searching
          • 12. Reporting and Reshaping
          • 13. Hierarchical Queries
          • 14. Odds 'n' Ends
    • SQL vs NoSQL
    • Best Practices
  • Git
    • Commands
      • Setup and Configuration Commands
      • Getting and Creating Projects
      • Tracking Changes
      • Branching and Merging
      • Sharing and Updating Projects
      • Inspection and Comparison
      • Debugging
      • Patching
      • Stashing and Cleaning
      • Advanced Manipulations
    • Workflows
      • Branching Strategies
        • Git Flow
        • Trunk-Based Development
        • GitHub Flow
        • Comparison
      • Merge Strategies
        • Merge
        • Rebase
        • Squash
        • Fast-forward vs No-fast-forward
        • MR vs PR
      • Conflict Resolution
        • Handling Merge Conflicts
        • Merge Conflicts
        • Rebase Conflicts
        • Divergent Branches After git pull
        • Force Push
      • Patch & Recovery
        • Cherry-pick strategies
        • Revert vs Reset
        • Recover from a bad rebase
      • Rebasing Practices
        • Merge vs Rebase
        • Rebase develop branch on main branch
      • Repository Management
        • Working Directory
        • Mirror a repository
        • Convert a local folder to a Git repo
        • Backup and restore a Git repository
  • Java
    • Java Installation
    • Java Distributions
    • Java Platform Editions
      • Java SE
      • Java EE
      • Jakarta EE
      • Java ME
      • JavaFX
    • Java Overview
      • OOP Principles
        • Encapsulation
        • Inheritance
        • Polymorphism
        • Abstraction
          • Abstract Class & Method
          • Interface
            • Functional Interfaces
            • Marker Interfaces
          • Abstract Class vs Interface
      • OOP Basics
        • What is a Class?
          • Types of Classes
        • What is an Object?
          • Equals and HashCode
            • FAQ
          • Shallow Copy and Deep Copy
          • Ways to Create Object
          • Serialization & Deserialization
        • Methods & Fields
          • Method Overriding & Overloading
          • Method Signature & Header
          • Variables
        • Constructors
        • Access Modifiers
      • Parallelism & Concurrency
        • Ways to Identify Thread Concurrency or Parallelism
        • Thread Basics
          • Thread vs Process
          • Creating Threads
          • Thread Context Switching
          • Thread Lifecycle & States
          • Runnable & Callable
          • Types of Threads
          • Thread Priority
        • Thread Management & Synchronisation
          • Thread Resource Sharing
          • Thread Synchronization
            • Why is Synchronization Needed?
            • Synchronized Blocks & Methods
          • Thread Lock
            • Types of Locks
            • Intrinsic Lock (Monitor Lock)
            • Reentrant Lock
          • Semaphore
          • Thread Starvation
          • Thread Contention
          • Thread Deadlock
          • Best Practices for Avoiding Thread Issues
      • Keywords
        • this
        • super
        • Access Modifiers
      • Data Types
        • Default Values
        • Primitive Types
          • byte
          • short
          • int
          • long
          • float
          • double
          • char
          • boolean
        • Non-Primitive (Reference) Types
          • String
            • StringBuilder
            • StringBuffer
              • Problems
            • Multiline String
            • Comparison - String, StringBuilder & StringBuffer
          • Array
          • Collections
            • List
              • Array vs List
              • ArrayList
              • Vector
                • Stack
                  • Problems
              • LinkedList
            • Queue
              • PriorityQueue
              • Deque (Double-Ended Queue)
                • ArrayDeque
                • ConcurrentLinkedDeque - TBU
                • LinkedBlockingDeque - TBU
            • Map
              • HashMap
              • Hashtable
              • LinkedHashMap
              • ConcurrentHashMap
              • TreeMap
              • EnumMap
              • WeakHashMap
            • Set
              • HashSet
              • LinkedHashSet
              • TreeSet
              • EnumSet
              • ConcurrentSkipListSet
              • CopyOnWriteArraySet
        • Specialized Classes
          • BigInteger
          • BigDecimal
            • Examples
          • BitSet
          • Date and Time
            • Examples
          • Optional
          • Math
          • UUID
          • Scanner
          • Formatter
            • Examples
          • Properties
          • Regex (Pattern and Matcher)
            • Examples
          • Atomic Classes
          • Random
          • Format
            • NumberFormat
            • DateFormat
            • DecimalFormat
        • Others
          • Object
          • Enum
            • Pre-Defined Enum
            • Custom Enum
            • EnumSet and EnumMap
          • Record
          • Optional
          • System
          • Runtime
          • ProcessBuilder
          • Class
          • Void
          • Throwable
            • Error
            • Exception
              • Custom Exception Handling
              • Best Practice
            • Error vs Exception
            • StackTraceElement
    • Java Features by Version
      • How New Java Features are Released ?
      • Java Versions
        • Java 8
        • Java 9
        • Scoped Values
        • Unnamed Variables & Patterns
      • FAQ
    • Concepts
      • Set 1
        • Streams
          • flatmap
          • Collectors Utility Class
          • Problems
        • Functional Interfaces
          • Standard Built-In Interfaces
          • Custom Interfaces
        • Annotation
          • Custom Annotation
          • Meta Annotation
        • Generics
          • Covariance and Invariance
        • Asynchronous Computation
          • Future
          • CompletableFuture
          • Future v/s CompletableFuture
          • ExecutorService
            • Thread Pool
            • Types of Work Queues
            • Rejection Policies
            • ExecutorService Implementations
            • ExecutorService Usage
          • Locks, Atomic Variables, CountDownLatch, CyclicBarrier - TBU
          • Parallel Streams, Fork/Join Framework,Stream API with Parallelism - TBU
      • Set 2
        • Standards
          • ISO Standards
          • JSR
            • JSR 303, 349, 380 (Bean Validation)
        • Operator Precedence
      • Set 3
        • Date Time Formatter
        • Validation
      • Set 4
        • Input from User
        • Comparison & Ordering
          • Object Equality Check
          • Comparable and Comparator
            • Comparator Interface
          • Sorting of Objects
          • Insertion Ordering
    • Packages
      • Core Packages
        • java.lang
          • java.lang.System
          • java.lang.Thread
      • Jakarta Packages
        • jakarta.validation
        • javax.validation
      • Third-party Packages
    • Code Troubleshoot
      • Thread Dump
      • Heap Dump
    • Code Quality & Analysis
      • ArchUnit
      • Terminologies
        • Cyclic dependencies
    • Code Style
      • Naming Convention
      • Package Structure
      • Formatting
      • Comments and Documentation
      • Imports
      • Exception Handling
      • Class Structure
      • Method Guidelines
      • Page 1
      • Code Smells to Avoid
      • Lambdas and Streams Style
      • Tools
    • Tools
      • IntelliJ IDEA
        • Shortcuts for MAC
      • Apache JMeter
        • Examples
      • Thread Dump Capture
        • jstack
        • VisualVM - TBU
        • jcmd - TBU
        • JConsole - TBU
        • YourKit Java Profiler - TBU
        • Eclipse MAT - TBU
        • IntelliJ IDEA Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Thread Dump Analyzers - TBU
      • Heap Dump Capture
        • jmap
        • VisualVM - TBU
        • jcmd - TBU
        • Eclipse MAT (Memory Analyzer Tool) - TBU
        • IntelliJ IDEA Profiler - TBU
        • YourKit Java Profiler - TBU
        • AppDynamics - TBU
        • Dynatrace - TBU
        • Kill -3 Command - TBU
        • jhat (Java Heap Analysis Tool) - TBU
        • JVM Options - TBU
      • Wireshark
        • Search Filters
    • Best Practices
      • Artifact and BOM Versioning
  • Maven
    • Installation
    • Local Repository & Configuration
    • Command-line Options
    • Build & Lifecycle
    • Dependency Management
      • Dependency
        • Transitive Dependency
        • Optional Dependency
      • Dependency Scope
        • Maven Lifecycle and Dependency Scope
      • Dependency Exclusions & Overrides
      • Bill of Materials (BOM)
      • Dependency Conflict Resolution
      • Dependency Tree & Analysis
      • Dependency Versioning Strategies
    • Plugins
      • Build Lifecycle Management
      • Dependency Management
      • Code Quality and Analysis
      • Documentation Generation
      • Code Generation
      • Packaging and Deployment
      • Reporting
      • Integration and Testing
      • Customization and Enhancement
        • build-helper-maven-plugin
        • properties-maven-plugin
        • ant-run plugin
        • exec-maven-plugin
        • gmavenplus-plugin
      • Performance Optimization
    • FAQs
      • Fixing Maven SSL Issues: Unable to Find Valid Certification Path
  • Spring
    • Spring Basics
      • What is Spring?
      • Why Use Spring
      • Spring Ecosystem
      • Versioning
      • Setting Up a Spring Project
    • Core Concepts
      • Spring Core
        • Dependency Injection (DI)
        • Stereotype Annotation
      • Spring Beans
        • Bean Lifecycle
        • Bean Scope
          • Singleton Bean
        • Lazy & Eager Initialization
          • Use Case of Lazy Initialization
        • BeanFactory
        • ApplicationContext
      • Spring Annotations
        • Spring Boot Specific
        • Controller Layer (Web & REST Controllers)
    • Spring Features
      • Auto Configuration
        • Spring Boot 2: spring.factories
        • Spring Boot 3: spring.factories
      • Spring Caching
        • In-Memory Caching
      • Spring AOP
        • Before Advice
        • After Returning Advice
        • After Throwing Advice
        • After (finally) Advice
        • Around Advice
      • Spring File Handling
      • Reactive Programming
        • Reactive System
        • Reactive Stream Specification
        • Project Reactor
          • Mono & Flux
      • Asynchronous Computation
        • @Async annotation
      • Spring Security
        • Authentication
          • Core Components
            • Security Filter Chain
              • HttpSecurity
              • Example
            • AuthenticationManager
            • AuthenticationProvider
            • UserDetailsService
              • UserDetails
              • PasswordEncoder
            • SecurityContext
            • SecurityContextHolder
            • GrantedAuthority
            • Security Configuration (Spring Security DSL)
          • Authentication Models
            • One-Way Authentication
            • Mutual Authentication
          • Authentication Mechanism
            • Basic Authentication
            • Form-Based Authentication
            • Token-Based Authentication (JWT)
            • OAuth2 Authentication
            • Multi-Factor Authentication (MFA)
            • SAML Authentication
            • X.509 Certificate Authentication
            • API Key Authentication
            • Remember-Me Authentication
            • Custom Authentication
          • Logout Handling
        • Authorization
        • Security Filters and Interceptors
        • CSRF
          • Real-World CSRF Attacks & Prevention
        • CORS
        • Session Management and Security
        • Best Practices
      • Spring Persistence
        • JDBC
          • JDBC Components
          • JDBC Template
          • Transaction Management
          • Best Practices in JDBC Usage
          • Datasource
            • Connection Pooling
              • HikariCP
            • Caching
        • JPA (Java Persistence API)
          • JPA Fundamentals
          • ORM Mapping Annotations
            • 1. Entity and Table Mappings
            • 2. Field/Column Mappings
            • 3. Relationship Mappings
            • 4. Inheritance Mappings
            • 5. Additional Configuration Annotations
          • Querying Data
            • JPQL
            • Criteria API
            • JPA Specification
              • Example - Employee Portal
            • Native SQL Queries
            • Named Queries
            • Query Return Types
            • Pagination & Sorting
              • Example - Employee Portal
            • Projection
          • Fetch Strategies in JPA
        • JPA Implementation
          • Hibernate
            • Properties
            • Example
        • Spring Data JPA
          • Repository Abstractions
          • Entity-to-Table Mapping
          • Derived Query Methods
        • Cross-Cutting Concerns
          • Transactions
          • Caching
          • Concurrency
        • Examples
          • Employee Portal
            • API
    • Distributed Systems & Communication
      • Distributed Scheduling
      • Inter-Service Communication
        • 1. RestTemplate
        • 2. WebClient
        • 3. OpenFeign
        • Retry Mechanism
          • @Retryable annotation
            • Example
    • Security & Data Protection
      • Encoding | Decoding
        • Types
          • Base Encoding
            • Base16 - TBD
              • Encoding and Decoding in Java - TBD
            • Base32
              • Encoding and Decoding in Java
            • Base64 -TBD
              • Encoding and Decoding in Java - TBD
          • Text Encoding - TBD
            • Extended ASCII
              • Encoding and Decoding in Java - TBD
                • ISO-8859-1
                • Windows-1252 - TBD
                • IBM Code Pages - TBD
            • ASCII
              • Encoding and Decoding in Java
        • Java Guidelines
          • Text Encoding Decoding Examples
          • Base Encoding Decoding Examples
          • Best Practices and Concepts
          • Libraries
      • Cryptography
        • Terminology
        • Java Cryptography Architecture (JCA)
        • Key Management
          • Key Generation
            • Tools and Libraries
              • OpenSSL
              • Java Keytool
                • Concept
                • Use Cases
            • Key & Certificate File Formats
          • Key Distribution
          • Key Storage
          • Key Rotation
          • Key Revocation
        • Encryption & Decryption
          • Symmetric Encryption
            • Algorithm
            • Modes of Operation
            • Examples
          • Asymmetric Encryption
            • Algorithm
            • Mode of Operation
            • Examples
    • Utilities & Libraries
      • Apache Libraries
        • Apache Camel
          • Camel Architecture
            • Camel Context
            • Camel Endpoints
            • Camel Components
            • Camel Exchange & MEP
          • Spring Dependency
          • Different Components
            • Camel SFTP
        • Apache Commons Lang
      • MapStruct Mapper
      • Utilities by Spring framework
        • FileCopyUtils
    • General Concepts
      • Spring Boot Artifact Packaging
      • Classpath and Resource Loading
      • Configuration - Mapping Properties to Java Class
      • Validations in Spring Framework
        • Jakarta Validation
          • Jakarta Bean Validation Annotations
    • Practical Guidelines
      • Spring Configuration
      • Spring Code Design
  • Software Testing
    • Software Testing Methodologies
      • Functional Testing
      • Non Functional Testing
    • Software Testing Life Cycle (STLC)
    • Integration Test
      • Dynamic Property Registration
    • Java Test Framework
      • JUnit
        • JUnit 4
          • Examples
        • JUnit 5
          • Examples
        • JUnit 4 vs JUnit 5
  • System Design
    • Foundations
      • Programming Paradigms
      • Object-Oriented Design
        • SOLID Principles
        • GRASP Principles
        • Composition
        • Aggregation
        • Association
      • Design Pattern
        • Creational Pattern
        • Structural Pattern
        • Behavioral Pattern
        • Examples
          • Data Collector
          • Payment Processor
        • Design Enhancements
          • Fluent API Design
            • Examples
    • Architectural Building Blocks
      • CAP Theorem
      • Load Balancer
        • Load Balancer Architecture
        • Load Balancing in Java Microservices
          • Client-Side Load Balancing Example
          • Server-Side Load Balancing Example
        • Load Balancer Monitoring Tool
      • Scaling
        • Vertical Scaling (Scaling Up)
        • Horizontal Scaling (Scaling Out)
        • Auto-Scaling
        • Database Scaling via Sharding
      • Caching
        • Pod-Level vs Distributed Caching
      • Networking Metrics
        • Types of Delay
        • Scenario
      • System Characteristics
      • Workload Types
      • Resilience & Failure Handling
    • Performance
      • Why Is My API Sometimes Slow ?
    • Security
      • Security by Design
      • Zero Trust Security Model
      • Zero Trust Architecture
      • Principles
        • CIA
        • Least Privilege Principle
        • Defense in Depth
      • Security Threats & Mitigations
        • OWASP
          • Top 10 Security Threats
          • Application Security Verification Standard
          • Software Assurance Maturity Model
          • Dependency Check
          • CSRFGuard
          • Cheat Sheets
          • Security Testing Guide
          • Threat Dragon
        • Threat Modeling
      • Compliance & Regulation
        • PCI DSS
    • Deployment Patterns
    • Diagrams
      • UML Diagrams
        • PlantUML
          • Class Diagram
          • Object Diagram
          • Sequence Diagram
          • Use Case Diagram
          • Activity Diagram
          • State Diagram
          • Architecture Diagram
          • Component Diagram
          • Timing Diagram
          • ER Diagram (Entity-Relationship)
          • Network Diagram
    • Common Terminologies
    • Problems
      • Reference Materials
      • Cache Design
  • Interview Guide
    • Non-Technical
      • Behavioural or Introductory Guide
      • Project Specific
    • Technical
      • Java Interview Companion
        • Java Key Concepts
          • Set 1
          • Set 2
        • Java Code Snippets
        • Java Practice Programs
          • Set 3 - Strings
          • Set 4 - Search
          • Set 5 - Streams and Collection
      • SQL Interview Companion
        • SQL Practice Problems
          • Set 1
      • Spring Interview Companion
        • Spring Key Concepts
          • Set 1 - General
          • Set 2 - Core Spring
        • Spring Code Snippets
          • JPA
      • Application Server
      • Maven
      • Containerized Application
      • Microservices
    • General
      • Applicant Tracking System (ATS)
      • Flowchart - How to Solve Coding Problem?
Powered by GitBook
On this page
  • About
  • How OAuth2 Authentication Works ?
  • OAuth2 Roles
  • OAuth2 Client & OAuth2 Resource Owner
  • OAuth2 Grant Types (Authorization Flows)
  • 1. Authorization Code Flow (Recommended for Web Apps & SPAs)
  • 2. Client Credentials Flow (Used for Machine-to-Machine Authentication)
  • 3. Implicit Flow (Deprecated, Previously Used for SPAs)
  • 4. Password Grant Flow (Deprecated, Previously Used for Direct Login)
  • 5. Device Authorization Flow (Used for Devices Without Keyboards)
  • OAuth2 Tokens
  • Access Token
  • Refresh Token
  • OAuth2 with Spring Security
  • 1. Dependencies
  • 2. Configure OAuth2 Login (Google as Provider)
  • 3. Enable OAuth2 Login in Security Configuration
  • OAuth2 with Resource Server (Protecting APIs)
  • OAuth2 vs OpenID Connect (OIDC)
  • OAuth2: When to Use?
  • OpenID Connect (OIDC): When to Use?
  • OAuth2 + OIDC: When to Use Both?

Was this helpful?

  1. Spring
  2. Spring Features
  3. Spring Security
  4. Authentication
  5. Authentication Mechanism

OAuth2 Authentication

About

OAuth2 (Open Authorization 2.0) is an industry-standard authorization protocol that allows secure access to resources without sharing credentials. It is widely used in modern applications for third-party authentication and authorization, such as Google, Facebook, and GitHub login.

OAuth2 is primarily an authorization framework, but it can be extended to handle authentication using OpenID Connect (OIDC).

How OAuth2 Authentication Works ?

  1. User Requests Access

    • The user attempts to log in to an application using OAuth2 (e.g., "Login with Google").

  2. Redirect to Authorization Server

    • The application redirects the user to the OAuth2 provider (Authorization Server) (e.g., Google, Facebook).

  3. User Grants Permission

    • The user logs in and grants permission for the application to access their data (e.g., email, profile).

  4. Authorization Server Issues Code

    • If permission is granted, the OAuth2 provider returns an authorization code to the application.

  5. Application Requests Access Token

    • The application exchanges the authorization code for an access token from the OAuth2 provider.

  6. Application Uses Token

    • The application includes the access token in API requests to access user data.

The typical work flow for OAuth 2.0 requests

  • When a user tries to access a feature in our application that requires them to be logged into a Google or YouTube account, our application triggers the OAuth 2.0 authorization process.

  • Our application redirects the user to Google's authorization server, specifying the scope of access it requires. This scope defines the actions our application can perform—such as retrieving, inserting, updating, or deleting resources—on behalf of the authenticated user.

  • If the user grants permission, Google provides a token to our application. Depending on the application type, it either validates the token or exchanges it for another type.

  • For instance, a server-side web application exchanges the received token for both an access token and a refresh token. The access token allows the application to make authorized requests on the user’s behalf, while the refresh token enables it to obtain a new access token when the current one expires.

OAuth2 Roles

OAuth2 defines four key roles:

Role

Description

Resource Owner

The user who grants access to their data.

Client

The application requesting access on behalf of the user.

Authorization Server

Issues access tokens after user consent.

Resource Server

The API that holds the user’s protected resources.

OAuth2 Client & OAuth2 Resource Owner

1. OAuth2 Client

  • Acts as the application that requires authentication and authorization from an OAuth2 provider.

  • The client does not store or validate tokens, but instead relies on an OAuth2 Authorization Server (like Keycloak, Google, or GitHub) to handle authentication.

  • The user logs in through the OAuth2 provider, and the client application obtains an access token to act on behalf of the user.

  • Commonly used for SSO (Single Sign-On) or integrating with external authentication providers.

Example Use Case:

  • A web application that allows users to log in with Google OAuth (instead of its own authentication system).

  • When a user clicks "Login with Google," the OAuth2 Client redirects the user to Google's authentication page.

  • Once authenticated, Google redirects back with an authorization code, which the client exchanges for an access token.

  • The web app then uses this token to access user data from Google's API.

2. OAuth2 Resource Server

  • Acts as the backend API that protects its resources and validates incoming access tokens.

  • It does not authenticate users directly, but instead verifies the access token issued by an OAuth2 Authorization Server.

  • Used when a client application (frontend, mobile, or another service) sends a request with an OAuth2 access tokento access a protected API.

Example Use Case:

  • We have a REST API that only allows authenticated users to fetch data.

  • A frontend (React/Angular) calls the API and sends an OAuth2 access token.

  • The resource server (API) validates the token and processes the request if valid.

OAuth2 Grant Types (Authorization Flows)

OAuth2 provides different grant types (authorization flows) to handle different use cases. These grant types define how a client application can obtain an access token to access a protected resource (e.g., an API).

1. Authorization Code Flow (Recommended for Web Apps & SPAs)

Best for: Web applications (backend and frontend) & Single Page Applications (SPAs).

How it Works:

  1. The user tries to log in through a third-party provider (e.g., Keycloak, Google, GitHub, or other identity providers).

  2. The provider redirects the user to a login page.

  3. After successful login, the provider sends back an authorization code to the application.

  4. The application exchanges the authorization code for an access token (by making a server-to-server request).

  5. The application can now use the access token to access the user’s data.

Why Use This?

  • More secure since the token is not exposed to the frontend.

  • Uses server-to-server communication, reducing the risk of token theft.

2. Client Credentials Flow (Used for Machine-to-Machine Authentication)

Best for: Services or APIs communicating without user involvement.

How it Works:

  1. The client application (e.g., a backend service) directly sends a request to the authorization server with its client ID and client secret.

  2. The authorization server verifies the credentials and returns an access token.

  3. The client uses the access token to access the protected resource (e.g., an API).

Why Use This?

  • No user is involved; only trusted backend services use this flow.

  • Used for microservices or backend-to-backend communication.

3. Implicit Flow (Deprecated, Previously Used for SPAs)

Best for: Older SPAs (NOT recommended due to security risks).

How it Works:

  1. The user logs in through a third-party provider.

  2. The provider directly returns an access token to the frontend application (without an authorization code).

  3. The frontend application uses this token to access resources.

Why It’s Deprecated?

  • Tokens are exposed in the browser URL, making them vulnerable to attacks.

  • Authorization Code Flow with PKCE is now recommended instead.

4. Password Grant Flow (Deprecated, Previously Used for Direct Login)

Best for: Legacy applications (NOT recommended).

How it Works:

  1. The user enters their username and password directly into the client application.

  2. The client application sends these credentials to the authorization server.

  3. The authorization server verifies them and returns an access token.

Why It’s Deprecated?

  • Requires users to trust third-party applications with their credentials.

  • Security risk if credentials are stored or exposed.

5. Device Authorization Flow (Used for Devices Without Keyboards)

Best for: Smart TVs, gaming consoles, IoT devices.

How it Works:

  1. The device displays a code and asks the user to visit a URL on another device (e.g., a smartphone).

  2. The user logs in on their smartphone and approves access.

  3. The device then receives an access token and can authenticate.

Why Use This?

  • Allows login on devices with no keyboard or browser.

  • Secure since login happens on a trusted device.

OAuth2 Tokens

Access Token

  • A short-lived token used to access resources (e.g., APIs).

  • Included in the Authorization header:

    Authorization: Bearer <access_token>
  • Typically expires in minutes or hours.

Refresh Token

  • A long-lived token that allows obtaining a new access token without user interaction.

  • Used when an access token expires.

OAuth2 with Spring Security

1. Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

2. Configure OAuth2 Login (Google as Provider)

application.yml:

spring:
  security:
    oauth2:
      client:
        registration:
          google:
            client-id: your-client-id
            client-secret: your-client-secret
            scope: profile, email

3. Enable OAuth2 Login in Security Configuration

Spring Boot 2 (Spring Security 5)

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .csrf().disable()
            .authorizeRequests()
                .antMatchers("/").permitAll()
                .anyRequest().authenticated()
            .and()
            .oauth2Login();  // Enable OAuth2 Login
    }
}

Spring Boot 3 (Spring Security 6)

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/").permitAll()
                .anyRequest().authenticated()
            )
            .oauth2Login(Customizer.withDefaults());  // Enable OAuth2 Login

        return http.build();
    }
}

OAuth2 with Resource Server (Protecting APIs)

1. Dependencies

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

2. Configure Resource Server

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: https://accounts.google.com

3. Secure API Endpoints with OAuth2 Token

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public").permitAll()
                .requestMatchers("/api/**").authenticated()
            )
            .oauth2ResourceServer(oauth2 -> oauth2.jwt());

        return http.build();
    }
}

OAuth2 vs OpenID Connect (OIDC)

OAuth2 and OpenID Connect (OIDC) are both authentication and authorization protocols, but they serve different purposes.

Feature

OAuth2

OpenID Connect (OIDC)

Purpose

Authorization (Who can access what?)

Authentication + Authorization (Who are you?)

Primary Use

API security (Granting access to resources)

User authentication (Logging in users)

Token Type

Access Token (for resource access)

ID Token (for authentication) + Access Token

Standardized User Info?

No built-in user identity

Yes, provides user identity claims

Used For

Securing APIs, allowing third-party apps access (e.g., GitHub OAuth login)

Single Sign-On (SSO), federated login, mobile/web app authentication

Token Format

JWT or opaque token

Always JWT for ID Token

Identity Provider (IdP)

Not required (only authorization server needed)

Requires an Identity Provider (IdP)

OAuth2: When to Use?

Best for API Authorization

  • If we need to grant third-party applications access to your APIs securely.

  • Example: Google Drive API access via OAuth2 (Allowing a third-party app to read your Google Drive files).

Secure Resource Access Without Exposing User Credentials

  • Users grant permission to apps without sharing their username & password.

  • Example: Logging into Spotify with your Google account without giving your Google password.

Fine-Grained Access Control

  • We can define scopes (e.g., “read-only” or “read-write” access).

  • Example: GitHub lets apps request only "read repo" instead of full account access.

Not Ideal for User Authentication

  • OAuth2 alone doesn’t verify the user’s identity.

  • Third-party apps can misuse OAuth tokens for login (OAuth2 abuse problem).

OpenID Connect (OIDC): When to Use?

Best for User Authentication (Login Systems & SSO)

  • If we need user authentication with identity claims (e.g., name, email).

  • Example: "Login with Google" or "Login with Facebook" uses OIDC.

Mobile & Web App Authentication

  • Modern apps use OIDC for user login workflows.

  • Example: Amazon Cognito uses OIDC for authentication.

Single Sign-On (SSO)

  • If you need federated login across multiple apps.

  • Example: Logging into Slack using your Google account.

Not Ideal for API-Only Authorization

  • OIDC is overkill for securing APIs without login needs.

  • Use OAuth2 with scopes if no user authentication is needed.

OAuth2 + OIDC: When to Use Both?

Many systems combine OAuth2 & OpenID Connect to get both authentication & authorization. Example:

  1. OIDC authenticates the user (Who are you?)

  2. OAuth2 provides API access (What can you access?)

Example Use Case:

  • Logging into Google Drive (OIDC) → Then accessing Google Drive API (OAuth2).

PreviousToken-Based Authentication (JWT)NextMulti-Factor Authentication (MFA)

Last updated 2 months ago

Was this helpful?