ASP.NET Core + JWT

Radzion
2 min readJul 11, 2017

--

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))
};
app.UseJwtBearerAuthentication(new JwtBearerOptions
{
AutomaticAuthenticate = true,
AutomaticChallenge = true,
TokenValidationParameters = tokenValidationParameters
});

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)
}),
Expires = DateTime.UtcNow.AddDays(Convert.ToInt32(days)),SigningCredentials = new SigningCredentials(
new SymmetricSecurityKey(Convert.FromBase64String(secret)),
SecurityAlgorithms.HmacSha256Signature
)
};
return new JwtSecurityTokenHandler().WriteToken(
tokenHandler.CreateToken(tokenDescriptor)
);
}

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 increaser.org.

Increaser

--

--