Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site.... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

News

OAuth2: secure authentication online 

Discover how OAuth 2.0 enhances online security, enabling access without sharing credentials. Learn how access tokens and refresh tokens work.

Gaining access

Table of contents

  • OAuth 2.0: the secure authentication standard for the web 
  • What is OAuth 2.0 and how does it work? 
  • OAuth 2.0 authorization flow 
  • OAuth 1.0 vs. OAuth 2.0: key differences 
  • The role of access tokens and refresh tokens in OAuth 2.0 
  • OAuth 2.0 grant types: different authorization flows 
  • OAuth 2.0 and native applications 

OAuth 2.0: the secure authentication standard for the web 

Online authentication and authorization are essential for securing user data and managing access permissions. OAuth 2.0 is a widely adopted open standard that enables users to obtain access to online services without sharing their credentials directly.

It is used by major platforms such as Google, Facebook, and Amazon to facilitate Single Sign-On (SSO) and secure authorization for third-party applications. 

This article explores how OAuth 2.0 works, its advantages over OAuth 1.0, the role of access tokens and refresh tokens, and how different grant types handle authentication flows. 

What is OAuth 2.0 and how does it work? 

OAuth 2.0: detailed workflow with examples and code 

OAuth 2.0 is an authorization protocol that allows applications to access user data without exposing their credentials.

Instead of using usernames and passwords for every request, OAuth 2.0 requires an access token, a temporary key that grants specific permissions to interact with a protected resource

Key components of OAuth 2.0 

The OAuth 2.0 authorization flow involves four key entities: 

  • Client
    The application requesting access to a protected resource
  • Resource owner
    The user who owns the data and grants permission. 
  • Resource server
    The server that hosts the protected resource and responds to requests if the access token is valid.
  • Authorization server
    The system that authenticates the resource owner and issues an access token to the client

Real-world example
Imagine an application called PhotoShare, which allows users to edit and publish photos directly from their Google Drive. 

  • PhotoShare is the client that needs permission to access images stored in Google Drive (the resource server). 
  • The user (resource owner) logs in via Google (authorization server) to grant access. 
  • If the user approves, Google issues an access token, allowing PhotoShare to interact with Google Drive without requiring the user’s credentials each time.

OAuth 2.0 authorization flow 

The authorization process follows these basic steps:

The client redirects the user to the authorization server 

When the user logs in, the client redirects them to the authorization server, including parameters such as: 

  • Client_id
    The registered application’s ID. 
  • Response_type
    The expected response (usually code for the authorization code flow). 
  • Redirect_uri
    The URL to return the user after authorization. 
  • Scope
    The requested permissions (e.g., read, write). 

Example GET request: 

http 

GET https://accounts.google.com/o/oauth2/auth? 

    response_type=code& 

    client_id=CLIENT_ID& 

    redirect_uri=https://photoshare.com/callback& 

    scope=https://www.googleapis.com/auth/drive.readonly& 

    state=xyz

The user grants permission 

The user is redirected to Google’s login page and, upon successful authentication, is asked whether to grant PhotoShare permission to access their Google Drive images. 

If the user approves, the authorization server generates an authorization code and sends it to the client

Example response: 

http 

HTTP/1.1 302 Found 

Location: https://photoshare.com/callback?code=AUTHORIZATION_CODE&state=xyz

The client exchanges the code for an access token 

Now, the client must exchange the received code for an access token by sending a POST request to the token endpoint of the authorization server.

Example POST request: 

http 

POST https://oauth2.googleapis.com/token 

Content-Type: application/x-www-form-urlencoded 

client_id=CLIENT_ID& 

client_secret=CLIENT_SECRET& 

grant_type=authorization_code& 

code=AUTHORIZATION_CODE& 

redirect_uri=https://photoshare.com/callback

If the request is valid, the authorization server responds with an access token and, optionally, a refresh token

Example response: 

json 

{ 

  "access_token": "ya29.a0AfH6SM...", 

  "expires_in": 3600, 

  "refresh_token": "1//09X...", 

  "scope": "https://www.googleapis.com/auth/drive.readonly", 

  "token_type": "Bearer" 

}

The client uses the access token to access the protected resource 

Now that the client has obtained an access token, it can use it to make authorized API requests. 

The token must be included in the Authorization Header of the request: 

http 

GET https://www.googleapis.com/drive/v3/files 

Authorization: Bearer ya29.a0AfH6SM...

If the token is valid, the resource server (Google Drive) responds with the requested data. 

Example response: 

json 

{ 

  "files": [ 

    { 

      "id": "1a2b3c", 

      "name": "vacation.jpg", 

      "mimeType": "image/jpeg" 

    } 

  ] 

}

If the access token has expired or is invalid, the server responds with a 401 Unauthorized error, prompting the client to request a new access token

Refreshing an expired access token 

Since access tokens have a short lifespan (e.g., 1 hour), the client can use a refresh token to obtain a new one without requiring the user to log in again. 

Example refresh token request: 

http 

POST https://oauth2.googleapis.com/token 

Content-Type: application/x-www-form-urlencoded 

client_id=CLIENT_ID& 

client_secret=CLIENT_SECRET& 

grant_type=refresh_token& 

refresh_token=1//09X...
json 

{ 

  "access_token": "ya29.a0AfH6SM...NEW", 

  "expires_in": 3600, 

  "token_type": "Bearer" 

}

Conclusions

Using OAuth 2.0 enhances security because it eliminates the need to share passwords and allows users to control which applications can access their data. Furthermore, refresh tokens allow continuous access without repeated logins. 

This protocol is widely used for services such as: 

  • Google Sign-In (for authentication via Google accounts); 
  • Facebook Login (to sign in to third-party websites):
  • Cloud API access (e.g., Dropbox, GitHub, Microsoft 365). 

Example Implementation in Python (Using requests) 

python 

import requests 

TOKEN = "ya29.a0AfH6SM..." 

headers = {"Authorization": f"Bearer {TOKEN}"} 

response = requests.get("https://www.googleapis.com/drive/v3/files", headers=headers) 

if response.status_code == 200: 

    print("Results:", response.json()) 

else: 

    print("Error:", response.status_code, response.text)

By implementing OAuth 2.0, applications can securely manage user authentication and authorization, ensuring a safer and more efficient way to access protected resources online. 

OAuth 1.0 vs. OAuth 2.0: key differences 

Prior to OAuth 2.0, delegated authentication was done through OAuth 1.0, which had significant limitations. OAuth 2.0 introduced major improvements:

Here’s how OAuth 2.0 improved upon its predecessor: 

  • Simplified authentication
    OAuth 2.0 eliminates the need for cryptographic signing, making it easier to implement. 
  • Better support for mobile and web apps
    OAuth 2.0 introduced improved flows for native applications and browser-based applications. 
  • Flexible authorization flows
    OAuth 2.0 allows different grant types, tailoring authentication methods to different use cases. 
  • More secure token management
    OAuth 2.0 uses refresh tokens to extend session durations securely. 

These enhancements make OAuth 2.0 the preferred standard for modern authentication systems. 

Secure token management

The role of access tokens and refresh tokens in OAuth 2.0 

OAuth 2.0 relies on access tokens and refresh tokens to authenticate users and manage session durations securely. 

Access tokens 

An access token is a temporary credential that grants the client access to a protected resource. It includes three main components: 

  • Header
    Contains metadata such as token type and signing algorithm. 
  • Payload
    Stores user information, authorization scope, and expiration time. 
  • Signature
    Ensures token integrity and prevents tampering. 

Access tokens have a limited lifespan, reducing the risk of exposure in case of a security breach. 

Refresh tokens 

A refresh token is a long-lived credential that allows the client to request a new access token without requiring the user to log in again. This enhances security while improving the user experience by maintaining continuous access to resources. 

OAuth 2.0 grant types: different authorization flows 

OAuth 2.0 provides multiple grant types to accommodate different authentication scenarios, offering varying levels of security and flexibility. The choice of grant type depends on the application type, the level of security required, and the user experience considerations.

Below, we’ll explore each grant type, explain how it works, and provide code examples where applicable. 

Authorization Code Grant (most scure for web apps and servers) 

The Authorization Code Grant is the most widely used and secure flow, primarily designed for web applications and backend servers. It introduces an intermediate authorization code that must be exchanged for an access token, preventing direct exposure of the token in the browser. 

How it works 

  • The client redirects the user to the authorization server for authentication;
  • After authentication, the authorization server sends an authorization code to the client;
  • The client exchanges the authorization code for an access token via a back-end request, ensuring that sensitive tokens are never exposed to the user’s browser. 

Example authorization request (user redirected to authorization server) 

http 

GET https://accounts.google.com/o/oauth2/auth? 

    response_type=code& 

    client_id=YOUR_CLIENT_ID& 

    redirect_uri=https://yourapp.com/callback& 

    scope=read_profile& 

    state=xyz 

Example Token Exchange Request (Server-side) 

http 

POST https://oauth2.googleapis.com/token 

Content-Type: application/x-www-form-urlencoded 

client_id=YOUR_CLIENT_ID& 

client_secret=YOUR_CLIENT_SECRET& 

grant_type=authorization_code& 

code=AUTHORIZATION_CODE& 

redirect_uri=https://yourapp.com/callback

Best use cases 

  • Ideal for web applications and backend services;
  • Provides strong security as the access token is never exposed to the browser;
  • Supports refresh tokens for session continuity. 

Implicit Grant (deprecated, used for single-page applications) 

The Implicit Grant is a simplified version of the Authorization Code Grant, used for Single-Page Applications (SPAs). Instead of exchanging an authorization code, the access token is immediately returned in the browser. 

How it works 

  • The client redirects the user to the authorization server;
  • After authentication, the authorization server immediately returns an access token in the URL. 

Example Authorization Request:

http

GET https://accounts.google.com/o/oauth2/auth? 

    response_type=token& 

    client_id=YOUR_CLIENT_ID& 

    redirect_uri=https://yourapp.com/callback& 

    scope=read_profile& 

    state=xyz

This approach eliminates the need for a backend server but is less secure because the access token is visible in the browser URL and can be intercepted. 

Best use cases 

  • Not recommended due to security concerns;
  • Consider using Authorization Code Grant with PKCE for SPAs instead. 

Password Grant (legacy, only for trusted applications) 

The Password Grant allows users to provide their username and password directly to the client application, which then exchanges them for an access token. This approach is less secure because the client application handles user credentials directly

How it works 

  • The user submits their credentials directly to the client application;
  • The client sends the credentials to the authorization server in exchange for an access token

Example token request 

http 

POST https://oauth2.googleapis.com/token 

Content-Type: application/x-www-form-urlencoded 

client_id=YOUR_CLIENT_ID& 

client_secret=YOUR_CLIENT_SECRET& 

grant_type=password& 

username=user@example.com& 

password=USER_PASSWORD

Security risks: the client must be fully trusted because it handles user credentials. 

Best use cases 

  • Suitable for internal applications where the client is highly trusted (e.g., company intranet);
  • Not recommended for public applications—use Authorization Code Grant instead. 

Client Credentials Grant (for Machine-to-Machine authentication) 

The Client Credentials Grant is used when an application acts on its own behalf, without user involvement. This is ideal for Machine-to-Machine (M2M) communication, where the client is also the resource owner

How it works 

  • The client authenticates with the authorization server using its client ID and secret;
  • The authorization server issues an access token

Example token request 

http 

POST https://oauth2.googleapis.com/token 

Content-Type: application/x-www-form-urlencoded 

client_id=YOUR_CLIENT_ID& 

client_secret=YOUR_CLIENT_SECRET& 

grant_type=client_credentials& 

scope=read_data

Best use cases 

  • Ideal for server-to-server communication (e.g., microservices, APIs);
  • Secure because no user credentials are involved

Device Grant (for devices without keyboards, e.g., Smart TVs) 

The Device Grant (also called Device Flow) is used for devices that lack a keyboard or browser, such as Smart TVs, game consoles, and IoT devices

How it works 

  • The client (device) requests an authorization code from the authorization server;
  • The authorization server provides a verification URL and a user code;
  • The user visits the verification URL on a separate device, enters the user code, and grants permission;
  • The device polls the authorization server to check if the user has completed authentication;
  • Once authorized, the device receives an access token

Example device code request 

http 

POST https://oauth2.googleapis.com/device/code 

Content-Type: application/x-www-form-urlencoded 

client_id=YOUR_CLIENT_ID& 

scope=read_profile 

Example Response: 

json 

{ 

  "device_code": "4/Jb34E", 

  "user_code": "A1B2C3", 

  "verification_uri": "https://example.com/device", 

  "expires_in": 1800 

} 

The user then visits https://example.com/device, enters A1B2C3, and logs in. 

Meanwhile, the device continuously polls for authorization: 

http 

POST https://oauth2.googleapis.com/token 

Content-Type: application/x-www-form-urlencoded 

client_id=YOUR_CLIENT_ID& 

device_code=4/Jb34E& 

grant_type=urn:ietf:params:oauth:grant-type:device_code

Best use cases 

  • Ideal for Smart TVs, IoT devices, and game consoles
  • User authentication is done on a separate device, improving security. 

Choosing the right Grant type 

Grant type Security level Best for 
Authorization Code 🔒🔒🔒🔒🔒 Web apps, backend services 
Implicit (Deprecated) 🔒🔒⚠️ SPAs (Use PKCE instead) 
Password (Not Recommended) 🔒⚠️⚠️ Internal, trusted apps 
Client Credentials 🔒🔒🔒 Server-to-server communication 
Device Grant 🔒🔒🔒 IoT, Smart TVs, game consoles 

For modern applications, Authorization Code with PKCE is recommended for web and mobile apps, while Client Credentials is best for server-to-server authentication. 

OAuth 2.0 and native applications 

Native applications (mobile and desktop apps) also use OAuth 2.0 for authentication. Since these apps are installed directly on a device, they cannot securely store client secrets like web apps do. Instead, they rely on external authorization servers to handle authentication and obtain access tokens

The authentication process includes: 

  • The client app launches a browser to redirect users to the authorization server;
  • The user logs in and grants access;
  • The authorization server issues a temporary code;
  • The client app stores the token securely and uses it for API requests. 

This approach provides greater security and improves the user experience through Single Sign-On.

Conclusion 

OAuth 2.0 is essential for online security and privacy, enabling secure authentication without exposing user credentials. Through the use of access tokens and refresh tokens, it improves data protection and simplifies access to protected resources.

As the protocol continues to develop, the evolution of OAuth 2.0 and the future OAuth 3.0 version will bring further improvements to address new digital security challenges.


Questions and answers

  1. What is OAuth 2.0 used for? 
    OAuth 2.0 is used for secure authentication and authorization, allowing users to grant access to their data without sharing their credentials. 
  2. How is OAuth 2.0 different from OAuth 1.0? 
    OAuth 2.0 simplifies authentication, improves support for native applications, introduces refresh tokens, and provides flexible grant types for various use cases. 
  3. What is an access token in OAuth 2.0? 
    An access token is a temporary credential that allows an application to access protected resources on behalf of the user. 
  4. What is a refresh token? 
    A refresh token is used to request a new access token without requiring the user to log in again. 
  5. Is OAuth 2.0 secure? 
    Yes, OAuth 2.0 is secure when implemented correctly, but it requires careful handling of access tokens to prevent leaks and attacks. 
  6. What is the difference between an authorization server and a resource server? 
    The authorization server issues tokens, while the resource server verifies tokens and grants access to protected resources. 
  7. How does OAuth 2.0 improve security? 
    OAuth 2.0 eliminates password sharing, uses token-based authentication, and provides granular access control. 
  8. 8Can OAuth 2.0 be used for mobile apps? 
    Yes, OAuth 2.0 supports native applications, allowing mobile apps to authenticate users securely. 
  9. What is Single Sign-On (SSO) in OAuth 2.0? 
    SSO allows users to authenticate once and access multiple applications without logging in again. 
  10. What are OAuth 2.0 grant types? 
    OAuth 2.0 supports various grant types, including authorization code, implicit, password, client credentials, and device grant. 
To top