Showing posts with label jwtToken. Show all posts
Showing posts with label jwtToken. Show all posts

Wednesday, 20 November 2024

Claim in jwt authentication token

 In JWT (JSON Web Token) authentication, a claim is a piece of information that is encoded within the token. Claims represent statements about an entity (usually the user) and additional metadata. Claims are used to convey information that is relevant to the authentication or authorization process.

A JWT typically contains three parts: the header, the payload, and the signature. The claims are part of the payload.

Types of Claims in JWT

There are three types of claims in a JWT:

  1. Registered Claims: These are predefined claims that are not mandatory but recommended to use for common functionalities. Some of the registered claims include:

    • iss (Issuer): Identifies the principal that issued the JWT.
    • sub (Subject): Identifies the subject of the JWT (usually the user).
    • aud (Audience): Identifies the intended recipient(s) of the JWT.
    • exp (Expiration Time): The expiration time of the JWT, after which it should not be accepted.
    • nbf (Not Before): The time before which the token should not be accepted.
    • iat (Issued At): The time when the token was issued.
    • jti (JWT ID): A unique identifier for the JWT.
  2. Public Claims: These are custom claims that can be defined by anyone, but they should be registered in the IANA JSON Web Token Claims registry or be chosen carefully to avoid conflicts with other claims. These claims often contain information about the user, such as their roles, permissions, or other application-specific data.

  3. Private Claims: These are custom claims created to share information between the parties that agree on them. These are typically not registered or standardized, and they are meant to be used internally between the issuer and the consumer of the JWT.

Example of Claims in JWT Payload

Here is an example of a JWT payload with some claims:

{
    "iss": "example.com",         // Issuer
    "sub": "1234567890",           // Subject (user ID)
    "aud": "exampleApp",           // Audience
    "exp": 1625123456,             // Expiration time (timestamp)
    "iat": 1625113456,             // Issued at (timestamp)
    "role": "admin",               // Custom claim (e.g., user role)
    "username": "john_doe"         // Custom claim (e.g., username)
  }

In this example:

  • iss indicates the issuer of the token.
  • sub identifies the subject (user) of the token.
  • aud specifies the audience for whom the token is intended.
  • exp specifies when the token expires.
  • iat is the timestamp when the token was issued.
  • role and username are private, custom claims used in this specific application.

How Claims Are Used

  • Authentication: Claims like sub (subject) are used to identify the user or entity for which the token was issued.
  • Authorization: Claims like role can be used to check what actions the user is authorized to perform.
  • Token Integrity: Claims like exp (expiration) ensure that the token cannot be used after a certain time.

Claims allow JWT tokens to be versatile and carry various types of information that can be validated and used for access control, personalization, and ensuring the security of the token.


Continue Reading →

What information JWT token contains

JWT (JSON Web Token) is a compact, URL-safe token format used for securely transmitting information between parties. In the context of a Web API, a JWT typically contains three main parts:

1. Header:

  • The header typically consists of two parts:
    • Type: This is usually "JWT" to indicate the token format.
    • Algorithm: The algorithm used for signing the token, such as HS256 (HMAC SHA-256) or RS256 (RSA SHA-256). The algorithm ensures the integrity of the token and prevents it from being tampered with.

Example of a header:

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

2. Payload:

  • The payload contains the claims or the information being transmitted. There are three types of claims:
    • Registered Claims: These are predefined claims that are recommended to use, but not mandatory. Examples include:
      • iss (Issuer): The entity that issued the token.
      • sub (Subject): The subject or user the token is about.
      • aud (Audience): The intended recipient of the token.
      • exp (Expiration Time): The expiration time of the token (timestamp).
      • iat (Issued At): The timestamp when the token was issued.
      • nbf (Not Before): The timestamp before which the token should not be accepted.
      • jti (JWT ID): A unique identifier for the token.
    • Public Claims: These are claims that can be defined by anyone, but they should be collision-resistant (e.g., using a URI).
    • Private Claims: These are custom claims that are used between the issuer and the consumer (API server). These claims contain application-specific information, such as user roles, permissions, etc.

Example of a payload:

var claims = new[]
{
    new Claim(JwtRegisteredClaimNames.Sub, "userid"), // Registered Claims
    new Claim(JwtRegisteredClaimNames.Name, username), // Registered Claims
    new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
    new Claim("role", "admin"), // Custom Claims
    new Claim("email", "johndoe@example.com") // Custom Claims
};

3. Signature:

  • The signature is created by concatenating the encoded header and payload, and then signing them using the secret key (e.g., secretkey) and the algorithm (HS256).

Example process of creating the signature:

  • Take the encoded header and payload.
  • Concatenate them with a period (.) separator: header.payload.
  • Sign this concatenated string with the specified algorithm and secret key.
  • Base64Url encode the resulting signature.

The final JWT looks like:

header.payload.signature

Example of a Complete JWT:

A complete JWT token might look like this (note that these parts are base64url-encoded):

eyJhbGciOiAiSFMyNTYiLCJ0eXAiOiAiSl"..."...

Summary:

  • Header: Contains metadata like the algorithm and token type.
  • Payload: Contains the claims or information (such as user ID, roles, etc.).
  • Signature: Ensures the integrity of the token and verifies the sender’s identity.

In the context of Web APIs, JWTs are used to authenticate and authorize users, securely transmitting user data (like a user ID or roles) between the client and the server. The server can verify the authenticity of the JWT and extract relevant information to grant access to resources or perform other actions.



Continue Reading →

JWT Token Generation Code in C#

Install the required NuGet packages

You'll need the following packages in your C# project:

  • System.IdentityModel.Tokens.Jwt (for JWT token generation and validation)
  • Microsoft.IdentityModel.Tokens (for creating signing keys and algorithms)

Set up the JWT Token Generation Code

Here’s an example of how to generate a JWT token in C# using various options:

public string GenerateJwtToken(string username)
{
     // Define JWT claims
    var claims = new[]
    {
        new Claim(JwtRegisteredClaimNames.Sub, "userid"), // Registered Claims
        new Claim(JwtRegisteredClaimNames.Name, username), // Registered Claims
        new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
        new Claim("role", "admin"), // Custom Claims
        new Claim("email", "johndoe@example.com") // Custom Claims
    };

    //  Define the security key
    string secretKey = "your_secret_key_here";
    var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

     // Define the signing credentials (HMACSHA256 algorithm)
    var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

// Create jwt token
    var token = new JwtSecurityToken(
        issuer: "your-issuer", // Can be your app name
        audience: "your-audience", // Can be a target application or service
        claims: claims,
        expires: DateTime.Now.AddMinutes(30),
        signingCredentials: creds);

     // Serialize the token to a string
     var tokenHandler = new JwtSecurityTokenHandler();
     string jwtToken = tokenHandler.WriteToken(token);

    return jwtToken ;
}

Explanation of the Options Used:

  1. Security Key and Signing Credentials:

    • A secret key is used to sign the token. It's crucial to keep this key secure. We use the HMACSHA256 algorithm (SecurityAlgorithms.HmacSha256) to sign the token with the SymmetricSecurityKey.
  2. Claims:

    • Claims are used to include information about the user (e.g., sub, name) and other custom claims (e.g., role, email). Claims are represented as Claim objects.
  3. Issuer and Audience:

    • Issuer: The entity that issued the token, often the name of the app or service that generates the token.
    • Audience: The recipient(s) of the token, often a service or application that will validate the token.
  4. Expiration Time:

    • You can set the expiration time for the token using expires. The token will be invalid once the expiration date is reached.
  5. JWT Token Generation:

    • We use JwtSecurityToken to construct the JWT with all the provided information (issuer, audience, claims, expiration time, and signing credentials).
  6. Serialize the Token:

    • JwtSecurityTokenHandler is used to serialize the JwtSecurityToken object into a string that can be used as the actual JWT token.

3. Customization Options

You can customize the JWT further with the following options:

  1. Audience:

    • If your token is intended for a specific service or client, you can set the audience to that service's identifier.
  2. Signing Algorithms:

    • You can use different signing algorithms like HmacSha256, Rs256, Es256, etc., depending on your use case.

      Example for RSA or ECDSA signing:
      var rsaKey = new RsaSecurityKey(privateKey); // Private RSA key
      var signingCredentials = new SigningCredentials(rsaKey, SecurityAlgorithms.RsaSha256);
  3. Claims: JWT tokens allow you to add custom claims (e.g., roles, permissions, etc.). You can add any additional claim that might be useful for your system's authorization.

  4. NotBefore (nbf): Set the NotBefore claim to indicate that the token is not valid before a certain time: 
    nbf: DateTime.UtcNow.AddMinutes(1)
  5. Issuer & Audience Validation:

    • On the validation side, when you decode the token, you can specify the allowed Issuer and Audience values to ensure that the token is intended for your service.
  6. Example of Token Validation:

    Once you have generated the token, you would typically validate it on the receiving side:

var tokenHandler = new JwtSecurityTokenHandler();
var validationParameters = new TokenValidationParameters
{
    ValidateIssuer = true,
    ValidateAudience = true,
    ValidateLifetime = true,
    ValidIssuer = "your-issuer",
    ValidAudience = "your-audience",
    IssuerSigningKey = symmetricKey // Same key used to sign the token
};

try
{
    var principal = tokenHandler.ValidateToken(jwtToken, validationParameters,
out SecurityToken validatedToken);
    Console.WriteLine("Token is valid.");
}
catch (SecurityTokenException ex)
{
    Console.WriteLine("Token validation failed: " + ex.Message);
}

Conclusion

By following this approach, you can generate a highly customizable JWT token in C# using multiple options, such as custom claims, signing algorithms, and expiration times. You can further extend this with more advanced features like refreshing tokens, audience validation, and different signing algorithms for more complex security needs.


Continue Reading →

Sunday, 22 January 2023

JWT authentication in ASP.NET Core WebAPI

Using JWT (JSON Web Tokens) in a Web API is a common approach for handling authentication and authorization. Here's a concise guide on how to implement JWT in a Web API, typically using a framework like ASP.NET Core, but the principles apply to other frameworks as well.

Step 1: Install Necessary Packages

For ASP.NET Core, you'll need to install the following NuGet packages:

  1. Microsoft.AspNetCore.Authentication.JwtBearer
  2. System.IdentityModel.Tokens.Jwt

Step 2: Configure JWT in Startup

In your Startup.cs file, configure JWT authentication in the ConfigureServices method:

public void ConfigureServices(IServiceCollection services)
{
    // Other service configurations...

    var key = Encoding.ASCII.GetBytes("your_secret_key_here"); // Use a strong secret key
    services.AddAuthentication(x =>
    {
        x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    })
    .AddJwtBearer(x =>
    {
        x.RequireHttpsMetadata = false; // Set to true in production
        x.SaveToken = true;
        x.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(key),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

    services.AddControllers();
}

Step 3: Create a JWT Token

You'll need a method to generate the JWT. This typically occurs during login:

  public string GenerateJwtToken(string username)
  {
// Define JWT claims
      var claims = new[]
      {
          new Claim(JwtRegisteredClaimNames.Sub, userid), // Registered Claims
new Claim(JwtRegisteredClaimNames.Name, username), // Registered Claims
          new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim("role", "admin"), // Custom Claims
new Claim("email", "johndoe@example.com") // Custom Claims
      };
 
// Define the security key
string secretKey = "your_secret_key_here";
      var key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(secretKey));

// Define the signing credentials (HMACSHA256 algorithm)
      var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);
 
      var token = new JwtSecurityToken(
          issuer: "your-issuer", // Can be your app name
          audience: "your-audience", // Can be a target application or service
          claims: claims,
          expires: DateTime.Now.AddMinutes(30),
          signingCredentials: creds);
 
       // Serialize the token to a string
       var tokenHandler = new JwtSecurityTokenHandler();
       string jwtToken = tokenHandler.WriteToken(token);

      return jwtToken ;
  }

Step 4: Secure Your API Endpoints

Use the [Authorize] attribute to protect your API endpoints:

  [Authorize]
  [ApiController]
  [Route("[controller]")]
  public class WeatherForecastController : ControllerBase
  {
      [HttpGet]
      public IActionResult Get()
      {
          return Ok(new { Message = "This is a protected endpoint!" });
      }
  }

Step 5: Handling User Login

Create a login endpoint to authenticate users and return a JWT:

  [HttpPost("login")]
  public IActionResult Login([FromBody] LoginModel login)
  {
      // Validate user credentials (this is just an example)
      if (login.Username == "test" && login.Password == "password") // Replace with actual validation
      {
          var token = GenerateJwtToken(login.Username);
          return Ok(new { Token = token });
      }
 
      return Unauthorized();
  }

Step 6: Testing

Use a tool like Postman to test your endpoints:

  1. Call the login endpoint with valid credentials to receive a JWT.
  2. Use the received token in the Authorization header (Bearer <token>) when accessing protected endpoints.

Where jwt tokens are stored on on server

JWT (JSON Web Tokens) are typically not stored on the server in the same way as session data. Instead, they are often used in a stateless manner, meaning the server does not maintain a session for each user. Here’s how it generally works:

  1. Client-Side Storage: After authentication, the server sends the JWT to the client, which usually stores it in local storage or cookies.

  2. Stateless Authentication: Each time the client makes a request, it sends the JWT along (typically in the Authorization header). The server validates the token without needing to store any session data.

  3. Optional Revocation: If you need to implement token revocation or blacklisting, you might maintain a list of revoked tokens on the server, but this is an additional layer of complexity that somewhat counters the stateless principle.

  4. Expiry: JWTs usually have an expiration time, after which they are considered invalid. This reduces the need for server-side storage since expired tokens can be discarded.

In summary, JWTs are mainly stored client-side, while the server verifies them as needed.

How server verifies jwt token on server

To verify a JWT (JSON Web Token) on the server, the following steps are typically followed:

  1. Extract the Token: The server retrieves the JWT from the request, usually from the Authorization header as a Bearer token.

  2. Decode the Token: The server decodes the JWT to access its header and payload. This step does not require validation and can be done using a base64 decoding method.

  3. Verify the Signature: The most critical part of the verification process is to check the signature of the token:

    • The server uses the algorithm specified in the JWT header (e.g., HS256, RS256) and the secret key (for symmetric algorithms) or the public key (for asymmetric algorithms) that was used to sign the token.
    • It re-generates the signature using the header and payload and compares it with the signature part of the received token.
  4. Check Claims: The server validates the claims in the payload:

    • Expiration: Check the exp claim to see if the token is still valid.
    • Audience: Verify the aud claim to ensure the token was intended for your server.
    • Issuer: Check the iss claim to confirm it was issued by a trusted source.
    • Not Before: Optionally, check the nbf claim to see if the token is being used before its valid time.
  5. Process the Request: If the token is valid and all claims check out, the server processes the request. If not, it responds with an appropriate error (e.g., 401 Unauthorized).

Access token vs Refresh Token:

  1. Access Token (short-lived): This token is used for authenticating requests and is typically valid for a short duration (e.g., 15 minutes).
  2. Refresh Token (long-lived): This token is used to get a new access token when the old one expires. It typically has a longer expiry time (e.g., 7 days or more). 
What information JWT token contains

JWT Token Generation Code in C#
Click here

Claim in jwt authentication token
Click here

By following these steps, the server ensures that the JWT is valid, has not been tampered with, and is still active.


Reference: https://medium.com/https://www.c-sharpcorner.com/https://javascript.plainenglish.io/

Continue Reading →

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (47) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (55) CD (1) CI (2) CloudComputing (2) Coding (10) CQRS (1) CSS (2) Design_Pattern (7) DevOps (4) DI (3) Dotnet (10) DotnetCore (20) Entity Framework (5) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) jwtToken (4) Lamda (3) Linq (10) microservice (4) Mongodb (1) MVC (46) NodeJS (8) React (10) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (3) UI (1) UnitTest (2) WCF (14) Web Api (16) Web Service (1) XMl (1)

Dotnet Guru Archives