.NET API Login and Registration using Identity

Introduction

Authentication and authorization are essential aspects of building secure and robust web applications. In the .NET ecosystem, Microsoft Identity provides a robust framework for implementing authentication and authorization functionalities seamlessly. In this article, we'll explore how to implement user registration and login functionalities in a .NET API using Microsoft Identity, accompanied by controllers, to handle these operations effectively.

Prerequisites

Before proceeding, ensure that you have the following prerequisites installed:

  • .NET SDK (version 5 or later)
  • Visual Studio or Visual Studio Code (optional)

Setting up the Project

First, let's create a new .NET Web API project:

dotnet new webapi -n YourProjectName
cd YourProjectName

Adding Identity to the Project

To add Identity to your project, run the following commands:

dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer

This adds the necessary packages to your project for using Identity and Entity Framework Core with SQL Server.

Scaffold Identity

Next, scaffold Identity into your project:

dotnet aspnet-codegenerator identity -dc YourDbContext

Replace YourDbContext with the name of your application's DbContext.

Implementing Registration and Login Controllers:

Now, let's implement controllers for user registration and login.

1. Registration Controller

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using YourProjectName.Models;

namespace YourProjectName.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class RegisterController : ControllerBase
    {
        private readonly UserManager<ApplicationUser> _userManager;

        public RegisterController(UserManager<ApplicationUser> userManager)
        {
            _userManager = userManager;
        }

        [HttpPost]
        public async Task<IActionResult> Register(RegisterModel model)
        {
            var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
            var result = await _userManager.CreateAsync(user, model.Password);
            if (result.Succeeded)
            {
                return Ok("Registration successful");
            }
            return BadRequest(result.Errors);
        }
    }
}

2. Login Controller

using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
using YourProjectName.Models;

namespace YourProjectName.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        private readonly SignInManager<ApplicationUser> _signInManager;

        public LoginController(SignInManager<ApplicationUser> signInManager)
        {
            _signInManager = signInManager;
        }

        [HttpPost]
        public async Task<IActionResult> Login(LoginModel model)
        {
            var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, false, false);
            if (result.Succeeded)
            {
                return Ok("Login successful");
            }
            return Unauthorized("Invalid email or password");
        }
    }
}

Models

Ensure you have the necessary models for registration and login:

namespace YourProjectName.Models
{
    public class RegisterModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }

    public class LoginModel
    {
        public string Email { get; set; }
        public string Password { get; set; }
    }
}

Configuring Startup

Finally, add Identity services to the ConfigureServices method in Startup.cs:

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<YourDbContext>()
    .AddDefaultTokenProviders();

Conclusion

In this guide, we've walked through the process of implementing user registration and login functionalities in a .NET API using Microsoft Identity. By following these steps and utilizing Identity's powerful features, you can ensure that your application is equipped with robust authentication mechanisms, enhancing its security and reliability. Feel free to customize and expand upon these implementations to suit your specific requirements and use cases.

Happy coding!


Similar Articles