Skip to main content

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

Part 4️⃣ - JWT Authentication API |๐Ÿ›’ Build .NET 8 eCommerce Microservice ๐Ÿš€with API Gateway, Rate Limiting, Caching & more ๐Ÿงบ

Entity Description - AppUser

AppUser Class Description

The AppUser class represents a user in the application, encapsulating various properties related to user identity, contact information, and roles. Here’s a detailed breakdown of each property:

  1. Id

    • Type: int
    • Description: A unique identifier for the user.
  2. Name

    • Type: string?
    • Description: The user's name. It is nullable, allowing the possibility of no name being provided.
  3. TelephoneNumber

    • Type: string?
    • Description: The user's telephone number. It is nullable.
  4. Address

    • Type: string?
    • Description: The user's physical address. It is nullable.
  5. Email

    • Type: string?
    • Description: The user's email address. It is nullable.
  6. Password

    • Type: string?
    • Description: The user's password for authentication. It is nullable.
  7. Role

    • Type: string?
    • Description: The role assigned to the user (e.g., Admin, User). It is nullable.
  8. DateRegistered

    • Type: DateTime
    • Description: The date and time when the user registered. It defaults to the current UTC time at the moment of instantiation.

Usage

The AppUser class can be used to represent users within the application, storing their essential information and supporting various functionalities like authentication, authorization, and user management. The nullable properties provide flexibility in handling incomplete user data during different stages of the user lifecycle.


LoginDTO Record Description - LoginDTO.cs

The LoginDTO record represents the data transfer object used for user login purposes. It encapsulates the necessary information for authenticating a user. Here’s a detailed breakdown of its properties:

  1. Email

    • Type: string
    • Description: The user's email address used for logging in.
  2. Password

    • Type: string
    • Description: The user's password used for logging in.

Usage

The LoginDTO record is typically used in authentication processes where a user provides their email and password to gain access to the application. This data transfer object ensures that only the necessary information for login is transmitted, enhancing security and efficiency.

By using a record, LoginDTO benefits from immutability and value-based equality, which are ideal for simple data carriers like DTOs.


GetUserDTO Record Description - GetUserDTO.cs

The GetUserDTO record is a data transfer object designed to encapsulate and transmit essential user information. This DTO is typically used for retrieving user details. Here’s a detailed breakdown of its properties:

  1. Id

    • Type: int
    • Description: A unique identifier for the user.
  2. Name

    • Type: string
    • Attributes: [Required]
    • Description: The user's name. This property is mandatory.
  3. TelephoneNumber

    • Type: string
    • Attributes: [Required]
    • Description: The user's telephone number. This property is mandatory.
  4. Address

    • Type: string
    • Attributes: [Required]
    • Description: The user's physical address. This property is mandatory.
  5. Email

    • Type: string
    • Attributes: [Required, EmailAddress]
    • Description: The user's email address. This property is mandatory and must be a valid email format.
  6. Role

    • Type: string
    • Attributes: [Required]
    • Description: The role assigned to the user (e.g., Admin, User). This property is mandatory.

Usage

The GetUserDTO record is used when fetching user details, ensuring that all essential information is included and validated. The [Required] attribute ensures that the properties must have values, and the [EmailAddress] attribute enforces that the Email property contains a valid email address.

This record is beneficial for API responses, user management interfaces, and any scenario where complete and validated user information is necessary. The use of a record provides immutability and value-based equality, making it an ideal choice for DTOs.


AppUserDTO Record Description - AppUserDTO.cs

The AppUserDTO record is a data transfer object designed to encapsulate and transmit comprehensive user information, including sensitive data such as the password. Here’s a detailed breakdown of its properties:

  1. Id

    • Type: int
    • Description: A unique identifier for the user.
  2. Name

    • Type: string
    • Attributes: [Required]
    • Description: The user's name. This property is mandatory.
  3. TelephoneNumber

    • Type: string
    • Attributes: [Required]
    • Description: The user's telephone number. This property is mandatory.
  4. Address

    • Type: string
    • Attributes: [Required]
    • Description: The user's physical address. This property is mandatory.
  5. Email

    • Type: string
    • Attributes: [Required, EmailAddress]
    • Description: The user's email address. This property is mandatory and must be in a valid email format.
  6. Password

    • Type: string
    • Attributes: [Required]
    • Description: The user's password for authentication. This property is mandatory.
  7. Role

    • Type: string
    • Attributes: [Required]
    • Description: The role assigned to the user (e.g., Admin, User). This property is mandatory.

Usage

The AppUserDTO record is used when handling comprehensive user information, including scenarios where user data needs to be transmitted or processed, such as user registration, profile updates, and administrative tasks. The attributes ensure that all essential properties are provided and validated:

  • [Required]: Ensures the property must have a value.
  • [EmailAddress]: Validates that the email property contains a valid email address.

This record is beneficial for API interactions, ensuring that complete and validated user data is transmitted. Using a record provides immutability and value-based equality, making it an ideal choice for DTOs in .NET applications.


IUser Interface Description - IUser.cs

The IUser interface defines the contract for user-related operations, including registration, login, and retrieving user details. Implementing this interface ensures a consistent approach to handling user data across the application. Here's a detailed breakdown of each method:

  1. Register

    • Signature: Task<Response> Register(AppUserDTO appUserDTO)
    • Description: Registers a new user using the provided AppUserDTO object.
    • Parameters:
      • AppUserDTO appUserDTO: The data transfer object containing the user's information required for registration.
    • Returns: A Task that represents the asynchronous operation, containing a Response object with the outcome of the registration process.
  2. Login

    • Signature: Task<Response> Login(LoginDTO loginDTO)
    • Description: Authenticates a user using the provided LoginDTO object.
    • Parameters:
      • LoginDTO loginDTO: The data transfer object containing the user's email and password for login.
    • Returns: A Task that represents the asynchronous operation, containing a Response object with the outcome of the login attempt.
  3. GetUser

    • Signature: Task<GetUserDTO> GetUser(int userId)
    • Description: Retrieves the details of a user by their unique identifier.
    • Parameters:
      • int userId: The unique identifier of the user whose details are to be retrieved.
    • Returns: A Task that represents the asynchronous operation, containing a GetUserDTO object with the user's details.

Usage

The IUser interface can be implemented by any class that manages user-related operations, such as a user service or repository. This ensures that all user operations follow a consistent pattern and allows for easy testing and maintenance.

  • Register: Handles user registration, ensuring that new users can sign up and have their details stored appropriately.
  • Login: Manages user authentication, verifying credentials and providing access tokens or error messages as needed.
  • GetUser: Fetches detailed information about a user, which can be used in various parts of the application for displaying user profiles or performing authorization checks.

By defining these methods in an interface, the application adheres to the principles of abstraction and dependency inversion, facilitating easier testing and a more modular codebase.


UserRepository Class - UserRepository.cs

The UserRepository class implements the IUser interface and provides methods to manage user authentication and registration using Entity Framework Core for data access and BCrypt for password hashing. Here's a detailed breakdown of its components:

Constructor

  • UserRepository(IConfiguration config, AuthenticationDbContext context)
    • Parameters:
      • IConfiguration config: Configuration object for accessing application settings.
      • AuthenticationDbContext context: The database context for accessing user data.
    • Description: Initializes the repository with configuration settings and the database context.

Private Methods

  • private async Task<AppUser> GetUserByEmail(string email)
    • Parameters:
      • string email: The email of the user to find.
    • Returns: An AppUser object if found, otherwise null.
    • Description: Retrieves a user from the database by their email address.

Public Methods

  1. public async Task<GetUserDTO> GetUser(int userId)

    • Parameters:
      • int userId: The ID of the user to retrieve.
    • Returns: A GetUserDTO object if the user is found, otherwise null.
    • Description: Fetches user details by their ID and maps them to the GetUserDTO data transfer object.
  2. public async Task<Response> Login(LoginDTO loginDTO)

    • Parameters:
      • LoginDTO loginDTO: Contains the email and password for login.
    • Returns: A Response object indicating the result of the login attempt. Contains a token if successful.
    • Description: Authenticates a user by checking the provided credentials. Returns a JWT token if the credentials are valid.
  3. public async Task<Response> Register(AppUserDTO appUserDTO)

    • Parameters:
      • AppUserDTO appUserDTO: Contains user information for registration.
    • Returns: A Response object indicating the result of the registration attempt.
    • Description: Registers a new user by checking if the email is already in use, hashing the password, and saving the user to the database.

Private Methods

  • private string GenerateToken(AppUser user)
    • Parameters:
      • AppUser user: The user for whom the token is generated.
    • Returns: A JWT token as a string.
    • Description: Creates a JWT token using the user’s details and configuration settings. The token is signed using a symmetric key and includes claims for the user’s name, email, and role.

Summary

The UserRepository class provides the implementation for user management functions such as registration, login, and retrieval. It leverages Entity Framework Core for data operations, BCrypt for password hashing and verification, and JWT for generating authentication tokens. This class integrates configuration settings from IConfiguration and ensures secure handling of user credentials and authentication processes.


AuthenticationDbContext Class - AuthenticationDbContext.cs

The AuthenticationDbContext class represents the Entity Framework Core context for the authentication system. It is responsible for managing the database interactions related to user data. Here's a detailed breakdown:

Constructor

  • AuthenticationDbContext(DbContextOptions<AuthenticationDbContext> options)
    • Parameters:
      • DbContextOptions<AuthenticationDbContext> options: Configuration options for the DbContext, such as connection strings and provider-specific settings.
    • Description: Initializes a new instance of the AuthenticationDbContext class with the provided options.

Properties

  • public DbSet<AppUser> Users { get; set; }
    • Type: DbSet<AppUser>
    • Description: Represents the collection of AppUser entities in the database. This property allows querying and saving AppUser instances to the database.

Summary

The AuthenticationDbContext class inherits from DbContext, making it the central point for database operations related to authentication. By defining a DbSet<AppUser>, it allows Entity Framework Core to handle CRUD operations for user entities. This setup ensures that the AppUser data model is properly mapped to the underlying database schema and provides a mechanism to interact with user data.

ServiceContainer Class - ServiceContainer.cs

The ServiceContainer class is designed to set up and configure services and middleware for an ASP.NET Core application. It contains extension methods for adding infrastructure services and applying application-level policies.

Methods

  1. AddInfrastructureService

    • Purpose: Configures infrastructure services.
    • Details:
      • Sets up database connectivity and logging.
      • Configures JWT authentication if required.
      • Registers the UserRepository as the implementation for the IUser interface, facilitating dependency injection.
  2. UserInfrastructurePolicy

    • Purpose: Applies application-wide policies and middleware.
    • Details:
      • Adds global exception handling to manage errors.
      • Implements policies to restrict access to the API gateway, ensuring that only authorized calls are processed.

Summary

The ServiceContainer class helps in organizing and configuring various services and middleware components. It supports setting up essential services like database connectivity and authentication, while also ensuring that application-level policies and error handling mechanisms are in place. This approach helps maintain a clean and manageable application setup.


AuthenticationController Class - AuthenticationController.cs

The AuthenticationController class is an ASP.NET Core controller responsible for handling user authentication operations. It provides endpoints for user registration, login, and retrieval of user details.

Attributes

  • [Route("api/[controller]")]: Specifies the route template for the controller, mapping to /api/authentication.
  • [ApiController]: Enables automatic model validation and other API-specific features.
  • [AllowAnonymous]: Allows unauthenticated access to the controller's actions.

Methods

  1. Register

    • Route: /api/authentication/register
    • HTTP Method: POST
    • Purpose: Registers a new user.
    • Details:
      • Checks if the model state is valid; if not, returns a BadRequest with the model state errors.
      • Calls the Register method on the IUser interface to perform the registration.
      • Returns an Ok response if the registration is successful, otherwise returns a BadRequest.
  2. Login

    • Route: /api/authentication/login
    • HTTP Method: POST
    • Purpose: Authenticates a user and issues a token.
    • Details:
      • Validates the model state; returns a BadRequest if invalid.
      • Uses the Login method of the IUser interface to authenticate the user.
      • Responds with an Ok result if login is successful, or a BadRequest if the credentials are invalid.
  3. GetUser

    • Route: /api/authentication/{id:int}
    • HTTP Method: GET
    • Purpose: Retrieves user details by ID.
    • Details:
      • Validates the user ID; returns a BadRequest if the ID is invalid.
      • Calls the GetUser method on the IUser interface to fetch user details.
      • Returns Ok with the user details if the user is found; otherwise, returns NotFound.

Summary

The AuthenticationController class manages user-related actions for authentication purposes. It provides endpoints for registering new users, logging in, and retrieving user details. The controller uses the IUser interface to interact with user-related operations and ensures that all input is validated before processing.


# Here's a follow-up section to encourage engagement and support for Netcode-Hub:

๐ŸŒŸ Get in touch with Netcode-Hub! ๐Ÿ“ซ

1. GitHub: [Explore Repositories] ๐ŸŒ

2. Twitter: [Stay Updated] ๐Ÿฆ

3. Facebook: [Connect Here]๐Ÿ“˜

4. LinkedIn: [Professional Network]๐Ÿ”—

5. Email: [business.netcodehub@gmail.com] ๐Ÿ“ง

# ☕️ If you've found value in Netcode-Hub's work, consider supporting the channel with a coffee!

1. Buy Me a Coffee: [Support Netcode-Hub] ☕️

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