Integrating JWT To .NET 8. Note - This Is A Very Simplistic and Not - by Amund Fremming - Medium
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
Note: This is a very simplistic and not minimal secure way of setting up JWT.
using System.ComponentModel.DataAnnotations;
namespace Auth;
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;
[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;
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
[HttpPost("register")]
public async Task<IActionResult> Register([FromBody] RegistrationRequest reques
{
var salt = GenerateSalt();
var saltedPassword = request.Password + salt;
await _userService.CreateUser(user);
var token = _tokenService.CreateToken(user);
[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");
}
if (result != PasswordVerificationResult.Success)
{
return Unauthorized("Invalid credentials 2");
}
// Generate token
var token = _tokenService.CreateToken(user);
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" });
c.AddSecurityRequirement(new OpenApiSecurityRequirement()
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference
{
Type = ReferenceType.SecurityScheme,
Id = "Bearer"
},
Scheme = "oauth2",
Name = "Bearer",
In = ParameterLocation.Header,
},
new List<string>()
}
});
});
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
};
});
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapControllers();
"Jwt": {
"Key": "your_secret_key_here_your_secret_key_here",
"Issuer": "your_issuer",
"Audience": "your_audience"
}
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);
}
}
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
Semih Tekin
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
Mar 14 66
Lists
Staff Picks
727 stories · 1277 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
Apr 3 3
yusuf sarıkaya
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
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
Apr 11 567 2
https://medium.com/@amund.fremming/integrating-jwt-to-net-8-925c4f60695e 12/12