data-driven-docs

Selft training repo


Project maintained by ggranados Hosted on GitHub Pages — Theme by mattgraham

OAuth


Table of Contents


OAuth (Open Authorization) is an open standard protocol that allows secure and controlled access to protected resources, such as user data or APIs, without the need to share a user’s credentials (username and password) with the requesting application. It provides a standardized way for applications to request and obtain authorization to access resources on behalf of a user. OAuth is widely used in modern web and mobile applications to enable secure access to various services and APIs.

Back to top

OAuth Versions

OAuth 2.0 logoOAuth 2.0 is the industry-standard protocol for authorization. It focuses on client developer simplicity while providing specific authorization flows for web applications, desktop applications, mobile phones, and living room devices. This specification and its extensions are being developed within the IETF OAuth Working Group.

OAuth 2.1 is an in-progress effort to consolidate OAuth 2.0 and many common extensions under a new name.

Back to top

How OAuth Works

OAuth2.0 Roles

OAuth involves four main roles:

Back to top

OAuth Flow Steps

img.png

Back to top

Benefits of OAuth

Back to top

Grant Types

Authorization Code Flow

(Standard Web Application Flow)

This is the most common and secure OAuth flow for web applications. It involves multiple steps, including redirecting the user to the authorization server for consent and obtaining an authorization code, which is then exchanged for an access token. This flow is suitable for server-to-server communication and allows for token refresh.

Flow steps are:

Back to top

Implicit Flow

(Single-Page Application Flow)

The Implicit Flow is designed for browser-based applications and is commonly used in single-page applications (SPAs). Instead of obtaining an authorization code, the access token is returned directly to the client application after user consent. However, this flow does not support token refresh, which can be a security concern.

Flow steps are:

Back to top

Client Credentials Flow

The Client Credentials Flow is used when the client application (usually a server-side application) needs to access its resources without acting on behalf of any specific user. The client directly requests an access token from the authorization server using its own credentials (client ID and client secret).

Flow steps are:

Back to top

JWT Bearer Token Flow

The JWT Bearer Token Flow is essentially a JWT (JSON Web Token) implementation of the OAuth 2.0 Client Credentials Flow

The JWT Bearer Token Flow is a simplified OAuth 2.0 flow designed for clients that are not capable of keeping client secrets, such as native mobile apps or single-page applications (SPAs).

Flow steps are:

Back to top

Resource Owner Password Credentials Flow

Is intended for trusted applications (e.g., native mobile apps) where the client application collects the user’s username and password directly and sends them to the authorization server to obtain an access token. This flow should be used with caution due to potential security risks of handling user credentials.

Flow steps are:

There are also extension grant types and custom flows that can be implemented based on specific requirements, but the four flows mentioned above are the core flows standardized by OAuth 2.0.

Back to top

Example

Basic example of the Authorization Code Flow implemented in an HTML page using JavaScript. Please remember that this example is simplified for educational purposes and may not cover all security considerations or error handling.

<!DOCTYPE html>
<html>
<head>
    <title>Authorization Code Flow Example</title>
</head>
<body>
    <h1>Authorization Code Flow Example</h1>
    
    <button onclick="authorize()">Authorize</button>
    
    <script>
        function authorize() {
            // Step 1: Redirect user to authorization server for authentication and consent
            const authorizationEndpoint = 'https://example.com/authorization'; // Replace with your authorization endpoint
            const clientId = 'your_client_id'; // Replace with your client ID
            const redirectUri = 'https://your-redirect-uri.com/callback'; // Replace with your redirect URI
            const scope = 'desired_scope'; // Replace with desired scope
            
            const authUrl = `${authorizationEndpoint}?response_type=code&client_id=${clientId}&redirect_uri=${redirectUri}&scope=${scope}`;
            
            window.location.href = authUrl;
        }
        
        // Callback function after user is redirected back from authorization server
        function handleCallback() {
            const authorizationCode = getParameterByName('code');
            
            // Step 3: Exchange authorization code for an access token
            const tokenEndpoint = 'https://example.com/token'; // Replace with your token endpoint
            const clientSecret = 'your_client_secret'; // Replace with your client secret
            
            const tokenData = {
                grant_type: 'authorization_code',
                code: authorizationCode,
                redirect_uri: 'https://your-redirect-uri.com/callback',
                client_id: 'your_client_id',
                client_secret: clientSecret
            };
            
            fetch(tokenEndpoint, {
                method: 'POST',
                body: new URLSearchParams(tokenData),
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
            .then(response => response.json())
            .then(data => {
                const accessToken = data.access_token;
                
                // Step 4: Use access token to access protected resources
                const resourceEndpoint = 'https://api.example.com/resource'; // Replace with your protected resource endpoint
                
                fetch(resourceEndpoint, {
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                })
                .then(response => response.json())
                .then(resourceData => {
                    console.log('Resource Data:', resourceData);
                })
                .catch(error => {
                    console.error('Error accessing resource:', error);
                });
            })
            .catch(error => {
                console.error('Error exchanging authorization code for token:', error);
            });
        }
        
        // Helper function to get query parameter by name from URL
        function getParameterByName(name) {
            const url = window.location.href;
            name = name.replace(/[\[\]]/g, '\\$&');
            const regex = new RegExp(`[?&]${name}(=([^&#]*)|&|#|$)`),
            results = regex.exec(url);
            if (!results) return null;
            if (!results[2]) return '';
            return decodeURIComponent(results[2].replace(/\+/g, ' '));
        }
    </script>
</body>
</html>

Back to top


Ref.


Get Started | Web Services and API Design