Skip to content

Instantly share code, notes, and snippets.

@shahabganji
Last active January 2, 2022 11:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shahabganji/f96cc19135a01c10662f3d006e10bc9e to your computer and use it in GitHub Desktop.
Save shahabganji/f96cc19135a01c10662f3d006e10bc9e to your computer and use it in GitHub Desktop.
Sample codes for the blog post: Generate/Validate JSON Web Tokens(JWT) in ASP.NET Core
var securityKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("7h!$S40u1d83@$7r0n9P@5$Word"));
var header = new JwtHeader(
new SigningCredentials(
securityKey,
SecurityAlgorithms.HmacSha512Signature
));
var claims = new[]
{
new Claim(ClaimTypes.NameIdentifier, "user1"),
new Claim(ClaimTypes.Role, "admin"),
};
var payload = new JwtPayload(
issuer: "http://localhost:6001",
audience: "my-api",
claims: claims, null,
expires: DateTime.UtcNow.AddDays(7),null);
var token = new JwtSecurityToken(header, payload);
var tokenHandler = new JwtSecurityTokenHandler();
return tokenHandler.WriteToken(token);
dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer --version 3.1.8
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
ValidateIssuer = true,
ValidateAudience = true,
ValidIssuer = "http://localhost:6001",
ValidAudience = "my-api",
IssuerSigningKey = new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("7h!$S40u1d83@$7r0n9P@5$Word"))
};
options.Events = new JwtBearerEvents
{
OnMessageReceived = ValidateToken
};
});
curl -X POST "https://localhost:6001/Account/login" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"username\":\"shahab\",\"password\":\"somepassword\"}"
public static Task ValidateToken(MessageReceivedContext context)
{
try
{
context.Token = GetToken(context.Request);
var tokenHandler = new JwtSecurityTokenHandler();
tokenHandler.ValidateToken(context.Token, context.Options.TokenValidationParameters, out var validatedToken);
var jwtSecurityToken = validatedToken as JwtSecurityToken;
context.Principal = new ClaimsPrincipal();
var claimsIdentity = new ClaimsIdentity(jwtSecurityToken.Claims.ToList(),
"JwtBearerToken", ClaimTypes.NameIdentifier, ClaimTypes.Role);
context.Principal.AddIdentity(claimsIdentity);
context.Success();
return Task.CompletedTask;
}
catch (Exception e)
{
context.Fail(e);
}
return Task.CompletedTask;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment