Skip to main content

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

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

RESPONSE

This code defines a C# record named Response with two properties: Flag, a boolean initialized to false, and Message, a string that defaults to null. Records in C# are immutable reference types that provide built-in functionality for value equality and concise syntax for defining data containers.

GLOBAL EXCEPTION

This code defines a middleware class named GlobalException for handling exceptions and specific HTTP response statuses in an ASP.NET Core application. The middleware checks for and modifies responses with status codes 401 (Unauthorized), 403 (Forbidden), and 429 (Too Many Requests). It also handles internal server errors and request timeouts by logging the exceptions and sending user-friendly error messages in JSON format.

Key components of this middleware include:

  • Dependencies: Uses Microsoft.AspNetCore.Http, Microsoft.AspNetCore.Mvc, System.Net, and System.Text.Json.
  • Constructor: Takes a RequestDelegate called next.
  • InvokeAsync: The main method that processes HTTP requests, handles exceptions, and modifies response headers based on specific conditions.
  • ModifyHeader: A private method that sets the response content type to JSON and writes a user-friendly error message to the response.

Functionality:

  1. Constructor: Stores the RequestDelegate for the next middleware in the pipeline.
  2. InvokeAsync:
    • Tries to process the request by calling the next middleware.
    • Modifies the response for specific status codes (401, 403, 429).
    • Catches exceptions, logs them, and modifies the response for internal server errors and request timeouts.
  3. ModifyHeader:
    • Sets the response content type to JSON.
    • Writes a ProblemDetails object with the error message, status code, and title to the response.

This middleware ensures that user-friendly messages are sent to the client for specific error conditions, enhancing the user experience by providing clear and concise error information.

List To Only Gateway API

This code defines a middleware class named ListenToOnlyApiGateway that ensures requests are processed only if they originate from an API Gateway. It does this by checking for a specific header (Api-Gateway) in the request. If the header is not present, the middleware responds with a 503 Service Unavailable status and a relevant message.

Key components of this middleware include:

  • Dependencies: Uses Microsoft.AspNetCore.Http.
  • Constructor: Takes a RequestDelegate called next.
  • InvokeAsync: The main method that processes HTTP requests, checks for the Api-Gateway header, and either forwards the request to the next middleware or returns a 503 status code.

Functionality:

  1. Constructor: Stores the RequestDelegate for the next middleware in the pipeline.
  2. InvokeAsync:
    • Extracts the Api-Gateway header from the request.
    • Checks if the header is present:
      • If the header is missing, sets the response status to 503 Service Unavailable and writes a message to the response body.
      • If the header is present, forwards the request to the next middleware.

GENERIC INTERFACE

This code defines a generic interface IGenericInterface<T> in C# for basic CRUD operations and querying entities. The interface provides a standard set of methods for creating, updating, deleting, and retrieving entities, making it reusable for different types of entities in an application. The operations return a custom Response type for indicating the result of the operation.

Key components of this interface include:

  • Dependencies: Uses eCommerce.SharedLibrary.Responses and System.Linq.Expressions.
  • Generic Type Parameter: T is constrained to be a class.
  • CRUD Methods: Defines methods for Create, Update, Delete, and Retrieve operations.

This interface provides a consistent way to handle data operations across different entity types, promoting code reuse and maintainability. The use of generic type parameter T allows it to be flexible and applicable to various entities within the application.

JWT AUTHENTICATION SCHEME

This code defines a static class JWTAuthenticationScheme that provides an extension method to add and configure JWT (JSON Web Token) authentication in an ASP.NET Core application. This extension method is designed to be used with the dependency injection system, allowing easy integration of JWT authentication.

Key components of this implementation include:

  • Dependencies: Uses Microsoft.AspNetCore.Authentication.JwtBearer, Microsoft.Extensions.Configuration, Microsoft.Extensions.DependencyInjection, and Microsoft.IdentityModel.Tokens.
  • Extension Method: The AddJWTAuthenticationScheme method configures the JWT authentication scheme using settings from the application's configuration.

Functionality:

  • Extension Method:
    public static IServiceCollection AddJWTAuthenticationScheme(this IServiceCollection services, IConfiguration config)
    - Configures JWT authentication using settings from the application's configuration file (appsettings.json or another configuration source). - Adds the JWT authentication scheme to the service collection. - Configures the JwtBearer options: - Retrieves the key, issuer, and audience from the configuration. - Sets RequireHttpsMetadata to false to allow HTTP (not recommended for production). - Saves the token after successful authentication. - Sets up token validation parameters, including validation of the issuer, audience, and signing key using a symmetric security key.

This extension method simplifies the setup of JWT authentication in an ASP.NET Core application, ensuring that the necessary configuration is added to the dependency injection container. By calling AddJWTAuthenticationScheme in the Startup.cs or Program.cs file, developers can easily integrate JWT authentication into their application.

SHARED SERVICE CONTAINER

This code defines a static class SharedServiceContainer that provides extension methods to add and configure shared services and middleware in an ASP.NET Core application. These methods include setting up a database context, configuring logging with Serilog, adding JWT authentication, and registering custom middleware.

        
# 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