Skip to main content

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

๐Ÿ”Secure .NET 8 Web API with Access Token Authentication : Role-Based Authorization ๐Ÿš€

 

Description | Custom AuthenticationHandler

This code defines a custom authentication handler for a .NET Web API using access tokens. The handler is implemented by the CustomAuthenticationHandler class, which inherits from AuthenticationHandler<AuthenticationSchemeOptions>. Here's a breakdown of its functionality:

  • Namespace and Imports: The code is organized under the DemoAccessTokenAuthInWebApi.Scheme namespace and uses various namespaces for authentication, Entity Framework Core, logging, and security.

  • Constructor: The constructor initializes the handler with necessary services such as options, logger, URL encoder, and an instance of AuthDbContext, which is used for database interactions.

  • HandleAuthenticateAsync Method: This method handles the authentication logic:

    • It retrieves the authorization header from the incoming request.
    • If the header is missing, it returns an authentication failure result.
    • The token is extracted, decoded, and parsed to retrieve the user ID.
    • The user’s role and details are fetched from the database using the extracted ID.
    • Claims are created for the authenticated user, including their ID, name, and role.
    • A ClaimsIdentity and ClaimsPrincipal are created using the claims.
    • An AuthenticationTicket is generated and returned as a success result if the token is valid.
    • If any error occurs during this process, an authentication failure result is returned.

This custom authentication handler allows the Web API to validate access tokens, extract user information, and establish an authenticated user context for subsequent requests.


Description | AuthenticationController

This code defines an AuthenticationController for a .NET Web API that handles user registration, login, and protected routes using custom authentication. The controller is implemented within the DemoAccessTokenAuthInWebApi.Controllers namespace. Here's a detailed breakdown of its functionality:

  • Namespace and Imports: The code utilizes namespaces for data access, DTOs, authorization, MVC, and Entity Framework Core.

  • Controller Definition: The AuthenticationController is an API controller that takes AuthDbContext and IConfiguration as dependencies through its constructor.

  • Register Method (POST /api/authentication/register):

    • This method handles user registration.
    • It checks if the user data is provided and if the email already exists in the database.
    • If the user does not exist, it adds a new user to the AppUsers table with a hashed password using BCrypt.
    • It also adds the user's role to the UserRoles table.
    • The method returns a success response if the registration is successful.
  • Login Method (POST /api/authentication/login/{email}/{password}):

    • This method handles user login.
    • It validates the provided email and password.
    • If the user is found and the password is verified using BCrypt, it retrieves the user's role.
    • An access token is generated by encoding a string containing the authentication key, user name, and user ID.
    • The method returns the access token as the response.
  • Protected Routes:

    • AdminGetProtectedMessage Method (GET /api/authentication/protected-admin):
      • This method is protected and requires the user to be authenticated with the "Netcode-Scheme" and have the "Admin" role.
      • It returns a message indicating that the user is authorized as an Admin.
    • UserGetProtectedMessage Method (GET /api/authentication/protected-user):
      • This method is protected and requires the user to be authenticated with the "Netcode-Scheme" and have the "User" role.
      • It returns a message indicating that the user is authorized as a User.

Key Points:

  • User Registration: Securely registers users by hashing passwords and storing user roles.
  • User Login: Authenticates users and generates an access token for subsequent requests.
  • Protected Routes: Demonstrates role-based access control for different user roles (Admin and User).

This controller provides a foundational approach to implementing user authentication and authorization in a .NET Web API, leveraging Entity Framework Core for database operations and BCrypt for password hashing.

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