How to check validity of token?

Namrata
7 min readMay 25, 2024

--

Determining the absence of a valid session or authentication token is a crucial step for the Service Provider (SP) to decide whether to redirect the user to the Identity Provider (IdP) for authentication. Here’s how this determination is typically made:

Checking for a Valid Session or Authentication Token

Session Cookies:

What It Is ?

When a user successfully logs into an SP, the SP usually creates a session for the user and stores a session identifier in a cookie on the user’s browser.

How It Works?

  • Request Handling: When the user requests a resource, the browser automatically sends the session cookie along with the HTTP request.
  • Session Validation: The SP checks the session identifier in the cookie against its session store (e.g., a database or in-memory store) to see if there is an active session for the user.

Outcome:

  • Valid Session: If the session is valid and active, the SP allows the user to access the resource.
  • Invalid or No Session: If the session is missing, expired, or invalid, the SP determines that the user is not authenticated.

How is signature created?

Creating a digital signature using RSA involves several steps. RSA (Rivest–Shamir–Adleman) is an asymmetric cryptographic algorithm, meaning it uses a pair of keys: a private key for signing and a public key for verification. Here’s a detailed explanation of how a signature is created using RSA, especially in the context of a JSON Web Token (JWT).

Steps to Create a Signature Using RSA

  1. Generate RSA Key Pair:
    If you don’t already have an RSA key pair, you need to generate one. This typically involves creating a private key and deriving the corresponding public key.
  2. Prepare the Data to Sign:
    For a JWT, the data to sign is the concatenation of the Base64Url-encoded header and payload, separated by a period (.).
  3. Hash the Data:
    The data to sign is hashed using a cryptographic hash function (e.g., SHA-256). This produces a fixed-size hash value (digest) of the data.
  4. Encrypt the Hash with the Private Key:
    The hash value is then encrypted using the RSA private key. This encrypted hash is the digital signature.

Authentication Tokens:

What It Is?

In some cases, especially in modern web applications, authentication is handled using tokens (e.g., JSON Web Tokens — JWTs) instead of traditional session cookies.

How It Works:

Token Inclusion

The token is typically included in the HTTP request headers (e.g., the Authorization header) or as a query parameter.

Token Validation

The SP validates the token by:

  1. Signature Verification: Checking the token’s digital signature to ensure it was issued by a trusted authority and has not been tampered with.
  2. Expiration Check: Ensuring the token has not expired by checking the exp (expiration) claim.
  3. Other Claims: Optionally checking other claims within the token, such as issuer (iss), audience (aud), and user information.

Outcome:

  • Valid Token: If the token is valid, the SP allows the user to access the resource.
  • Invalid or No Token: If the token is missing, expired, or invalid, the SP determines that the user is not authenticated.

How signature verification of token takes place?

Signature verification is a critical process in ensuring the integrity and authenticity of tokens, such as JSON Web Tokens (JWTs), in the context of authentication and authorization. Here’s a detailed explanation of how signature verification works:

Components of a JWT

A JWT typically consists of three parts:

  1. Header: Contains metadata about the token, including the type of token (JWT) and the signing algorithm (e.g., HMAC SHA256, RSA).
  2. Payload: Contains the claims, which are statements about the user and additional data.
  3. Signature: Ensures the token hasn’t been altered and verifies its authenticity.

The JWT is usually represented as a Base64Url-encoded string in the format:

header.payload.signature

Steps for Signature Verification

Extract and Decode:

The JWT is split into its components (header, payload, signature), and the header and payload are Base64Url-decoded to get the original JSON objects.

Reconstruct Data:
The data to verify is reconstructed by concatenating the Base64Url-encoded header and payload with a period (.) in between. This is the exact same data that was signed originally.

Hashing and RSA Verification:

  • The public_key.verify() function takes the signature, the reconstructed data, and specifies the padding and hash algorithm.
  • Internally, this function hashes the reconstructed data using SHA-256, then uses the RSA public key to decrypt the signature and compare it to the hash. If they match, the signature is valid.

How is SP getting public key for RSA?

When it comes to RSA signature verification, the Service Provider (SP) needs the public key to verify the signature of the token. The private key, used to sign the token, is securely held by the Identity Provider (IdP). Here’s how the SP typically obtains the public key for RSA signature verification:

Obtaining and Managing RSA Keys

1. Key Generation

  • Private Key: The private key is generated and securely stored by the entity responsible for signing the tokens or assertions. This is typically the IdP.
  • Public Key: The corresponding public key is derived from the private key and is intended to be shared with the SP.

2. Key Distribution

Metadata Exchange

In SAML, the exchange of public keys often happens through metadata files. Both the IdP and SP publish metadata files that include their public keys, endpoints, and other configuration details.

  • IdP Metadata: The IdP’s metadata file includes the IdP’s public key, which the SP uses to verify the signatures of SAML assertions.
  • SP Metadata: The SP’s metadata file includes the SP’s public key, which the IdP uses to encrypt assertions or sign AuthnRequests if needed.

Direct Configuration: In some cases, the public key may be directly configured in the SP’s settings or provided via a secure channel.

Why MITM Attack with Public Key Replacement is Difficult

Public Key Distribution and Trust:

Public keys are typically distributed through trusted channels. For example, in HTTPS, the public key is part of a digital certificate issued by a Certificate Authority (CA).

CAs verify the identity of the entity requesting the certificate and sign the certificate with their own private key. Browsers and other clients trust these CAs and can verify the authenticity of the certificate.

If an attacker tries to replace the public key, they will also need to forge a valid certificate from a trusted CA, which is practically infeasible without compromising the CA itself.

Digital Certificates:

  • Digital certificates bind public keys to the identities of entities (e.g., websites, organizations). They are signed by trusted CAs.
  • When a client receives a public key, it also receives the certificate, which includes the CA’s signature. The client verifies the certificate using the CA’s public key, which is pre-installed in the client’s trust store.
  • If an attacker replaces the public key, they would need to provide a certificate signed by a trusted CA. Since CAs do not sign certificates without proper verification, this prevents unauthorized public key replacement.

Integrity and Authenticity:

  • Even if an attacker could replace the public key, they would need to sign the payload with the corresponding private key.
  • The client would then verify the signature using the attacker’s public key. However, since the public key is not trusted and its certificate is not valid, the client would reject the signature.

What are claims in JWT ?

When dealing with authentication tokens, especially JSON Web Tokens (JWTs), it’s important to understand the various claims that can be included within the token. These claims provide additional information about the token and the authenticated user. Here’s a detailed explanation of some of the key claims, including issuer (iss), audience (aud), and user information.

Key JWT Claims

Issuer (iss)

  • Definition: The iss claim identifies the principal that issued the JWT. This is typically the authentication server or Identity Provider (IdP).
  • Purpose: Ensures that the token was issued by a trusted authority.
  • Validation: The Service Provider (SP) checks the iss claim against a list of trusted issuers. If the iss claim does not match any of the trusted issuers, the token is considered invalid.

Example:

{   "iss": "https://idp.example.com" }

Audience (aud):

  • Definition: The aud claim identifies the recipients that the JWT is intended for. This is usually the SP or a specific application.
  • Purpose: Ensures that the token is intended for the SP and not for some other service.
  • Validation: The SP checks the aud claim to ensure it matches the SP’s identifier. If the aud claim does not match, the token is considered invalid.

Example:

{   "aud": "https://sp.example.com" }

Expiration (exp):

  • Definition: The exp claim identifies the expiration time on or after which the JWT must not be accepted for processing.
  • Purpose: Prevents the use of old, expired tokens.
  • Validation: The SP checks the current time against the exp claim. If the token is expired, it is considered invalid.

Example:

{   "exp": 1716854400  // Unix timestamp for expiration date }

User Information Claims

Subject (sub):

  • Definition: The sub claim identifies the principal (user) that is the subject of the JWT.
  • Purpose: Provides a unique identifier for the user.

Example:

{   "sub": "user123" }

Name (name):

  • Definition: The name claim provides the full name of the user.
  • Purpose: Useful for displaying the user’s name in the application.
  • Example:
{   "name": "John Doe" }

Email (email):

  • Definition: The email claim provides the email address of the user.
  • Purpose: Can be used for communication or as a unique identifier.

Example:

{   "email": "john.doe@example.com" }

Roles (roles):

  • Definition: The roles claim provides the roles assigned to the user.
  • Purpose: Used for authorization purposes to determine what actions the user can perform.

Example:

{   "roles": ["admin", "user"] }

Example JWT Payload

Here’s an example of a JWT payload containing these claims:

{
"iss": "https://idp.example.com",
"aud": "https://sp.example.com",
"exp": 1716854400,
"sub": "user123",
"name": "John Doe",
"email": "john.doe@example.com",
"roles": ["admin", "user"]
}

--

--

Namrata
Namrata

Written by Namrata

Engineering @Microsoft A software developer writing her daily bits . https://www.linkedin.com/in/namrataagarwal5/

No responses yet