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:
Id
- Type:
int - Description: A unique identifier for the user.
- Type:
Name
- Type:
string? - Description: The user's name. It is nullable, allowing the possibility of no name being provided.
- Type:
TelephoneNumber
- Type:
string? - Description: The user's telephone number. It is nullable.
- Type:
Address
- Type:
string? - Description: The user's physical address. It is nullable.
- Type:
Email
- Type:
string? - Description: The user's email address. It is nullable.
- Type:
Password
- Type:
string? - Description: The user's password for authentication. It is nullable.
- Type:
Role
- Type:
string? - Description: The role assigned to the user (e.g., Admin, User). It is nullable.
- Type:
DateRegistered
- Type:
DateTime - Description: The date and time when the user registered. It defaults to the current UTC time at the moment of instantiation.
- Type:
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:
Email
- Type:
string - Description: The user's email address used for logging in.
- Type:
Password
- Type:
string - Description: The user's password used for logging in.
- Type:
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:
Id
- Type:
int - Description: A unique identifier for the user.
- Type:
Name
- Type:
string - Attributes:
[Required] - Description: The user's name. This property is mandatory.
- Type:
TelephoneNumber
- Type:
string - Attributes:
[Required] - Description: The user's telephone number. This property is mandatory.
- Type:
Address
- Type:
string - Attributes:
[Required] - Description: The user's physical address. This property is mandatory.
- Type:
Email
- Type:
string - Attributes:
[Required, EmailAddress] - Description: The user's email address. This property is mandatory and must be a valid email format.
- Type:
Role
- Type:
string - Attributes:
[Required] - Description: The role assigned to the user (e.g., Admin, User). This property is mandatory.
- Type:
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:
Id
- Type:
int - Description: A unique identifier for the user.
- Type:
Name
- Type:
string - Attributes:
[Required] - Description: The user's name. This property is mandatory.
- Type:
TelephoneNumber
- Type:
string - Attributes:
[Required] - Description: The user's telephone number. This property is mandatory.
- Type:
Address
- Type:
string - Attributes:
[Required] - Description: The user's physical address. This property is mandatory.
- Type:
Email
- Type:
string - Attributes:
[Required, EmailAddress] - Description: The user's email address. This property is mandatory and must be in a valid email format.
- Type:
Password
- Type:
string - Attributes:
[Required] - Description: The user's password for authentication. This property is mandatory.
- Type:
Role
- Type:
string - Attributes:
[Required] - Description: The role assigned to the user (e.g., Admin, User). This property is mandatory.
- Type:
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:
Register
- Signature:
Task<Response> Register(AppUserDTO appUserDTO) - Description: Registers a new user using the provided
AppUserDTOobject. - Parameters:
AppUserDTO appUserDTO: The data transfer object containing the user's information required for registration.
- Returns: A
Taskthat represents the asynchronous operation, containing aResponseobject with the outcome of the registration process.
- Signature:
Login
- Signature:
Task<Response> Login(LoginDTO loginDTO) - Description: Authenticates a user using the provided
LoginDTOobject. - Parameters:
LoginDTO loginDTO: The data transfer object containing the user's email and password for login.
- Returns: A
Taskthat represents the asynchronous operation, containing aResponseobject with the outcome of the login attempt.
- Signature:
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
Taskthat represents the asynchronous operation, containing aGetUserDTOobject with the user's details.
- Signature:
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.
- Parameters:
Private Methods
private async Task<AppUser> GetUserByEmail(string email)- Parameters:
string email: The email of the user to find.
- Returns: An
AppUserobject if found, otherwisenull. - Description: Retrieves a user from the database by their email address.
- Parameters:
Public Methods
public async Task<GetUserDTO> GetUser(int userId)- Parameters:
int userId: The ID of the user to retrieve.
- Returns: A
GetUserDTOobject if the user is found, otherwisenull. - Description: Fetches user details by their ID and maps them to the
GetUserDTOdata transfer object.
- Parameters:
public async Task<Response> Login(LoginDTO loginDTO)- Parameters:
LoginDTO loginDTO: Contains the email and password for login.
- Returns: A
Responseobject 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.
- Parameters:
public async Task<Response> Register(AppUserDTO appUserDTO)- Parameters:
AppUserDTO appUserDTO: Contains user information for registration.
- Returns: A
Responseobject 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.
- Parameters:
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.
- Parameters:
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 theDbContext, such as connection strings and provider-specific settings.
- Description: Initializes a new instance of the
AuthenticationDbContextclass with the provided options.
- Parameters:
Properties
public DbSet<AppUser> Users { get; set; }- Type:
DbSet<AppUser> - Description: Represents the collection of
AppUserentities in the database. This property allows querying and savingAppUserinstances to the database.
- Type:
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
AddInfrastructureService
- Purpose: Configures infrastructure services.
- Details:
- Sets up database connectivity and logging.
- Configures JWT authentication if required.
- Registers the
UserRepositoryas the implementation for theIUserinterface, facilitating dependency injection.
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
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
BadRequestwith the model state errors. - Calls the
Registermethod on theIUserinterface to perform the registration. - Returns an
Okresponse if the registration is successful, otherwise returns aBadRequest.
- Checks if the model state is valid; if not, returns a
- Route:
Login
- Route:
/api/authentication/login - HTTP Method:
POST - Purpose: Authenticates a user and issues a token.
- Details:
- Validates the model state; returns a
BadRequestif invalid. - Uses the
Loginmethod of theIUserinterface to authenticate the user. - Responds with an
Okresult if login is successful, or aBadRequestif the credentials are invalid.
- Validates the model state; returns a
- Route:
GetUser
- Route:
/api/authentication/{id:int} - HTTP Method:
GET - Purpose: Retrieves user details by ID.
- Details:
- Validates the user ID; returns a
BadRequestif the ID is invalid. - Calls the
GetUsermethod on theIUserinterface to fetch user details. - Returns
Okwith the user details if the user is found; otherwise, returnsNotFound.
- Validates the user ID; returns a
- Route:
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!
Comments
Post a Comment