ASP.NET Core + JWT

main

There is a lot of tutorials about authentication in ASP.NET. But almost all of them have too much code and words. In this tutorial, I will show how to make ASP.NET Core with JWT in an easy way.

First, add this piece of code to the Configure method of Startup class before the app.UseMvc(). It will apply JWT authentication middleware for your app.

var tokenValidationParameters = new TokenValidationParameters()
{
RequireExpirationTime = true,
ValidateIssuer = false,
ValidateAudience = false,
IssuerSigningKey = new SymmetricSecurityKey(Convert.FromBase64String(SecretKey))
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});
view raw Configure.cs hosted with ❤ by GitHub

Use the method below to generate a token. It will save id in the token payload and will make the token valid during the specified time.

public static string GenerateToken(string id, int days, string secret)
{
var tokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[]
{
new Claim(ClaimTypes.Name, id)
}),
Expires = DateTime.UtcNow.AddDays(Convert.ToInt32(days)),
SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(Convert.FromBase64String(secret)),
SecurityAlgorithms.HmacSha256Signature
)
};
return new JwtSecurityTokenHandler().WriteToken(
tokenHandler.CreateToken(tokenDescriptor)
);
}
view raw GenerateToken.cs hosted with ❤ by GitHub

Put [Authorize] attribute above the controller in which you want an authorized user. To take user's id inside a controller:

var userId = HttpContext.User.Identity.Name;
view raw Controller.cs hosted with ❤ by GitHub