OAuth 2.0

OAuth 2.0 is an authorization framework that allows applications to access user resources without exposing user credentials.

It is widely used by modern applications for secure authentication and authorization.


What is OAuth 2.0?

OAuth 2.0 allows a third-party application to access resources on behalf of a user using access tokens instead of username and password.

Example: Logging into an application using a Google account.

OAuth 2.0 Roles

  • Resource Owner – The user who owns the data
  • Client – Application requesting access
  • Authorization Server – Issues access tokens
  • Resource Server – Stores protected resources

OAuth 2.0 Flow

User
 ↓
Client Application
 ↓
Authorization Server
 ↓
Access Token
 ↓
Resource Server
The client uses the access token to access protected resources.

Common OAuth 2.0 Grant Types

  • Authorization Code Grant
  • Client Credentials Grant
  • Implicit Grant
  • Password Grant (deprecated)

Authorization Code Flow

This is the most secure OAuth 2.0 flow used by web applications.

User → Client → Authorization Server
      ← Authorization Code
Client → Authorization Server
      ← Access Token
Client → Resource Server
      ← Protected Data

Spring Boot OAuth 2.0 Implementation

Step 1 – Add Dependencies

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

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

Step 2 – Configure OAuth in application.yml

spring:
 security:
  oauth2:
   client:
    registration:
     google:
      client-id: YOUR_CLIENT_ID
      client-secret: YOUR_CLIENT_SECRET
      scope:
        - email
        - profile
Client credentials are obtained from the OAuth provider.

Step 3 – Configure Security

@Configuration
@EnableWebSecurity
public class SecurityConfig {

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

http
.authorizeHttpRequests(auth -> auth
.anyRequest().authenticated()
)
.oauth2Login();

return http.build();
}

}

Step 4 – Create Controller

@RestController
public class HomeController {

@GetMapping("/")
public String home(){
return "OAuth Login Successful";
}

}

OAuth 2.0 Architecture with Spring Boot

User
 ↓
Browser
 ↓
Spring Boot Application
 ↓
OAuth Provider
 ↓
Access Token
 ↓
Protected APIs

Real World Example

Many applications allow users to log in using external providers.

  • Login with Google
  • Login with GitHub
  • Login with Facebook
The application never sees the user password. Instead, it receives an access token.

Quick Summary

  • OAuth 2.0 is an authorization framework
  • Uses access tokens instead of passwords
  • Commonly used for social login
  • Spring Boot provides built-in OAuth support

0 comments

Leave a comment