Table of Content
OAuth (Open Authorization) is a widely adopted protocol that enables secure and seamless authorization between third-party clients and services. It allows users to grant access to their resources on one platform without sharing their credentials, ensuring both convenience and security. The OAuth framework has become essential for modern applications, where different services need to interact with each other on behalf of users. In this article, we will explore what OAuth is, why it’s important, how it can be implemented, and how tools like Keycloak facilitate its adoption in real-world applications.
What is OAuth?
OAuth is a protocol/framework for authorization. It serves as a guideline for implementing authorization flows that allow third-party clients to access a service on behalf of a user.
Why OAuth?
To ensure secure authorization across various services, the method used depends on the security requirements of internal services. Authorization can be achieved either through traditional user credentials (email and password) or through a non-expiring API key assigned to the user.
How to implement OAuth?
Different paid and open-source tools help implement OAuth. Keycloak facilitates OAuth for authentication services, allowing us a quick start instead of having to implement OAuth entirely on our own.
A quick explanation of some terms used in the diagram and throughout the rest of the article:
Resource Owner: This refers to the user who authorizes the client to make requests on their behalf.
Client: This is the application used by the user, which can be a webpage or mobile app. The client utilizes permissions granted by the user to access protected services on their behalf.
Resource Server: This server hosts the protected resources, services, and APIs, often functioning as middleware. The middleware must be capable of granting access to the resources upon receiving a request with a valid access token.
Authorization Server: This server verifies the user and authorizes the client.
The client will authenticate against Keycloak using credentials (email/username and password) provided by them. Once authenticated, the client will receive a code that must be exchanged with Keycloak to obtain the appropriate access token. With this access token, the client can request protected resources from our server.
The resource server must use Keycloak to validate the access token, and if it is valid, allow the request to be fulfilled.
The client communicates directly with Keycloak to avoid security issues by preventing exposure of the resource server to unauthenticated users.
Keycloak Token Strategy
As mentioned before, the OAuth approach involves the use of tokens issued after a client has been properly authenticated and granted access to use the resource server.
There are several strategies for handling these tokens. In this case, we will discuss short-lived access tokens and long-lived refresh tokens. This approach allows for a balance between maximum security and flexibility. First, a quick explanation of these tokens:
The access token is used to access the protected resources when making a request. It expires every certain time and must be renewed. This time can be setup on Keycloak’s Manager Console.
This access token is a JSON Web Token (JWT)–an open standard (RFC 7519) that defines a compact and self-contained way to securely transmit information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret with the HMAC algorithm or a public/private key pair using RSA.
The refresh token is used to obtain a new access token when the previous one expires. It also has an expiration but typically lasts much longer than the access token. Once it expires, the client must be reauthorized by the user.
So, returning to the strategy, Keycloak will issue access tokens that last for a specific period of time. Then, using the refresh token, the client will need to renew the access token. Once the refresh token expires, the client must be reauthorized by the user by going through the entire authentication flow.
Keycloak User Database
Luckily for us, Keycloak offers the option to use either our own database instance or theirs. Keycloak’s user database provides functionality to add extra attributes, allowing us to centralize all user information in one place. If we opt for our own database instance, we will need to add our own user fields as required.
Keycloak Authorization Flow
Here is a diagram that outlines the flow every client must follow to authorize and grant access to the resource server.
- The user wants to use the client, initiating the login process.
- The client requests access from the authorization server.
- The authorization server requires the user to grant access to the client, initiating an authorization grant.
- The user grants access using their account credentials (email/username and password).
- The authorization server issues a code to the client; this code will be used to exchange for the appropriate tokens.
- The client requests the proper tokens from the authorization server using the code.
- Now the client is fully authorized to act on behalf of the user.
Keycloak Authorization Client
There are two options for authentication: the Login Web Page provided by Keycloak or Keycloak’s JavaScript Adapter. The Login Web Page handles the initial request to Keycloak, where the user’s credentials are validated, and the code for token exchange is returned.
The following example shows how to initialize the JavaScript Adapter. Ensure that you replace the options passed to the Keycloak constructor with those configured for your client.
import Keycloak from 'keycloak-js';
const keycloak = new Keycloak({
url: 'http://keycloak-server${kc_base_path}',
realm: 'myrealm',
clientId: 'myapp'
});
try {
const authenticated = await keycloak.init();
console.log(`User is ${authenticated ? 'authenticated' : 'not authenticated'}`);
} catch (error) {
console.error('Failed to initialize adapter:', error);
}
Refresh Access Token Flow
Here is a diagram that explains the flow every client must follow. This process is required every hour to refresh the access token.The client makes a request to the Authorization Server with the Refresh Token. The Authorization Server validates the Refresh Token and handles the response accordingly:
- If the token is valid, it generates a new Access Token, sets an expiration date for the token, and sends all this information back to the client.
- If the token is invalid, it sends an HTTP Authentication error. As before, this request is made directly to the Authorization Server to protect the Resource Server.
Protected Resource Request
Here is a diagram that explains the flow every client will follow to make a request to the Resource Server. For example, third-party services that require authentication can use an OpenID plugin. This allows us to implement Single Sign-On (SSO), sharing the user’s access token across services.
The client makes a request to the Resource Server using the access token obtained from the previous authentication flow. The Resource Server then validates the access token with the Authorization Server. Depending on the validity of the access token, one of the following actions will occur:
- If the access token is invalid, the Resource Server will reject the request with an authorization error.
- If the access token is valid, the Resource Server will attempt to fulfill the request.
- If credentials are required by the protected resource, the Resource Server will obtain the necessary credentials to make a request to the protected resource; otherwise, it will simply proceed with the request. This only occurs if the token is valid.
- Once the request has been fulfilled by the protected resource, the middleware processes the response as needed and fulfills the client’s request.
In summary, OAuth is a powerful tool that simplifies the process of managing secure access across various services. By using a solution like Keycloak, you can quickly implement OAuth without starting from scratch, ensuring your systems are both secure and manageable. The use of tokens—specifically, short-lived access tokens and long-lived refresh tokens—ensures that your authorization process is secure and flexible.
With Keycloak, you streamline the OAuth process and centralize user management, which helps keep everything organized and secure. Understanding how OAuth works and how Keycloak integrates into your security framework will equip you to protect your resources effectively while providing seamless access to users.
Conclusion
OAuth is an essential framework for securing authorization processes in today’s interconnected digital landscape. It ensures that third-party applications can interact with user resources without compromising security. By utilizing tools like Keycloak, organizations can streamline their OAuth implementation, focusing more on building their services rather than managing the complexities of authorization. With features such as token management and user databases, Keycloak simplifies the authorization flow, allowing for both flexibility and security in application development. Ultimately, OAuth, when properly implemented, strikes a balance between user convenience and data protection.