Image for post
Image for post

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

At first, add this piece of code in Configure method of Startup class before 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))

Using this method you can generate a token. Put it somewhere :) It will save id in token payload and will make token valid during some period of time.

public static string GenerateToken(string id, int days, string secret)
var tokenDescriptor = new SecurityTokenDescriptor
Subject = new ClaimsIdentity(new[]
new Claim(ClaimTypes.Name, id)

Put [Authorize] attribute before the controller in which you want a user to be authorized.

In order to take Id inside a controller:

var userId = HttpContext.User.Identity.Name;

It is easy to use JWT in ASP.NET Core :)

Reach the next level of focus and productivity with

Image for post
Image for post

Written by

Software engineer, creator of More at

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store