0% found this document useful (0 votes)
37 views12 pages

Integrating JWT To .NET 8. Note - This Is A Very Simplistic and Not - by Amund Fremming - Medium

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

Integrating JWT To .NET 8. Note - This Is A Very Simplistic and Not - by Amund Fremming - Medium

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

7/9/24, 7:00 Integrating JWT to .NET 8.

Note: This is a very simplistic and not… | by Amund Fremming | Medium

Get unlimited access to the best of Medium for less than $1/week. Become a member

Integrating JWT to .NET 8


Open in app

Amund Fremming · Follow


4 min read · Feb 7,Search
2024

Listen Share More

Note: This is a very simplistic and not minimal secure way of setting up JWT.

Step 1— Installing packages


First off you need to install some NuGet packages.

dotnet add package Microsoft.AspCore.Authentication.JwtBearer

dotnet add package System.IdentityModel.Tokens.Jwt

Step 2— Creating classes


You need to create some classes for handling login requests, registration requests
and authorization response. You also need some sort of user.

using System.ComponentModel.DataAnnotations;

namespace Auth;

public class LoginRequest


{
[Required]
[EmailAddress]
public string Email { get; set; }

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 1/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

[Required]
public string Password { get; set; }
}

using System.ComponentModel.DataAnnotations;

namespace Auth;

public class RegistrationRequest


{
[Required]
public string UserID { get; set; }

[Required]
public string Username { get; set; }

[Required]
public string Firstname { get; set; }

[Required]
public string Lastname { get; set; }

[Required]
[EmailAddress]
public string Email { get; set; }

[Required]
public string Password { get; set; }
}

namespace Auth;

public class AuthResponse


{
public string UserId { get; set; }
public string Username { get; set; }
public string Token { get; set; }
public string? ProfileImage { get; set; }
}

Step 3— Creating Controllers


When we have created our classes we need to implement logic for registering users,
and also logging in. I will skip the logic for creating users and just use my services in

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 2/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

my examples, you need to do this yourself.

[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegistrationRequest reques
{
var salt = GenerateSalt();
var saltedPassword = request.Password + salt;

var user = new User


{
Firstname = request.Firstname,
Lastname = request.Lastname,
Email = request.Email,
Password = _passwordHasher.HashPassword(null, saltedPassword), // Nu
Salt = salt,
Role = Enums.Role.USER
};

await _userService.CreateUser(user);
var token = _tokenService.CreateToken(user);

return Ok(new AuthResponse { Token = token });


}

[HttpPost("login")]
public async Task<IActionResult> Login([FromBody] LoginRequest request)
{
User? user = await _userService.FindByEmailAsync(request.Email);

if (user == null)
{
return Unauthorized("Invalid credentials 1");
}

var saltedPassword = request.Password + user.Salt;

var result = _passwordHasher.VerifyHashedPassword(user, user.Password,salte

if (result != PasswordVerificationResult.Success)
{
return Unauthorized("Invalid credentials 2");
}

// Generate token
var token = _tokenService.CreateToken(user);

// Return the token


https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 3/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

return Ok(new AuthResponse { Token = token });


}

Step 3 — Creating Token service


Now we need to create a method for generating our JWT token. In our token we can
add as much claims as we want. Here its important that our
SecurityTokenDescriptor has the same token validation parameters as our
authroization setup we have in “Program.cs”. We will come back to this later. The
variable i use here named “_configuration” is juse “IConfiguration” dependency
injected into my controller.

public string CreateToken(User user)


{
var tokenHandler = new JwtSecurityTokenHandler();
var key = Encoding.ASCII.GetBytes(_configuration["Jwt:Key"]);
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new Claim[]
{
new Claim(ClaimTypes.NameIdentifier, user.UserID),
new Claim(ClaimTypes.Role, user.Role.ToString()),
// Add more claims as needed
}),
Expires = DateTime.UtcNow.AddHours(1),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(ke
Issuer = _configuration["Jwt:Issuer"], // Add this line
Audience = _configuration["Jwt:Audience"]
};

var token = tokenHandler.CreateToken(tokenDescriptor);


return tokenHandler.WriteToken(token);
}

Step 4— Setting up swagger configuration


Now we need to configure swagger so we can test our endpoints later. Here its
important to mark that when we input our token string in the authroization input in
swagger we need to put: Bearer, followed by a whitespace then our token string.

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 4/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new() { Title = "Pappa´s API", Version = "v1" });

// Define the OAuth2.0 scheme that's in use (i.e., Implicit Flow)


c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Authorization header using the Bearer scheme. Exampl
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
Scheme = "Bearer"
});

c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
});

Step 5— Setting up authorization


Here its important that our token validation parameters are the same as the
parameters we added in our “CreateToken” method, in our token service.

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = true,
ValidateLifetime = true,
https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 5/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

ValidateIssuerSigningKey = true,
ValidIssuer = builder.Configuration["Jwt:Issuer"],
ValidAudience = builder.Configuration["Jwt:Audience"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(
ClockSkew = TimeSpan.Zero
};
});

Step 6— Setting up middleware


The order we place our middleware is very crucial, so do not mix up the order. We
also se swagger to only be active in development.

if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();

Step 7— Setting up app settings


Now we need to add jwt values to our “apptsettings.json”, including the key, issuer
and audience. For demonstration and development purposes i just use these simple
values. But note that especially the key should never be stored in plain text, but for
security its best to store all values in a secure place like Azure secrets or GitHub
secrets.

"Jwt": {
"Key": "your_secret_key_here_your_secret_key_here",
"Issuer": "your_issuer",
"Audience": "your_audience"
}

Step 8— Setting up Authrization in a Controller

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 6/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

Its time for integration our token to one of our APIs. To do this we let .NET handle
the encoding, as we set this up in out “Program.cs” file. We also add “[Authroize]”
with Roles for role based authentication. If you want to add more roles just separate
them in the same string with a comma.

[HttpGet("getuser")]
[Authorize(Roles = "USER")]
public async Task<ActionResult<User>> GetUser()
{
// Retrieve userId from the claims
var userIdClaim = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.

Console.WriteLine("Claims received:");
foreach (var claim in User.Claims)
{
Console.WriteLine($"{claim.Type}: {claim.Value}");
}

if(userIdClaim == null)
{
return Unauthorized("No user ID claim present in token.");
}

try
{
User? user = await _userService.GetUser(userIdClaim);
return Ok(user);
}
catch (InvalidOperationException ex)
{
return BadRequest(ex.Message);
}
}

More steps for securing the API on the way!

Jwt Jwt Token Aspnet Dotnet C

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 7/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

Follow

Written by Amund Fremming


12 Followers

Recommended from Medium

Semih Tekin

Building a .NET Core MVC Web API with PostgreSQL Database


Connectivity and CRUD Operations

May 8 4

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 8/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

Jordan Lee

Angular + ASP.NET + Azure Active Directory B2C


Step-by-step instructions on wiring up an Angular SPA and ASP.NET Web API with AAD B2C
for identity management.

Mar 14 66

Lists

Staff Picks
727 stories · 1277 saves

Stories to Help You Level-Up at Work


19 stories · 781 saves

Self-Improvement 101
20 stories · 2680 saves

Productivity 101
20 stories · 2301 saves

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 9/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

Alexey Lopatin

ASP.NET Authentication: JWT-Bearer events


In this brief post, I’ll describe using one feature of JWT-Bearer extensions in ASP.NET — events.
They allow handling common…

Apr 3 3

yusuf sarıkaya

Mastering Entity Framework Core: Configure Entity Framework


In this blog series, we’ll look at the Entity Framework Code First strategy, giving a concrete
explanation and real-world examples. Since…

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 10/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

May 28 10

Kumar Halder (DevYuga)

OpenIDConnect implementation in Web Apps in ASP.Net web API


In our previous chapter, we discussed about OpenID and OAuth, pros and cons, the workflow
how it works in simplified term. In this chapter…

Mar 11 34 1

Ken Fedorov

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 11/12
7/9/24, 7:00 Integrating JWT to .NET 8. Note: This is a very simplistic and not… | by Amund Fremming | Medium

Top 10 Useful C# .NET Snippets 🚀


1. Object Initialization Syntax: This snippet simplifies the process of creating an object and
initializing its properties.

Apr 11 567 2

See more recommendations

https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 12/12

You might also like