ASP.NET Core Web API Identity JWT 2024 - 21. Install Identity

3 min read 4 hours ago
Published on Feb 04, 2025 This response is partially generated with the help of AI. It may contain inaccuracies.

Table of Contents

Introduction

In this tutorial, we will learn how to install Identity in an ASP.NET Core Web API using JWT for authentication. This setup is essential for securing your API and managing user authentication efficiently. By following these steps, you'll be able to integrate Identity into your application seamlessly.

Step 1: Create a New ASP.NET Core Project

  • Open your terminal or command prompt.
  • Run the following command to create a new ASP.NET Core Web API project:
    dotnet new webapi -n YourProjectName
    
  • Replace YourProjectName with the desired name for your project.

Step 2: Add Required NuGet Packages

  • Navigate to your project folder:
    cd YourProjectName
    
  • Install the necessary Identity packages by running:
    dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
    dotnet add package Microsoft.EntityFrameworkCore.SqlServer
    dotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
    
  • These packages are essential for setting up Identity and JWT authentication.

Step 3: Set Up the Database Context

  • Open the Startup.cs file in your project.
  • Add the following namespaces at the top:
    using Microsoft.AspNetCore.Identity;
    using Microsoft.EntityFrameworkCore;
    
  • In the ConfigureServices method, add the database context and Identity services:
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
    
    services.AddIdentity<IdentityUser, IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>()
        .AddDefaultTokenProviders();
    
  • Ensure you have a connection string set up in your appsettings.json file.

Step 4: Configure JWT Authentication

  • Still in the Startup.cs file, add JWT authentication configuration in the ConfigureServices method:
    var key = Encoding.ASCII.GetBytes(Configuration["Jwt:Key"]);
    
    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
        };
    });
    

Step 5: Create the ApplicationDbContext

  • Create a new class file named ApplicationDbContext.cs.
  • In this file, inherit from IdentityDbContext:
    public class ApplicationDbContext : IdentityDbContext<IdentityUser>
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        {
        }
    }
    

Step 6: Update the Database

  • Run the following commands to create migrations and update the database:
    dotnet ef migrations add InitialCreate
    dotnet ef database update
    
  • This will create the necessary tables for Identity in your database.

Step 7: Implement User Registration and Login

  • Create a new controller named AuthController.cs.
  • Implement methods for user registration and login:
    [HttpPost("register")]
    public async Task<IActionResult> Register([FromBody] RegisterModel model)
    {
        var user = new IdentityUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            return Ok();
        }
        return BadRequest(result.Errors);
    }
    
    [HttpPost("login")]
    public async Task<IActionResult> Login([FromBody] LoginModel model)
    {
        var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
        if (result.Succeeded)
        {
            // Generate JWT token here
        }
        return Unauthorized();
    }
    

Conclusion

You have successfully installed Identity in your ASP.NET Core Web API and configured JWT authentication. You can now build upon this foundational setup to implement user registration and login functionalities. For further development, consider exploring user roles, password recovery options, and enhancing security features for your API.