Keycloak An Open Solution For OAuth

by Oct 15, 2024#Cloud, #DigitalTransformation, #HomePage

Printer Icon
f

Table of Content

  1. What is OAuth?
  2. Why OAuth?
  3. How to implement OAuth?
  4. Architecture with Keycloak
  5. Keycloak Token Strategy
  6. Keycloak User Database
  7. Keycloak Authorization Flow
  8. Keycloak Authorization Client
  9. Refresh Access Token Flow
  10. Protected Resource Request
  11. Conclusion

 

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.

 

Architecture with Keycloak

According to OAuth guidelines, this is how communication across the services will be structured.

Architecture with Keycloak

 

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.

Keycloak Authorization Flow

  • 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);
}

Alternatively, you can use a library wrapper that utilizes keycloak-js for your preferred client framework. For instance, Flutter offers a library that wraps the JavaScript adapter, known as keycloak_flutter. Additionally, Keycloak supports hybrid mobile apps developed with Apache Cordova.

 

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.

Refresh Access Token Flow

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.

Protected Resource Request

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:

  1. If the access token is invalid, the Resource Server will reject the request with an authorization error.
  2. If the access token is valid, the Resource Server will attempt to fulfill the request.
  3. 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.
  4. 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.

About Us: Krasamo is a mobile-first Cloud Computing and consulting company focused on the Internet-of-Things and Digital Transformation.

Click here to learn more about our cloud consulting services.

RELATED BLOG POSTS

Cloud Computing Fundamental Concepts

Cloud Computing Fundamental Concepts

Cloud Computing is an IT environment where applications run and resources are shared across networks—using computer servers, virtualization, or containers—with on-demand provisioning of resources.

Cloud Adoption Efforts Drive High Performance

Cloud Adoption Efforts Drive High Performance

Cloud adoption enables the right technologies and processes in cloud environments required to operate efficiently in the digital world. In addition, a modern operating model with the correct implementation of cloud services creates real competitive advantages.