Jwt Example

How to secure an application with JWT (Json Web Token)

Here we are going to use a Web-Api for the example. Let Visual Studio 2019 create a Web-Api project, remember to set Enable Open APISupport checked, to ensure that Swagger is enabled. In Configure method in Startup.cs do the following:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseSwagger(); app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CoreAPIWithJWT v1")); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthentication(); //Ensure to set UseAuthentication app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
Create an interface (optionally create a folder named Interfaces to put it in)
public interface IJwtAuthenticationManager { string Authenticate(string userName, string password); }
Then install the Microsoft.AspNetCore.Authentication and System.IdentityModel.Tokens.Jwt nuget packages in the project. For this example we will use data for username and password from a internal data store(From a Dictionary).
public class JwtAuthenticationManager: IJwtAuthenticationManager { private readonly IDictionary users = new Dictionary { {"test1","pwd1" }, {"test2","pwd2"} }; private readonly string _key; public JwtAuthenticationManager(string key) { _key = key; } public string Authenticate(string userName, string password) { if (!users.Any(u => u.Key == userName && u.Value == password)) { return null; } var tokenHandler = new JwtSecurityTokenHandler(); var tokenKey = Encoding.ASCII.GetBytes(_key); var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, userName), }), Expires = DateTime.UtcNow.AddHours(1), //Let the credentials work for an hour SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenKey), SecurityAlgorithms.HmacSha256Signature), }; SecurityToken token = null; try { token = tokenHandler.CreateToken(tokenDescriptor); } catch (Exception ex) { var err = ex.Message; } return tokenHandler.WriteToken(token); } }
Back to the controller you created. Create the constructor which IJwtAuthenticationManager will be accepting as the parameter.
public class NameController : ControllerBase { private readonly IJwtAuthenticationManager _jwtAuthenticationManager; public NameController(IJwtAuthenticationManager jwtAuthenticationManager) { _jwtAuthenticationManager = jwtAuthenticationManager; } . . .
Create a separate model called to hold the UserName and the Password, And use _jwtAuthenticationManager to access the Authenticate method.
[AllowAnonymous] // Let unauthenticated users authenticate.... [HttpPost("Authenticate")] public IActionResult Authenticate([FromBody] User user) { var token = _jwtAuthenticationManager.Authenticate(user.UserName, user.Password); if (token is null) return Unauthorized(); return Ok(token); } [HttpGet] public string Get() { return "you're in !"; Only when you're autenticated....' }