JWT TOKEN AUTHENTICATION IN .NET CORE WEB API BASIC EXAMPLE BY RAJESH

 

 

 

            JWT TOKEN AUTHENTICATION IN .NET CORE WEB API

                 BASIC EXAMPLE BY RAJESH

 

Install Nuget packages:

Microsoft.AspNetcore.Authentication

Microsoft.AspNetcore.Authentication.JwtBearer

System.IdentityModel.Tokens.Jwt

 

 

Controller :  created controller with Name Controller

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;

using sampleapijwt.Model;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

 

namespace sampleapijwt.Controllers

{

    [Authorize] //protect methods in controller

    [Route("api/[controller]")]

    [ApiController]

    public class NameController : ControllerBase

    {

 

        private readonly IJWTAuthenticationManager jWTAuthenticationManager;

 

        public NameController(IJWTAuthenticationManager jWTAuthenticationManager)

        {

            this.jWTAuthenticationManager = jWTAuthenticationManager;

        }

 

        // GET: api/<NameController>

        [HttpGet]

        public IEnumerable<string> Get()

        {

            return new string[] { "value1", "value2" };

        }

 

 

        // GET api/<NameController>/5

        [HttpGet("{id}")]

        public string Get(int id)

        {

            return "value";

        }

 

 

       

      [AllowAnonymous]// allow non authenticated also

        [HttpPost("authenticate")]

        public IActionResult Authenticate([FromBody] UserCredentials userCredentials)

        {

 

            var token = jWTAuthenticationManager.Authenticate(userCredentials.Username, userCredentials.Password);

 

           

            if (token == null)

            {

                return Unauthorized();

            }

            else

            {

                return Ok(token);

            }

 

           

        }

 

 

 

    }

}

 

Models :  for jwt generation & authentication

 

UserCredentials

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace sampleapijwt

{

    public class UserCredentials

    {

        public string Username { get; set; }

        public string Password { get; set; }

    }

}

 

User

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text.Json.Serialization;

using System.Threading.Tasks;

 

namespace sampleapijwt.Model

{

    public class User

    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Username { get; set; }

        public string Role { get; set; }

 

        [JsonIgnore]

        public string Password { get; set; }

    }

}

 


AuthenticateResponse

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace sampleapijwt.Model

{

    public class AuthenticateResponse

    {

        public int Id { get; set; }

        public string FirstName { get; set; }

        public string LastName { get; set; }

        public string Username { get; set; }

        public string Role { get; set; }

        public string Token { get; set; }

 

        public AuthenticateResponse(User user, string token)

        {

            Id = user.Id;

            FirstName = user.FirstName;

            LastName = user.LastName;

            Username = user.Username;

            Role = user.Role;

            Token = token;

        }

    }

 

 

}

 

JWTAuthenticationManager

using Microsoft.IdentityModel.Tokens;

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;

 

namespace sampleapijwt.Model

{

   

    public class JWTAuthenticationManager : IJWTAuthenticationManager

    {

        //changed

        //IDictionary<string, string> users = new Dictionary<string, string>

        //{

        //    { "test1", "password1" },

        //    { "test2", "password2" }

        //};

 

 

        private List<User> users = new List<User>

        {

            new User { Id = 1, FirstName = "Test", LastName = "User", Username = "test",Role="user", Password = "test" }

        };

 

 

      

        private readonly string tokenKey;

        public JWTAuthenticationManager(string tokenKey)

        {

            this.tokenKey = tokenKey;

        }

      

 

        //changed

        public AuthenticateResponse Authenticate(string username, string password)

        {

 

            //changed

            //if (!users.Any(u => u.Key == username && u.Value == password))

            //{

            //    return null;

            //}

 

            var user = users.SingleOrDefault(x => x.Username == username && x.Password == password);

 

            // return null if user not found

            if (user == null)

            {

                return null;

            }

 

 

            var token = generateJwtToken(username);

 

            return new AuthenticateResponse(user, token);

 

 

         

        }

 

 

        private string generateJwtToken(string username)

        {

 

            //8

            var tokenHandler = new JwtSecurityTokenHandler();

            var key = Encoding.ASCII.GetBytes(tokenKey);

            var tokenDescriptor = new SecurityTokenDescriptor

            {

                Subject = new ClaimsIdentity(new Claim[]

                {

                    new Claim(ClaimTypes.Name, username)

                }),

                Expires = DateTime.UtcNow.AddHours(1),

                SigningCredentials = new SigningCredentials(

                    new SymmetricSecurityKey(key),

                    SecurityAlgorithms.HmacSha256Signature)

            };

            var token = tokenHandler.CreateToken(tokenDescriptor);

            return tokenHandler.WriteToken(token);

        }

        }

}

 

 

Interface

IJWTAuthenticationManager

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

 

namespace sampleapijwt.Model

{

   

    public interface IJWTAuthenticationManager

    {

        AuthenticateResponse Authenticate(string username, string password);

    }

}

 

Appsettings

{

  "TokenKey": "This is my test private key",

  "Logging": {

    "LogLevel": {

      "Default": "Information",

      "Microsoft": "Warning",

      "Microsoft.Hosting.Lifetime": "Information"

    }

  },

  "AllowedHosts": "*"

}

 

Startup

 

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.Hosting;

using Microsoft.Extensions.Logging;

using Microsoft.IdentityModel.Tokens;

using Microsoft.OpenApi.Models;

using sampleapijwt.Model;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace sampleapijwt

{

    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.AddControllers();

           

 

            //added

            var tokenKey = Configuration.GetValue<string>("TokenKey");

            var key = Encoding.ASCII.GetBytes(tokenKey);

 

            services.AddAuthentication(x =>

            {

                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;

                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;

            })

            .AddJwtBearer(x =>

            {

                x.RequireHttpsMetadata = false;

                x.SaveToken = true;

                x.TokenValidationParameters = new TokenValidationParameters

                {

                    ValidateIssuerSigningKey = true,

                    IssuerSigningKey = new SymmetricSecurityKey(key),

                    ValidateIssuer = false,

                    ValidateAudience = false

                };

            });

 

            //added

            services.AddSingleton<IJWTAuthenticationManager>(new JWTAuthenticationManager(tokenKey));

            services.AddSwaggerGen(c =>

            {

                c.SwaggerDoc("v1", new OpenApiInfo { Title = "sampleapijwt", Version = "v1" });

            });

        }

 

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)

        {

            if (env.IsDevelopment())

            {

                app.UseDeveloperExceptionPage();

                app.UseSwagger();

                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "sampleapijwt v1"));

            }

 

            app.UseHttpsRedirection();

 

            app.UseRouting();

 

            //added

            app.UseAuthentication();

            app.UseAuthorization();

 

            app.UseEndpoints(endpoints =>

            {

                endpoints.MapControllers();

            });

        }

    }

}

 

Comments