asp .net core Jwt Security Token

Issuer and SecurityKey

To generate Jwt Security Token in asp.net core, we have to declare variables that are required for the token to be generated based on. Those variables are Issuer and SigningKey, we can put these variables in appsettings.json so we can read it later.


{
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*",
"jwt" : {
"key" : "KunciSuperRahasiaSekaliBangat",
"issuer" : "localhost"
}
}

JwtBearerAuthentication

Now to add jwtbearer middleware, we need to register it in the startup file. While registering the middleware, we must set the token validation parameters accordingly.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Microsoft.IdentityModel.Tokens;
namespace aspnetcore_jwt.AuthServer
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(jwt=>{
jwt.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters{
ValidateIssuer=true,
ValidateLifetime = true,
ValidateIssuerSigningKey = true,
ValidIssuer = Configuration["jwt:issuer"],
ValidAudience = Configuration["jwt:issuer"],
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes( Configuration["jwt:key"]))
};
});
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseAuthentication();
app.UseHttpsRedirection();
app.UseMvc();
}
}
}
view raw jwt_startup.cs hosted with ❤ by GitHub

Then setup a controller to generate the token, a user just have to send a request to a particular route to get the Json Web Token. The response would be a json object with the token property inside.


using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using aspnetcore_jwt.AuthServer.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.IdentityModel.Tokens;
namespace aspnetcore_jwt.AuthServer.Controllers
{
[Route("api/[controller]/[action]")]
[ApiController]
public class AuthController : Controller
{
private IConfiguration _config;
public AuthController( IConfiguration config)
{
this._config = config;
}
[HttpPost]
public IActionResult Token(LoginViewModel loginViewModel ){
//return new JwtTokenHandler
var token = GenerateJSONWebToken(loginViewModel);
return Ok(new { Token = token});
}
private string GenerateJSONWebToken(LoginViewModel userInfo)
{
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Jwt:key"]));
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
var claims = new List<Claim>(){ new Claim(ClaimTypes.Name, userInfo.username),
new Claim(ClaimTypes.NameIdentifier, userInfo.username)
};
var token = new JwtSecurityToken(_config["Jwt:issuer"],
_config["Jwt:issuer"],
claims,
expires: DateTime.Now.AddMinutes(1),
signingCredentials: credentials);
return new JwtSecurityTokenHandler().WriteToken(token);
}
}
}

Published by Gadael Sedubun

Developer

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: