Jumpstarting ORDS REST API Development: A Comprehensive Guide for Beginners - Part 2

In the part 1 of this blog series, we covered the creation of a REST API in Oracle REST Data Services (ORDS). Now, it's time to dive into the crucial aspect of securing our APIs using OAuth2.

OAuth2 is an industry-standard protocol used for authorization and authentication in modern web and mobile applications. It provides a secure and standardized way to protect our APIs, ensuring that only authorized clients can access the protected resources. Understanding OAuth2 is essential for developers and architects who want to build secure and reliable APIs.

In this blog post, we will start by explaining the core concepts of OAuth2 in simple terms. We will break down the OAuth2 roles, such as the resource owner, client, and authorization server, and how they interact with each other to establish secure communication channels. By the end of this blog post, you will have a solid understanding of OAuth2 and its relevance in securing REST APIs. 

So, let's get started and first understand what is Oauth2.

As per this article, OAuth 2.0, which stands for “Open Authorization”, is a standard designed to allow a website or application to access resources hosted by other web apps on behalf of a user. It replaced OAuth 1.0 in 2012 and is now the de facto industry standard for online authorization. 

OAuth2 involves several roles that interact with each other to enable secure and delegated access to protected resources. Here are the key roles in OAuth2:

Resource Owner: The resource owner in OAuth2 refers to the user or entity that owns the protected resources, such as personal data or assets, and has the ability to grant or deny access to those resources. In our case, the protected resource is REST module. 

Client:  The term "client" refers to the application or service that is requesting access to the protected resources (REST Module). The client can be a web application, a mobile app, a desktop application, or any other type of software that wants to interact with our REST service. 

Authorization Server:  The authorization server is a crucial component of the protocol. The Authorization Server acts as a middleman between the Client and the Resource Owner. When the Client wants to access certain resources, it asks the Authorization Server for permission by requesting an Access Token. The Authorization Server then checks if the Client is authenticated and if the Resource Owner has given consent. If both conditions are met, the Authorization Server issues an Access Token to the Client, allowing it to access the requested resources.

Resource Server: A server that protects the user’s resources and receives access requests from the Client. It accepts and validates an Access Token from the Client and returns the appropriate resources to it.

In some cases, the resource server and the authorization server may be hosted in separate data centers. However, in our scenario, both the resource owner and the authorization owner roles are fulfilled by the same entity, which is our database server. It contains the protected resources (REST Module) and also handles the authentication, authorization, and access token issuance processes. The client interacts with the database server to request access to the protected resources and receives access tokens from the server.

OAuth2 supports several different flows or grant types, each designed for specific use cases. Here we'll focus on Client Credential Flow. 

OAuth2 Client Credential Flow is a mechanism used for obtaining access tokens in the OAuth2 framework. This flow is commonly used in server-to-server communication scenarios, where the Client needs to authenticate and obtain an access token without involving a specific user.

In the Client Credential Flow, the client application directly exchanges its own credentials with the authorization server to obtain an access token. The flow does not involve user authentication or authorization, as the client application is acting on its own behalf.

Here's a step-by-step explanation of the Client Credential Flow:

1. Client Application Registration: The client application registers with the authorization server and receives a client ID and client secret. These credentials serve to identify and authenticate the client application.

2. Token Request: The client application sends a token request to the authorization server, including its client ID and client secret. This request typically includes the "client_credentials" grant type.

3. Client Authentication: The authorization server verifies the client application's credentials. If the credentials are valid, the authorization server proceeds with the token generation process.

4. Access Token Generation: Upon successful client authentication, the authorization server generates an access token. The access token represents the client application's authorization to access protected resources.

5. Token Response: The authorization server responds to the client application's token request with the access token, along with optional additional information such as token expiration time and scope.

6. Accessing Protected Resources: The client application includes the access token in the headers or requests to access protected resources. The protected resource server verifies the access token to ensure the client application's authorization.

Now let's understand what steps we need to take in order to protect our REST Module and enable it for Oauth2.

1. Define REST Module.

2. Create a Role

3. Create Privilege and establish the associations between the REST Module, Role, and Privilege

We have already defined our REST module "hr/v2/" in part 1.

Create Role

As shown in below image, we have created "inaoug.demo.role" role.

 Create Privilege

As shown in below image, we have created "inaoug.demo.privilege" and associated with both the "inaoug.demo.role" role and the "hr/v2/" module.

At this stage, our REST Module is protected, and if you attempt to access it without proper authorization, you will receive a "401 Unauthorized" error. This error indicates that the requested resource requires authentication, and you need valid credentials to access it.

To access this protected REST service, the first step is to generate a Client ID and Client Secret. This step is also called Client Application Registration. Since ORDS or Oracle APEX does not provide any GUI for this step yet, we need to generate this using below code.

-- Create Client
BEGIN
    
    OAUTH.create_client(
         p_name            => 'rutvik.prajapati',
         p_grant_type      => 'client_credentials',
         p_owner           => 'WKSP_WS1',
         p_description     => 'Internal client to access agreement API',
         p_support_email   => 'rutveek@gmail.com',
         p_privilege_names => 'inaoug.demo.privilege' );
     COMMIT;
END;
/

--Assign a Role to Client

BEGIN

    OAUTH.grant_client_role(
        p_client_name => 'rutvik.prajapati',
        p_role_name   => 'inaoug.demo.role' );

    COMMIT;
END;
Please note that, the Grant Type is "client_credentials", and it is important to ensure that the same privilege and role name used earlier to protect the REST module are provided. This ensures that the client requesting access is authenticated and authorized based on the previously defined role and privilege settings.

To obtain the client ID and client secret, you can use the following query. These credentials will be used to request an access token
--get client id and secret

SELECT NAME,
       DESCRIPTION,
       CLIENT_ID,
       CLIENT_SECRET
FROM ords_metadata.user_ords_clients 
WHERE NAME = 'rutvik.prajapati';


Once you have the client ID and client secret, you can use them in your OAuth2 authentication flow to request an access token from the authorization server. This access token will be required for subsequent API requests to the protected resources.

To generate an access token, you need the access token URL. The standard format for the ORDS access token URL is as follows:

http(s)://<server>/<ords_alias>/<schema_alias>/oauth/token

Replace <server>, <ords_alias>, and <schema_alias> with the actual URL of your ORDS server, ords alias and your schema alias. This endpoint is used to request an access token by providing the necessary authentication details and parameters.

Now let's see how to test our protected REST API using Postman.

Open Postman and locate the "Authorization" tab in the request builder. Within the "Authorization" tab, select "OAuth 2.0" as the authorization type.


Configure the OAuth 2.0 settings in the "Configure New Token" window, enter the required parameters such as the token URL, client ID, client secret, and other relevant details. Once the OAuth 2.0 parameters are set, click on the "Get New Access Token" button.

Postman will retrieve the access token and display it in the "MANAGE |ACCESS TOKEN" popup window.  Click "Use Token" to automatically include the access token in the request's authorization header.


 You can verify the Authorization parameters in the "Headers" tab in Postman.


Click the "Send" button to execute the API request, and you will receive the response from the protected REST API.
 

In this blog post, we explored the process of protecting a REST Module using OAuth 2.0 and demonstrated how to invoke the protected REST API using Postman. By following the steps outlined, we learned how to define the module, create roles and privileges, and link them together to establish access control. We also discussed the importance of generating client credentials and obtaining an access token for authentication.

In the next part of this series, we will delve into invoking the OAuth2 protected REST API using PL/SQL. This will allow us to leverage the power of PL/SQL to interact with the protected resources and perform various operations.

Comments

Popular posts from this blog

Sorting Order in Oracle APEX Classic Report

Multi-select List Item in Oracle APEX | Checkbox Group

OTP based Authentication in Oracle APEX using Twilio