JSON Web Tokens

 JSON Web Tokens (JWT)


  A JSON Web Token (JWT) is commonly used for authentication and authorization in web applications and APIs. Essentially, JWTs encode info about a user or entity into a JSON object, which is then digitally signed and/or encrypted. 

A JWT consists of three parts, separated by dots (.): 

1. Header: Contains metadata about the token, such as the signing algorithm (e.g., HMAC SHA256, RSA SHA256) and the token type (JWT). 

2. Payload: Contains the claims, which are statements about an entity (e.g., user ID, role, expiration time).  

3. Signature: Verify that the JWT sender is who they claim to be and that the message hasn't been tampered with. 


How it works:

  Authentication: A user logs in, and the server creates a JWT containing user info and other relevant claims. 

  Token Transmission: The server sends the JWT to the client (e.g., browser). 

  Subsequent Requests: The client includes the JWT in the authorization header of subsequent requests to the server. 

  Verify: The server verifies the JWT's signature to ensure its authenticity and integrity. 

  Authorization: If the JWT is valid, the server grants access to the requested resource. 


Benefits of JWTs:

  Stateless Authentication: Reduces server load and improves scalability as the server doesn't need to maintain session info. 

  Secure Data Exchange: The digital signature ensures that the data hasn't been tampered with during transmission. 

  Cross-Domain Authentication: JWTs can be used to authenticate users across different domains or services. 

  Reduced Database Load: By storing user info within the token, the need for database lookups is minimized. 


JWT Auth API in ASP.NET Core

  Register/login with in-memory or EF Core DB

  Return JWT with expiration + roles

  Protect an endpoint with [Authorize(Roles = "Admin")]

  Add refresh token logic for bonus points


Use Postman for testing the examples.

Use JWT IO for verification: https://jwt.io/


I would use File > New Project > ASP Core Web Api.

1) Add Nuget package: search using JwtBearer.

2) Click "Manage User Secrets" on the API project and then add "JWT:Secret". This creates a Secrets.Json file that you add "JWT:Secret" to.


3) Add a TokenProvider class that inherits from IConfiguration. 

    Add Create() method passing User parameter.  This assumes User object exists. 

    In this new Create(), do a bunch of coding:  


4) In the Handle() of LoginUser class, adjust this to call to the Create() of TokenProvider and return the string token.


5) Register token provider by doing:    builder.Services.AddSingleton<TokenProvider>()  where builder is built.

6) Add to appSettings.json parent and child.   The various Jwt settings.

7) Then verify at JWT.IO

8) Add to builder.services building doing this after TokenProvider:



9) Add the AddAuthorization() in the midst of the builder.GetMaps .

10) Add a new CS file with an extension for Swagger:

I like Milan's video for adding JWT to existing .NET 8 project ( https://www.youtube.com/watch?v=6DWJIyipxzw&ab_channel=MilanJovanovi%C4%87 ).










Comments

Popular posts from this blog

Upgrading to .NET8 from desktop versions 4.8.X

GHL > Set website so shorter URL address