What is JWT (JSON Web Token) and APEX_JWT?

Oracle Application Express is a rapid development tool for Web applications on the Oracle database.
Post Reply
admin
Posts: 2082
Joined: Fri Mar 31, 2006 12:59 am
Location: Pakistan
Contact:

What is JWT (JSON Web Token) and APEX_JWT?

Post by admin »

In this article you will be learning about JWT and when and why to use it and then we will discuss and share sample code of using Oracle APEX standard features handling JWT encoding and decoding with easy and comfort.

Introduction to JWT (JSON Web Token)

JWT (JSON Web Token) is a compact, URL-safe means of representing claims to be transferred between two parties. It is often used in web applications for secure communication and authentication. JWTs are widely used for authorizing API requests, user authentication, and information exchange in a secure and compact format.

JWT (JSON Web Token) is primarily used for authentication and authorization, but they are slightly different purposes in the context of JWTs.

1. Authentication:
JWT is commonly used for authenticating a user. Authentication is the process of verifying the identity of the user or system. When a user logs in, they provide their credentials (e.g., username and password), and the server verifies those credentials. Upon successful authentication, the server generates a JWT and sends it back to the client.

How it works:
  1. The server issues a JWT after validating the user's credentials.
  2. The client includes the JWT in subsequent requests to prove their identity.
  3. The server validates the JWT (checks the signature, expiration, etc.) to confirm the identity of the user and allows access to resources.
2. Authorization:
Once authenticated, the JWT can also be used for authorization, which is the process of determining what actions or resources the user is allowed to access based on their identity and roles.

How it works:
  1. After authentication, the JWT can include claims like roles or permissions (e.g., admin, user, etc.).
  2. When the client makes an API request, the server can inspect these claims to determine if the user has the necessary privileges (authorization) to access a specific resource or perform an action.JWT (JSON Web Token) is primarily used for authentication and authorization, but they are slightly different purposes in the context of JWTs.
Note: APEX_JWT APIs only support HS256 symmetric encryption algorithm for claim signatures. Asymmetric encryption algorithms such as RS256 are not supported.

A JWT typically consists of three parts:

<Header>.<Payload>.<Signature>

Code: Select all

Header

{
  "alg": "HS256",
  "typ": "JWT"
}

Payload

{
  "iss": "example.com",
  "sub": "user123",
  "aud": "api.example.com",
  "exp": 1637157413
}

Signature

HMACSHA256(
  base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
These parts are separated by periods (.), making the format easy to transfer.

Uses of JWT:
Authentication: JWTs are commonly used for authentication in web applications. Once a user logs in (or signs up), a JWT is generated by the server and returned to the user. This token is then included in subsequent API requests to authenticate the user without needing to re-enter credentials.

Steps:
  • User logs in with credentials (username/password).
  • Server validates the credentials and generates a JWT.
  • User sends the JWT in the Authorization header of subsequent requests (typically as Bearer <token>).
  • The server validates the JWT on each request to authorize access.
  • Authorization: After successful authentication, the JWT can be used to control access to various resources based on the user's roles and permissions (encoded as claims in the JWT). For example, a JWT might contain a role claim, which allows the system to grant or deny access to certain parts of an application based on the user's role.
Information Exchange: JWTs can be used to securely exchange information between parties. Since the information is signed (and optionally encrypted), it ensures that the content hasn't been tampered with. For instance, a JWT can be used to send data between a server and a client, where both parties can trust that the data is valid.

Single Sign-On (SSO): JWT is commonly used in Single Sign-On systems. A user can log in once and get a JWT, which can then be used across different applications or services within the same trust domain.

Stateless Authentication: JWTs are often used in stateless authentication, where the server doesn't need to maintain session state. The token itself contains all the necessary information to authenticate and authorize a request (such as user ID, roles, and expiration time).

Advantages of JWT:
  • JWTs are small in size, making them ideal for transmission via HTTP headers, URL parameters, or cookies.
  • JWTs contain all the information needed to authenticate a user, meaning no need for additional database lookups.
  • The signature ensures the data has not been tampered with. Additionally, JWTs can be encrypted (e.g., JWE) for added security.
  • JWTs are JSON-based, so they are easily readable and compatible across different platforms and programming languages.
  • As JWTs are stateless, they enable scalable applications without needing a central session store.

Oracle APEX
The above can be generated and used by using Oracle PLSQL involving many steps but Oracle APEX make it more simple and easy providing package APEX_JWT with following options,
  1. t_token Record
  2. ENCODE Function
  3. DECODE Function
  4. VALIDATE Procedure
Oracle APEX 24.1 Documentation

Sample Code

Code: Select all

DECLARE
-- This code by ERPstuff.com is for training purpose only use of this in production will be based on user knowledge, requirements and testing.

    l_jwt_value VARCHAR2(32767);
    l_token     apex_jwt.t_token;
    l_payload   CLOB;
    l_issuer    VARCHAR2(1000);
    l_subject   VARCHAR2(1000);
    l_audience  VARCHAR2(1000);
    l_signature_key RAW(256);
    l_oauth2_client_id VARCHAR2(30) := 'Oracle Community'; -- Must match the JWT audience
    
BEGIN
    -- Convert the signature key to RAW format
    l_signature_key := utl_raw.cast_to_raw('SikandarHayat');

    -- Encode JWT with HS256 algorithm
    l_jwt_value := apex_jwt.encode (
                       p_iss           => 'ERPstuff',
                       p_sub           => 'info@erpstuff.com',
                       p_aud           => l_oauth2_client_id,
                       p_exp_sec       => 60*5,
                       p_signature_key => l_signature_key);

    dbms_output.put_line('Encoded JWT: ' || l_jwt_value);

    -- Decode JWT
    l_token := apex_jwt.decode(p_value => l_jwt_value);

    -- Print header, payload, and signature
    dbms_output.put_line('Header: ' || apex_json.stringify(l_token.header));
    dbms_output.put_line('Payload: ' || apex_json.stringify(l_token.payload));
    dbms_output.put_line('Signature: ' || l_token.signature);

    -- Extract the payload
    l_payload := l_token.payload;

    -- Parse the JSON payload
    apex_json.parse(p_source => l_payload);

    -- Extract individual claims
    l_issuer := apex_json.get_varchar2(p_path => 'iss');
    l_subject := apex_json.get_varchar2(p_path => 'sub');
    l_audience := apex_json.get_varchar2(p_path => 'aud');

    -- Print claims
    dbms_output.put_line('Issuer: ' || l_issuer);
    dbms_output.put_line('Subject: ' || l_subject);
    dbms_output.put_line('Audience: ' || l_audience);

    -- Validate the JWT
    apex_jwt.validate (
         p_token           => l_token,
         p_aud             => l_oauth2_client_id );

    dbms_output.put_line('JWT is valid.');

EXCEPTION
    WHEN OTHERS THEN
        dbms_output.put_line('Validation failed: ' || SQLERRM);

END;

swtapex.jpg
https://jwt.io/
jwt.jpg
You do not have the required permissions to view the files attached to this post.
Malik Sikandar Hayat
Oracle ACE Pro
info@erpstuff.com
Post Reply

Who is online

Users browsing this forum: No registered users and 0 guests