How to Implement JWT Authentication in Asp.Net Core Web API

In this post, you will learn How to Implement JWT Authentication in Asp.Net Core Web API but before getting started let’s take a look at

What is JWT?

JWT stands for “JSON Web Token”. This specific token makes the data transfer more secure and adds an extra layer to our API security. JWT work as a promise between two parties.

How does JWT this work?

When a user tries to login, the user hits login API with login credentials if the user has correct creds and gets Authenticated by Identity. We generate a JWT token using the JWT library in our Asp.Net Core project and return the token to the client side. JWT is nothing but the user’s encrypted data into a JSON string. This token has a specific time of expiry. Now, whenever we hit any API from the client-side or the second party we have to send JWT in headers using the Authorization tag.

If you want to set up ASP.NET Core Multi-tier project follow the link and if you want to configure identity follow this.

How to Implement JWT Authentication in Asp.Net Core 5

Steps to configure JWT in Asp.Net Core:

  • Configure JWT in Startup. cs
  • Authenticate User
  • Generate and return JWT

Install npm Package:

First of all, configure JWT in your “startup.cs” class

//********jwt***********
 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(Encoding.ASCII.GetBytes(AppConstants.AuthKey)),
    ValidateIssuer = false,
    ValidateAudience = false
   };
});

Now will create a private method to generate our JWT into your “AccountServices.cs” or “AccountController.cs”

private string AuthenticateUser(string username, string password, Guid userid/*, string role*/)
{
  var _key = AppConstants.AuthKey;
  var key = Encoding.UTF8.GetBytes(_key);
  var tokenhanlder = new JwtSecurityTokenHandler();

  var tokendescriptor = new SecurityTokenDescriptor
  {
    Subject = new ClaimsIdentity(new[] {
      new Claim(ClaimTypes.Name, username)/*, new Claim(ClaimTypes.Role, role)*/,neClaim(ClaimTypes.NameIdentifier, userid.ToString())}),
    Expires = DateTime.UtcNow.AddHours(1),
    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
    };

  var stoken = tokenhanlder.CreateToken(tokendescriptor);
  var token = tokenhanlder.WriteToken(stoken);
  return token;
}

New We will call this method into our login method after authenticating the user.

public async Task<ResponseViewModel<object>> LogIn(ApplicationUser data)
        {
            try
            {
                var user = await _userManager.FindByNameAsync(data.UserName);
                if(user == null)
                {
                    return new ResponseViewModel<object>
                    {
                        Status = false,
                        Message = "Invalid UserName",
                    };
                }
                var result = _signInManager.PasswordSignInAsync(user, user.PasswordHash, false, false);
                if (result.IsCompleted == false)
                {
                    return new ResponseViewModel<object>
                    {
                        Status = false,
                        Message = "Wrong Password",
                    };
                }

                var token = AuthenticateUser(user.UserName, user.PasswordHash, user.Id);
                var tokres = await _userManager.SetAuthenticationTokenAsync(await _userManager.FindByNameAsync(user.UserName), "JWT", "JWT Token", token);

                return new ResponseViewModel<object>
                {
                    Status = true,
                    Message = "SignIn Succesfully",
                    StatusCode = System.Net.HttpStatusCode.OK.ToString(),
                    Data =token
                    
                };

            }
            catch (Exception e)
            {
                return new ResponseViewModel<object>
                {
                    Status = false,
                    Message = e.Message,
                };
            }
        }

And we will remove JWT if user logout

public async Task<ResponseViewModel<object>> LogOut(string username)
        {
            var user = await _userManager.FindByNameAsync(username);
            await _userManager.UpdateSecurityStampAsync(user);
            await _userManager.RemoveAuthenticationTokenAsync(user, "JWT", "JWT Token")


            return new ResponseViewModel<object>()
            {
                Status = true,
                Message = "User Logged Out",
                StatusCode = System.Net.HttpStatusCode.OK.ToString()
            };
        }

when we login it will return us a token like this.

Implement JWT Authentication

That is How you can Implement JWT Authentication in Asp.Net Core 5 Web API Project by following these simple steps. If you face any issue or problem while practicing this tutorial do not hesitate to post a comment or Contact Us. We will try to respond ASAP. Thank you.

Leave a Reply

Your email address will not be published.