Skip to main content

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

Part4️⃣- Authentication & Rate Limiting | ๐Ÿš€ Mastering Microservices: Using YARP as Your Ultimate API Gateway & Reverse Proxy! ๐Ÿ”—๐Ÿ’ก

Authentication Detailed Description

Add Database Connection

We start by setting up a database connection using Entity Framework Core. In this example, SQLite is used as the database provider. By specifying a connection string, we ensure that the application has a designated database file (DemoDb.db) where all data, including user and role information, will be stored and managed.

Add Identity

ASP.NET Core Identity is integrated to handle user authentication and authorization. This setup includes:

  • User and Role Management: Configuring Identity to use default classes for users and roles.
  • Entity Framework Integration: Specifying that Identity should utilize Entity Framework Core with our designated DbContext for managing user and role data.
  • Role-Based Authorization: Enabling the application to support roles, which can be used to enforce access control throughout the application.

Add JWT Authentication

JWT (JSON Web Token) authentication is configured to secure API endpoints:

  • Authentication Scheme: The application is set to use JWT bearer tokens for authentication.
  • JWT Configuration: The secret key for signing tokens is retrieved from configuration settings. The issuer and audience are also specified to ensure that tokens are correctly issued and validated.
  • Token Validation Parameters: Various parameters are set to validate the tokens, such as issuer, audience, and signing key. This ensures that only valid tokens are accepted, providing a secure way to verify users.

Add Authorization Policies

Custom authorization policies are defined to control access based on user roles:

  • Admin Policy: Requires users to be authenticated and to have the "Admin" role to access certain resources.
  • User Policy: Requires users to be authenticated and to have the "User" role to access specific parts of the application.

Middleware Configuration

Finally, the middleware pipeline is configured to incorporate the necessary services:

  • Authentication Middleware: Ensures that every request goes through an authentication check.
  • Authorization Middleware: Verifies that authenticated users have the necessary permissions to access resources.
  • Request and Response Transformation: Custom middleware is added for transforming requests and responses as needed.
  • Rate Limiting Middleware: Controls the rate of incoming requests to prevent abuse and ensure fair usage of the application's resources.
  • Controller Mapping: Enables routing to controller actions, making sure that the endpoints defined in controllers are accessible.

Summary

By following these steps, we set up a robust and secure application infrastructure. The database connection, identity management, JWT authentication, and custom authorization policies work together to ensure that only authorized users can access specific resources. Middleware components enhance the application's functionality by handling requests efficiently and securely. This configuration lays a strong foundation for building secure and scalable microservices in .NET 8.



IdentityController Class

The IdentityController class is an API controller in an ASP.NET Core application that manages user authentication and registration. It leverages the ASP.NET Core Identity framework to handle user management and JWT (JSON Web Token) generation.

Route and API Controller Attributes

The controller is decorated with the [Route("api/[controller]")] attribute, which sets the base route for all actions in the controller to /api/identity. The [ApiController] attribute enables API-specific features such as automatic model validation and binding source inference.

Constructor

The constructor of the IdentityController class accepts three parameters:

  • UserManager: Manages user-related operations.
  • RoleManager: Manages role-related operations.
  • IConfiguration: Provides access to configuration settings.

Authenticate Method

The Authenticate method is an HTTP POST endpoint that takes an email and password as parameters. It performs the following actions:

  • Attempts to find a user by email using the UserManager.
  • If the user does not exist, it calls the Register method to create a new user.
  • If the user exists, it calls the Login method to generate a JWT for the user.

Login Method

The Login method generates a JWT for an existing user. It performs the following actions:

  • Creates a security key using a secret key from the configuration.
  • Generates signing credentials using the security key.
  • Creates user claims including email, name, and role.
  • Generates a JWT using the claims, issuer, audience, and signing credentials.
  • Returns the JWT as a string.

Register Method

The Register method creates a new user and assigns them a role. It performs the following actions:

  • Creates a new IdentityUser with the provided email and password.
  • Checks if the user creation was successful.
  • If successful, it checks if the "Admin" role exists. If not, it creates the "Admin" role and assigns the new user to it. Otherwise, it checks if the "User" role exists. If not, it creates the "User" role and assigns the new user to it.
  • Returns "Successful" if the user was created and assigned a role successfully, otherwise returns "Unsuccessful".

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