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.

JSON Web Tokens (JWT) are a popular way to implement authentication and authorization in web applications, including ASP.NET Core Web API. JWT authentication works by creating a digitally signed token that contains information about the user and their permissions. This token is sent along with each subsequent request to the API, allowing the server to verify the user’s identity and grant or deny access to resources based on the information in the token.

The token itself is a string of characters that is made up of three parts separated by dots: the header, the payload, and the signature. The header typically contains information about the type of token and the algorithm used to sign it. The payload contains the user’s information, such as their username, user ID, and any relevant permissions. Finally, the signature is used to verify the integrity of the token and ensure that it has not been tampered with.

One advantage of JWT authentication is that it is stateless, meaning that the server does not need to keep track of the user’s session or login status. This can make it easier to scale the application and improve performance.

However, one potential disadvantage of JWT authentication is that the token itself can be stolen or intercepted by a third party. Therefore, it is important to implement appropriate security measures, such as using HTTPS to encrypt the communication between the client and server, and using strong encryption algorithms to sign the tokens.

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

Securing the Web API using JWT Authentication

Once JWT authentication has been added to the ASP.NET Core Web API, the next step is to use it to secure the API and control access to resources. This is done by adding the [Authorize] attribute to the controllers or actions that require authentication. This attribute specifies that only requests with a valid JWT token should be allowed to access the resource.

For example, consider a Web API that provides information about users. To secure this API, we would add the [Authorize] attribute to the controller that handles user requests. This would ensure that only authenticated users with a valid JWT token can access the user information.

If a request is made to the API without a valid token, the API will return a 401 Unauthorized response. To handle this scenario, we can create a custom middleware that intercepts unauthorized requests and returns a custom error message or redirects the user to a login page.

It is also important to ensure that the API is secure against common attacks, such as cross-site request forgery (CSRF) and cross-site scripting (XSS) attacks. This can be achieved by implementing appropriate security measures, such as using HTTPS to encrypt communication and validating input data to prevent malicious input.

Testing the JWT Authentication

Once JWT authentication has been implemented in the ASP.NET Core Web API, it’s important to test it to ensure that it’s working correctly. One way to test JWT authentication is by using a tool such as Postman.

To test the API with Postman, we need to send a request to the API that includes a valid JWT token in the Authorization header. The token can be obtained by logging in to the application or by using a tool such as jwt.io to generate a token manually.

Once we have the token, we can add it to the Authorization header in Postman and send a request to the API. If the token is valid, the API will return the expected response. If the token is invalid or has expired, the API will return a 401 Unauthorized response.

We can also test different scenarios, such as sending requests with invalid tokens or sending requests to resources that require authentication without including a token. This will help us identify any issues with the JWT authentication implementation and ensure that the API is secure against unauthorized access.

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

Related Posts