Web API Tutorialprovides basic and advanced concepts of C# for beginners and professionals.

Implement Authentication using JWT (JSON Web Token) in an ASP.NET MVC 5 Web API with CRUD operations

Back to: Web API Tutorial

To implement authentication using JWT (JSON Web Token) in an ASP.NET MVC 5 Web API with CRUD operations, follow these steps:


1. Add Required NuGet Packages

Install the required packages for JWT handling:

bash

Install-Package Microsoft.AspNet.WebApi -Version 5.2.7
Install-Package System.IdentityModel.Tokens.Jwt
Install-Package Microsoft.Owin.Security.Jwt
Install-Package Microsoft.Owin.Security
Install-Package Owin

2. Create a Token Generator

Define a method to generate JWT tokens. This method will be used to issue tokens for authenticated users.

using System;
using System.IdentityModel.Tokens.Jwt;
using System.Security.Claims;
using Microsoft.IdentityModel.Tokens;
public class TokenManager
{
private const string SecretKey = "YourSecretKeyHere123456";
// Replace with your secret key
public static string GenerateToken(string username)
{
var key = Convert.FromBase64String(SecretKey);
var tokenHandler = new JwtSecurityTokenHandler();
var claims = new[] { new Claim(ClaimTypes.Name, username), new Claim(JwtRegisteredClaimNames.Exp, DateTime.UtcNow.AddMinutes(30).ToString()) }; var credentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256);
var tokenDescriptor = new SecurityTokenDescriptor { Subject = new ClaimsIdentity(claims), Expires = DateTime.UtcNow.AddMinutes(30), SigningCredentials = credentials };
var token = tokenHandler.CreateToken(tokenDescriptor); return tokenHandler.WriteToken(token);
}
}

3. Configure JWT Authentication Middleware

Set up the OWIN middleware to validate incoming JWT tokens.

using Microsoft.Owin;
using Microsoft.Owin.Security.Jwt;
using Microsoft.Owin.Security;
using Owin; using System;
using Microsoft.IdentityModel.Tokens;
[assembly: OwinStartup(typeof(MyApp.Startup))]
namespace MyApp
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var key = Convert.FromBase64String("YourSecretKeyHere123456");
// Replace with your secret key

app.UseJwtBearerAuthentication(new JwtBearerAuthenticationOptions
{
AuthenticationMode = AuthenticationMode.Active,
TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = false,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(key),
ValidateLifetime = true
}});

}
}
}

4. Protect API Endpoints with Authentication

Use the [Authorize] attribute to protect your API controllers or actions.

using System.Web.Http;
[Authorize]
public class ValuesController : ApiController
{
// GET api/values
public IHttpActionResult Get()
{
return Ok(new { Message = "This is a protected resource" });
}
// POST api/values public IHttpActionResult Post([FromBody] string value)
{
 return Ok(new { Message = "Value created", Value = value });
 }
}

5. Authentication Endpoint for Token Generation

Create an endpoint to generate tokens for authenticated users.

using System.Web.Http;
public class AuthController : ApiController
{
[HttpPost]
[AllowAnonymous]
public IHttpActionResult Authenticate([FromBody] UserLogin user)
{
if (user.Username == "testuser" && user.Password == "password")
// Replace with actual validation logic
{
 var token = TokenManager.GenerateToken(user.Username);
 return Ok(new { Token = token }); }
 return Unauthorized();
}
}
public class UserLogin
{
public string Username { get; set; }
public string Password { get; set; }
}

6. Test the API

  1. Send a POST request to the authentication endpoint (/api/auth/authenticate) with username and password to get a JWT token.
  2. Include the token in the Authorization header as a Bearer token for other API calls.

7. CRUD Operations Example

Below is an example of a simple CRUD API.

[Authorize]
public class ProductsController : ApiController
{
private static List products = new List { "Product1", "Product2" };
// GET api/products
public IHttpActionResult Get()
{
 return Ok(products);
}
// GET api/products/1
public IHttpActionResult Get(int id)
{
if (id < 0 || id >= products.Count)
return NotFound();
return Ok(products[id]);
}
// POST api/products
public IHttpActionResult Post([FromBody] string product)
{
products.Add(product);
 return Ok(products); }
// PUT api/products/1
public IHttpActionResult Put(int id, [FromBody] string product)
{
if (id < 0 || id >= products.Count)
return NotFound(); products[id] = product;
return Ok(products);
}
// DELETE api/products/1
public IHttpActionResult Delete(int id)
{ if (id < 0 || id >= products.Count)
return NotFound();
products.RemoveAt(id); return Ok(products);
}
}

Summary

This setup provides:

  • Token-based authentication using JWT.
  • Middleware for validating JWT tokens.
  • Protected API endpoints with CRUD operations.

Make sure to replace placeholders like YourSecretKeyHere123456 with secure, unique values, and implement proper user authentication logic.

Scroll to Top