OAuth (Open Authorization) is an open standard protocol that allows users to grant third-party applications access to their resources without sharing their credentials. It is commonly used to enable secure access to user data across different applications.

Why Should We Use OAuth?

  1. Security: OAuth allows users to share specific data without revealing their passwords.
  2. User Experience: Users can log in easily using existing accounts (like Google or Facebook).
  3. Granular Access Control: Developers can specify which resources an application can access.
  4. Scalability: OAuth is well-suited for modern web applications that interact with multiple third-party services.

Basics of OAuth

OAuth typically involves three roles:

  1. Resource Owner: The user who grants access to their resources.
  2. Client: The application requesting access to the resources.
  3. Authorization Server: The server that manages authorization and issues tokens.

OAuth Flow

  1. The user is redirected to the authorization page of the Authorization Server.
  2. The user logs in and grants permission to the client.
  3. The Authorization Server returns an authorization code.
  4. The client exchanges this code for an access token from the Authorization Server.
  5. The client uses the access token to access protected resources.

Code Example: OAuth 2.0 with Java Spring Boot and Angular

This example demonstrates how to implement OAuth 2.0 in a Java Spring Boot application with an Angular frontend to access the GitHub API.

Step 1: Set Up the Spring Boot Application

1. Create a Spring Boot Project

  • Spring Web
  • Spring Security
  • OAuth2 Client

2. Configure application.yml

spring:
  security:
    oauth2:
      client:
        registration:
          github:
            client-id: YOUR_CLIENT_ID
            client-secret: YOUR_CLIENT_SECRET
            scope: read:user
            redirect-uri: "{baseUrl}/login/oauth2/code/{registrationId}"
        provider:
          github:
            authorization-uri: https://github.com/login/oauth/authorize
            token-uri: https://github.com/login/oauth/access_token
            user-info-uri: https://api.github.com/user

2. Create a Security Configuration

The SecurityConfig class is crucial for defining how security is handled in your Spring Boot application. Here’s a breakdown of its components:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .antMatchers("/", "/login").permitAll() // Allow public access to these endpoints
            .anyRequest().authenticated()// Require authentication for all other requests
            .and()
            .oauth2Login();
    }
}
  • @Configuration: Indicates that this class provides Spring configuration.
  • @EnableWebSecurity: Enables Spring Security’s web security support.
  • authorizeRequests(): Configures URL-based authorization.
    • .antMatchers("/", "/login").permitAll(): Allows unauthenticated access to the root (“/”) and login (“/login”) endpoints.
    • .anyRequest().authenticated(): Requires authentication for all other requests.
  • oauth2Login(): Enables OAuth2 login support, which handles the redirection to the authorization server (GitHub in this case).

Authorization Flow Explained

Here’s how the OAuth2 authorization flow works in detail:

1: User Initiates Login

When a user tries to access a protected resource (any URL other than “/” or “/login”), they are redirected to the login page. This page typically includes a button or link to log in via GitHub.

2: Redirect to GitHub

When the user clicks the login button, they are redirected to the GitHub authorization page. This redirection is handled by Spring Security automatically due to the oauth2Login() configuration. The request includes parameters like the client ID, redirect URI, and requested scopes.

3: User Grants Permission

On the GitHub authorization page, the user logs in (if not already logged in) and is prompted to authorize the application to access their data (like user profile information).

4: Authorization Code Received

Once the user grants permission, GitHub redirects the user back to your application’s specified redirect URI (configured in application.yml). This URI includes an authorization code as a query parameter.

5: Exchange Authorization Code for Access Token

Spring Security automatically handles the exchange of the authorization code for an access token. It sends a request to GitHub’s token endpoint with the authorization code, client ID, and client secret.

6: Access Protected Resources

With the access token received, the application can now make authorized requests to the GitHub API on behalf of the user. For example, it can fetch the user’s profile information using the /user endpoint.

Step 3: Create the Angular Application

1. Set Up Angular Project

Create a new Angular project using the Angular CLI:

ng new oauth-demo
cd oauth-demo

2. Create a Service to Handle Authentication

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  private apiUrl = 'http://localhost:8080'; // Your Spring Boot API URL

  constructor(private http: HttpClient) {}

  getUserProfile() {
    return this.http.get(`${this.apiUrl}/user`);
  }
}

3. Create a Component to Display User Information

import { Component, OnInit } from '@angular/core';
import { AuthService } from './auth.service';

@Component({
  selector: 'app-profile',
  template: `
    <h1>User Profile</h1>
    <pre>{{ user | json }}</pre>
  `
})
export class ProfileComponent implements OnInit {
  user: any;

  constructor(private authService: AuthService) {}

  ngOnInit() {
    this.authService.getUserProfile().subscribe(data => {
      this.user = data;
    });
  }
}

Step 4: Explanation of the Code

  • Spring Boot: The backend handles OAuth authentication and provides user data from GitHub.
  • Angular: The frontend interacts with the Spring Boot API to fetch and display user information.
  • Security Configuration: Defines which endpoints are secured and enables OAuth2 login.
  • Authorization Flow: When users log in, they are redirected to GitHub for authentication, and upon successful login, they are redirected back to the application.

Advantages of OAuth in Special Cases

  1. Mobile Applications: Users can log in quickly without entering passwords.
  2. Third-Party Integrations: Simplifies the integration of services like Google Drive or Dropbox into your applications.
  3. Enterprise Applications: Enables centralized user management and access control.
Conclusion

OAuth is a powerful protocol that enhances security and user experience in modern web applications. By implementing OAuth, developers can create robust and user-friendly applications that meet the demands of today’s digital landscape. With this guide, you should now have a foundational understanding of OAuth and how to implement it using Java Spring Boot and Angular.

By Shabazz

Software Engineer, MCSD, Web developer & Angular specialist

Leave a Reply

Your email address will not be published. Required fields are marked *