Skip to main content

๐Ÿš€Master User Authentication in .NET 8 Web API Email Confirmation, Password Reset, 2FA & Lockout with JWT & Identity๐Ÿ”

Master Email Confirmation in .NET 8 Web API using JWT & Identity ๐Ÿ”ฅ | Step-by-Step Secure Registration

Namespace and Imports

The code begins by importing several libraries and namespaces essential for email sending, JWT token handling, and ASP.NET Identity, including:

  • Microsoft.AspNetCore.Identity: For managing user identities in ASP.NET Core applications.
  • Microsoft.AspNetCore.Mvc: Provides attributes like [ApiController] and [Route], simplifying the API controller setup.
  • MailKit and MimeKit: Used to compose and send emails, supporting SMTP clients.
  • Microsoft.IdentityModel.Tokens, System.Security.Claims, System.IdentityModel.Tokens.Jwt: To handle JWT (JSON Web Tokens) for authentication.

AccountController Class

This class is responsible for user account management, including registration, email confirmation, and login.

[ApiController] and [Route("[controller]")]

These attributes define the class as an API controller and set the route pattern for the endpoints. Requests to this controller will follow the route pattern based on the controller name.

Register Method

The Register method handles user registration:

  • [HttpPost("register/{email}/{password}")]: Specifies that this endpoint is an HTTP POST request for registering new users with an email and password.
  • User Creation: It checks if a user already exists using GetUser(email). If not, it creates a new user using userManager.CreateAsync.
  • Generate Email Confirmation Token: After registration, an email confirmation token is generated via userManager.GenerateEmailConfirmationTokenAsync().
  • Send Email: The token is sent to the user's email using the SendEmail method.

SendEmail Method

This method is responsible for composing and sending an email with the confirmation code:

  • HTML Email Structure: Builds a simple HTML email message thanking the user for registering and providing the email confirmation code.
  • SMTP Email Sending: Uses MailKit.Net.Smtp.SmtpClient to send the email. It connects to the SMTP server, authenticates using the provided credentials, and sends the email to the user.

Confirmation Method

This method confirms the user's email address:

  • [HttpPost("confirmation/{email}/{code:int}")]: Defines the endpoint for confirming an email using a provided code.
  • Input Validation: It checks if the provided email and code are valid.
  • Confirm Email: Calls userManager.ConfirmEmailAsync to confirm the user's email using the generated confirmation code. If successful, the user can proceed to log in.

Login Method

This method handles user login:

  • [HttpPost("login/{email}/{password}")]: Defines the login endpoint.
  • Validation: It validates the email and password.
  • Email Confirmation Check: Ensures that the user's email has been confirmed before allowing login.
  • JWT Token Generation: On successful login, it returns a JWT token using the GenerateToken method.

GenerateToken Method

This method generates a JWT token for authenticated users:

  • Symmetric Security Key: A key is created using a predefined secret (key).
  • Claims: Claims are created based on the user's ID and email.
  • JWT Token Creation: A new JWT token is generated with the claims, security key, and signing credentials using JwtSecurityTokenHandler.

GetUser Method

This helper method retrieves the user by email using userManager.FindByEmailAsync().

Protected Endpoint

  • [Authorize] and JwtBearerDefaults.AuthenticationScheme: This endpoint is protected by JWT Bearer authentication, meaning only authenticated users with a valid JWT token can access it.
  • [HttpGet("protected")]: Returns a protected message when accessed by an authenticated user.

Summary

  • User Registration: Users can register with an email and password.
  • Email Confirmation: A confirmation token is sent to the user’s email. The user needs to confirm their email before they can log in.
  • JWT Authentication: After email confirmation, the user can log in, and a JWT token is generated. This token allows access to protected endpoints.
  • Email and SMTP: Emails are sent using the MailKit library and SMTP.

This controller handles critical authentication workflows such as registration, email confirmation, and JWT-based authentication.

Comments

Popular Posts

Complete Employee Management System | .NET 8 Blazor Wasm & Web API - Perform CRUD, Print, PDF etc..

.NET 8 Clean Architecture with Blazor CRUD, JWT & Role Authorization using Identity & Refresh Token๐Ÿ”ฅ

Employee Management System | .NET 8 Blazor Wasm- Profile & real-time data retrieval. Update 1