Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
35 views2 pages

JWT Tokens in .Net Core API

JWT (JSON Web Token) is used in .NET Core APIs for authentication and authorization, consisting of a header, payload, and signature. The process involves user login, token storage, and server validation through middleware. The document also provides examples of setting up JWT authentication and creating secured endpoints in a .NET Core API.

Uploaded by

Vijay Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views2 pages

JWT Tokens in .Net Core API

JWT (JSON Web Token) is used in .NET Core APIs for authentication and authorization, consisting of a header, payload, and signature. The process involves user login, token storage, and server validation through middleware. The document also provides examples of setting up JWT authentication and creating secured endpoints in a .NET Core API.

Uploaded by

Vijay Kumar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

### ✅ JWT Tokens in .

NET Core API – Explained Clearly

**JWT (JSON Web Token)** is a compact, URL-safe token used for securely
transmitting information between parties as a JSON object. In a .NET Core API, JWT
is commonly used for **authentication and authorization**.

### 🧱 Structure of a JWT


A JWT consists of **three parts**:
* **Header**: Type of the token (JWT) + signing algorithm (e.g., HS256)
* **Payload**: Claims (user info, roles, expiration, etc.)
* **Signature**: Created using a secret key (for verifying the token’s
authenticity)
### 🔐 How JWT Authentication Works in .NET Core API

#### 1. **User Logs In**

* The user sends their **username/password** to `/login`.


* If valid, the server creates a **JWT token** with user claims and sends it to the
client.

#### 2. **Client Stores Token**

* Usually stored in **localStorage** or **sessionStorage** in a browser.


* Sent on every API call using `Authorization: Bearer <token>` header.
#### 3. **Server Validates Token**
* Middleware checks for a valid token in the request.
* If valid, the request is allowed; else it returns `401 Unauthorized`.

### Example: Setting Up JWT in .NET Core API

#### **1. Add NuGet Package**

dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer

#### **2. Configure JWT Authentication (in `Program.cs` / `Startup.cs`)**

builder.Services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = "myapi.com",
ValidAudience = "myapi.com",
IssuerSigningKey = new
SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecretKey"))
};
});
#### **3. Enable Authentication Middleware**

app.UseAuthentication();
app.UseAuthorization();
#### **4. Generate Token (e.g., in `AuthController`)**

[HttpPost("login")]
public IActionResult Login([FromBody] LoginModel user)
{
if (user.Username == "admin" && user.Password == "pass123")
{
var claims = new[]
{
new Claim(ClaimTypes.Name, user.Username),
new Claim(ClaimTypes.Role, "Admin")
};

var key = new


SymmetricSecurityKey(Encoding.UTF8.GetBytes("MySuperSecretKey"));
var creds = new SigningCredentials(key, SecurityAlgorithms.HmacSha256);

var token = new JwtSecurityToken(


issuer: "myapi.com",
audience: "myapi.com",
claims: claims,
expires: DateTime.Now.AddHours(1),
signingCredentials: creds);

return Ok(new { token = new JwtSecurityTokenHandler().WriteToken(token) });


}

return Unauthorized();
}
### ✅ Example Secured Endpoint

[Authorize(Roles = "Admin")]
[HttpGet("secure-data")]
public IActionResult GetSecureData()
{
return Ok("This is protected data");
}
### 🔍 Summary

| Step | Purpose |
| ------------ | -------------------------------- |
| Login | User gets a JWT token |
| Store Token | Saved on client side |
| Use Token | Sent in request headers |
| Middleware | Validates and sets user context |
| \[Authorize] | Restricts access based on claims |

You might also like