ASP.NET Core 9.0 Web API application with authentication, user management, and authorization features.

Here’s a breakdown of the functionality in this class (Program.cs), which configures an ASP.NET Core Web API application with authentication, user management, and authorization features. The code is centered around Google OAuth and role-based user management.


1. Services Configuration

Minimal asp.net core API

Scans and discovers all Minimal API endpoints (routes added via methods like MapGet, MapPost, etc.).

csharp
builder.Services.AddEndpointsApiExplorer();

Swagger Setup
  • What it does: Adds Swagger support for API documentation.
  • Includes a Bearer token security scheme to secure the API endpoints that require authentication.
csharp
builder.Services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Minimal Web API",         Version = "v1" }); c.AddSecurityDefinition("Bearer", ...); c.AddSecurityRequirement(new OpenApiSecurityRequirement() { ... }); });

Authentication Configuration

  • Default Scheme: Sets IdentityConstants.BearerScheme as the default authentication scheme.
  • Configures:
    • Cookies for user session management.
    • Google OAuth using .AddGoogle() for social login.
    • Bearer Token Authentication for issuing and validating tokens.
csharp
builder.Services.AddAuthentication(options => { ... }) .AddCookie(CookieAuthenticationDefaults.AuthenticationScheme) .AddGoogle(options => { ... }) .AddBearerToken(IdentityConstants.BearerScheme);

Identity Setup

  • Adds ASP.NET Core Identity services for managing users and roles.
  • Configures ApplicationDbContext (a SQLite database) for storing user data.
  • Enables token-based authentication and role-based policies.
csharp
builder.Services.AddIdentityCore<User>().AddRoles<IdentityRole>() .AddEntityFrameworkStores<ApplicationDbContext>() .AddApiEndpoints() .AddDefaultTokenProviders();

Database Setup

  • Configures SQLite as the database provider.
csharp
builder.Services.AddDbContext<ApplicationDbContext>(options => options.UseSqlite(@"Data Source=mydatabase.db"));

Authorization Policies

  • AdminPolicy: Requires the user to have an "Admin" role.
  • UserPolicy: Requires the user to have a "User" role.
csharp
builder.Services.AddAuthorization(options => { ... });

2. Middleware Configuration

Development Mode

  • Enables Swagger for API testing in development mode:
csharp
if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); }

HTTPS Redirection

  • Forces HTTPS for all API endpoints:
csharp
app.UseHttpsRedirection();

Identity API Mapping

  • Maps Identity API endpoints for managing users (e.g., register, login):
csharp
app.MapIdentityApi<User>();

3. API Endpoints

Google OAuth Login

  1. Endpoint: /mauth/google
  2. What it does:
    • Initiates Google OAuth login by redirecting the user to Google.
    • Configures AuthenticationProperties with a callback to /mauth/google/callback.
csharp
app.MapGet("/mauth/google", (HttpContext httpContext) => { var props = new AuthenticationProperties {         RedirectUri = "mauth/google/callback"     }; return Results.Challenge(props,         new List<string> { GoogleDefaults.AuthenticationScheme }); });

Google OAuth Callback

  1. Endpoint: /mauth/google/callback
  2. What it does:
    • Handles the OAuth callback from Google.
    • Authenticates the user using cookies.
    • Creates a new user if the user does not exist in the database.
    • Issues a Bearer token and redirects to the app with token data.
csharp
app.MapGet("/mauth/google/callback",         async (HttpContext context,             UserManager<User> userManager,             RoleManager<IdentityRole> roleManager) => { ... });

Register a User

  1. Endpoint: /registerUser
  2. What it does:
    • Creates a new user in the database with the role "User."
csharp
app.MapPost("/registerUser", async (...));

Delete a User

  1. Endpoint: /users/{email}
  2. What it does:
    • Deletes a user from the database.
    • Requires the "AdminPolicy."
csharp
app.MapDelete("/users/{email}",     async (...)).RequireAuthorization("AdminPolicy");

Check If User Can Delete

  1. Endpoint: /users/candelete
  2. What it does:
    • Checks if the logged-in user has the "Admin" role.
csharp
app.MapGet("/users/candelete", async (...));

Get Current User Info

  1. Endpoint: /me
  2. What it does:
    • Returns the logged-in user's email and birth date.
    • Requires authentication.
csharp
app.MapGet("/me", async (...)).RequireAuthorization();

List All Users

  1. Endpoint: /users
  2. What it does:
    • Returns a list of all users with their emails and birth dates.
    • Requires authentication.
csharp
app.MapGet("/users", async (...)).RequireAuthorization();

4. Database Initialization

  • Creates an admin user and several test users during application startup.
csharp
using (var scope = app.Services.CreateScope()) { var services = scope.ServiceProvider; var dbContext = services.GetRequiredService<ApplicationDbContext>(); dbContext.Database.EnsureCreated(); var userManager = services.GetRequiredService<UserManager<User>>(); var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>(); await userManager.CreateUserWithRoleAsync(roleManager,             "admin@yourdomain.com",             "Admin!",             new DateOnly(1999, 1, 1),             "Admin); await userManager.CreateUserWithRoleAsync(roleManager,             "user@yourcompany.com",             "User!",             new DateOnly(1999, 1, 1),              "User"); }

Key Functionalities

  1. Google OAuth: Allows users to log in via Google.
  2. Role-Based Access Control: Admin and user roles with authorization policies.
  3. Token Authentication: Issues and validates Bearer tokens for securing API endpoints.
  4. CRUD Operations on Users: Register, delete, list users, and check authorization.
  5. Swagger Documentation: Enables API testing and exploration in development.

Comments

Popular posts from this blog

Configuring Any .NET 9.0 Program to Run in Docker: A Step-by-Step Guide

Understand .NET 9.0 Blazor Hosting Models

Understanding a Multi-Stage Dockerfile for .NET 9 Application