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:
- The server issues a JWT after validating the user's credentials.
- The client includes the JWT in subsequent requests to prove their identity.
- The server validates the JWT (checks the signature, expiration, etc.) to confirm the identity of the user and allows access to resources.
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:
- After authentication, the JWT can include claims like roles or permissions (e.g., admin, user, etc.).
- 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.
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)
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.
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,
- t_token Record
- ENCODE Function
- DECODE Function
- VALIDATE Procedure
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;