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
andClaimsPrincipal
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 takesAuthDbContext
andIConfiguration
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.
- AdminGetProtectedMessage Method (
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
Post a Comment