User Authentication API
Relevant source files
The following files were used as context for generating this wiki page:The User Authentication API provides core functionalities for user management, including registration, login, and password recovery. It is a RESTful API built with ASP.NET Core that serves as the backend for user-facing authentication processes. The system is designed with a clear separation of concerns, utilizing a service layer for business logic, Entity Framework Core for data persistence, and controllers to handle HTTP requests.
This API exposes endpoints under the /api/v1/user route. It manages user data through the User model, which is stored in a SQL Server database. The password management feature includes a token-based reset mechanism delivered via email.
Architecture
The authentication system follows a layered architecture to separate responsibilities, making the codebase more modular and maintainable. The main components are the Controller, Service Layer, and Data Access Layer.
- Controller (
UserController): The entry point for all API requests. It receives HTTP requests, validates input, calls the appropriate service methods, and formats the HTTP response. - Service (
IUserService/UserService): Contains the core business logic. It orchestrates operations like user creation, validation, and password reset token generation. It is injected into the controller via dependency injection. - Data Access (
UserDBContext): Manages all database interactions using Entity Framework Core. It is responsible for querying and persistingUserentities. - Models: Define the data structures used throughout the application, including database entities (
User) and Data Transfer Objects (DTOs) likeUserLoginandUserRegister.
This diagram illustrates the flow of a request through the different layers of the application.
Data Models
The API relies on several key data models to handle user information and requests.
User Entity
The User entity represents a user in the database. It includes credentials, role information, and fields for the password reset process.
The table below details the properties of the User entity and their database constraints as defined in UserConfiguration.
| Property | Type | Constraints | Description |
|---|---|---|---|
Id | int | Primary Key | Unique identifier for the user. |
Email | string | Required, MaxLength(100) | User's email address. |
UserName | string | Required, MaxLength(50) | Unique username for login. |
Password | string | Required, MaxLength(256) | User's password. Note: Stored as plain text. |
Role | bool | Required | User's role (true for admin, false for regular user). |
ResetToken | string? | Nullable | Token for password reset requests. |
ResetTokenExpiration | DateTime? | Nullable | Expiration date and time for the reset token. |
Sources: Models/User.cs:5-14, Configuration/UserConfiguration.cs:11-29
Data Transfer Objects (DTOs)
These models are used to transfer data between the client and the API for specific actions.
UserRegister: Used for the registration endpoint. ContainsEmail,UserName, andPassword.
Sources: Models/UserRegister.csUserLogin: Used for the login endpoint. ContainsUserNameandPassword.
Sources: Models/UserLogin.csForgotPasswordRequest: Used to request a password reset. Contains the user'sEmail.
Sources: Controllers/Login/UserController.cs:134ResetPasswordRequest: Used to submit a new password. ContainsEmail,Token, andNewPassword.
Sources: Controllers/Login/UserController.cs:162
API Endpoints
All user authentication endpoints are located under the base route api/v1/user.
| Method | Path | Description |
|---|---|---|
POST | /register | Registers a new user. |
POST | /login | Authenticates a user and returns their details. |
POST | /forgot-password | Initiates the password reset process by sending an email with a token. |
POST | /reset-password | Resets the user's password using a valid token. |
GET | / | Retrieves a list of all users. |
GET | /{id} | Retrieves a single user by their ID. |
Sources: Controllers/Login/UserController.cs
User Registration
The registration process creates a new user account after validating that the username and email are not already in use.
Endpoint: POST /api/v1/user/register
Request Body: UserRegister object.
The following sequence diagram shows the registration flow.
User Login
The login process validates a user's credentials. It checks for the existence of the username and then performs a direct, case-sensitive string comparison on the password.
Endpoint: POST /api/v1/user/login
Request Body: UserLogin object.
The login process is illustrated below.
Password Reset
The password reset is a two-step process: requesting a reset token and then submitting the new password with that token.
1. Forgot Password
This step generates a unique reset token, saves it to the user's record with a 1-hour expiration, and sends it to the user's email.
Endpoint: POST /api/v1/user/forgot-password
The email sending logic in UserService uses a hardcoded Gmail SMTP server and credentials.
// Service/user/UserService.cs:125-129
var smtpClient = new SmtpClient("smtp.gmail.com")
{
Port = 587,
Credentials = new NetworkCredential("chihtt1234@gmail.com", "limj cuov rrtf sxzm"),
EnableSsl = true,
};
Sources: Service/user/UserService.cs:125-129
2. Reset Password
This step validates the provided token and updates the user's password. The token is cleared after a successful reset.
Endpoint: POST /api/v1/user/reset-password
Service Layer and Dependency Injection
The business logic is encapsulated within the UserService, which implements the IUserService interface. This promotes loose coupling and testability.
IUserService Interface
Defines the contract for user-related operations.
// Service/user/IUserService.cs
public interface IUserService
{
Task<List<User>> GetUsersAsync();
Task<User> GetUserByIdAsync(int userId);
Task<bool> AddUserAsync(User newUser);
Task<bool> UpdateUserAsync(User user);
Task<bool> DeleteUserAsync(int userId);
Task<User> GetUserByUserNameAsync(string userName);
Task<User> CreateUserAsync(User user);
Task<User> GetUserByEmailAsync(string email);
Task<bool> SendResetPasswordEmailAsync(string email, string resetToken);
}
Sources: Service/user/IUserService.cs
Dependency Injection
The IUserService and UserDBContext are registered in the application's service container in Program.cs. This allows them to be injected into dependent classes, such as UserController.
// Program.cs:26-29
builder.Services.AddDbContext<UserDBContext>(option =>
{
option.UseSqlServer(builder.Configuration.GetConnectionString("UserDataBase"));
});
// Program.cs:38
builder.Services.AddTransient<IUserService, UserService>();
Sources: Program.cs:26-29, 38
Database Seeding
The application includes a database seeder to ensure a default admin user exists upon database creation. This is configured in DatabaseSeeder.cs and applied in UserDBContext.
// Seeders/DatabaseSeeder.cs:9-19
public static void Seed(this ModelBuilder modelBuilder)
{
_ = modelBuilder.Entity<User>().HasData(
new User()
{
Id = 1,
Email = "chihtt123@gmail.com",
UserName = "chi",
Password = "123",
Role = true
}
);
}
Sources: Seeders/DatabaseSeeder.cs:9-19, Data/UserDBContext.cs:26
Summary
The User Authentication API provides a complete, if basic, solution for managing user identity within the WEBAPI project. It exposes a clear set of RESTful endpoints for registration, login, and a full password reset cycle. The architecture is well-defined, separating concerns into controllers, services, and data access layers. Key implementation details include the use of Entity Framework Core for database interaction, a token-based password reset mechanism, and dependency injection for service management. However, it is important to note the current implementation stores passwords in plain text and contains hardcoded credentials for its email service, which are significant security risks that should be addressed.