REST Minimal Api with Authentication

Adding external authentication providers like Azure AD or Google to a .NET Core Minimal API involves integrating the appropriate authentication libraries and configuring the services to use these providers. Below is a modified version of the original code that adds external authentication using Azure AD and Google.

Step 1: Install Required NuGet Packages

First, you need to install the necessary NuGet packages to support authentication:

bashCopy codedotnet add package Microsoft.AspNetCore.Authentication.JwtBearer
dotnet add package Microsoft.Identity.Web
dotnet add package Microsoft.Identity.Web.UI
dotnet add package Microsoft.AspNetCore.Authentication.Google

Step 2: Configure Authentication in Program.cs

Modify the Program.cs file to configure authentication using Azure AD and Google:

csharpCopy codeusing Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication.Google;

var builder = WebApplication.CreateBuilder(args);

// Configure Azure AD Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(options =>
    {
        builder.Configuration.Bind("AzureAd", options);
    });

// Configure Google Authentication
builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = GoogleDefaults.AuthenticationScheme;
})
.AddCookie()
.AddGoogle(GoogleDefaults.AuthenticationScheme, options =>
{
    options.ClientId = builder.Configuration["Authentication:Google:ClientId"];
    options.ClientSecret = builder.Configuration["Authentication:Google:ClientSecret"];
});

builder.Services.AddAuthorization();

var app = builder.Build();

// Enable authentication middleware
app.UseAuthentication();
app.UseAuthorization();

var products = new List<Product>
{
    new Product { Id = 1, Name = "Product 1", Price = 10.00m },
    new Product { Id = 2, Name = "Product 2", Price = 20.00m },
    new Product { Id = 3, Name = "Product 3", Price = 30.00m }
};

// Secure the endpoints with [Authorize] attribute

app.MapGet("/products", () =>
{
    return Results.Ok(products);
}).RequireAuthorization();

app.MapGet("/products/{id:int}", (int id) =>
{
    var product = products.FirstOrDefault(p => p.Id == id);
    if (product is null)
    {
        return Results.NotFound();
    }
    return Results.Ok(product);
}).RequireAuthorization();

app.MapPost("/products", (Product product) =>
{
    product.Id = products.Max(p => p.Id) + 1;
    products.Add(product);
    return Results.Created($"/products/{product.Id}", product);
}).RequireAuthorization();

app.MapPut("/products/{id:int}", (int id, Product updatedProduct) =>
{
    var product = products.FirstOrDefault(p => p.Id == id);
    if (product is null)
    {
        return Results.NotFound();
    }

    product.Name = updatedProduct.Name;
    product.Price = updatedProduct.Price;

    return Results.Ok(product);
}).RequireAuthorization();

app.MapDelete("/products/{id:int}", (int id) =>
{
    var product = products.FirstOrDefault(p => p.Id == id);
    if (product is null)
    {
        return Results.NotFound();
    }

    products.Remove(product);
    return Results.NoContent();
}).RequireAuthorization();

app.Run();

Step 3: Configure Azure AD and Google in appsettings.json

Add the configuration settings for Azure AD and Google to your appsettings.json file:

jsonCopy code{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "yourtenant.onmicrosoft.com",
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",
    "ClientSecret": "your-client-secret"
  },
  "Authentication": {
    "Google": {
      "ClientId": "your-google-client-id",
      "ClientSecret": "your-google-client-secret"
    }
  }
}

Step 4: Secure the Endpoints

Notice that in the code, the .RequireAuthorization() method is used to secure each endpoint. This ensures that only authenticated users can access these endpoints.

Step 5: Test the Application

Run the application and try accessing the secured endpoints. When you navigate to one of the secured routes, you should be redirected to the Azure AD or Google login page, depending on the configured provider.

Summary:

  • Authentication Setup: Configured external authentication using Azure AD and Google.
  • Endpoint Security: Used .RequireAuthorization() to secure API endpoints.
  • Configuration: Managed authentication settings through appsettings.json.

This setup allows your .NET Core Minimal API to authenticate users via external providers like Azure AD and Google, adding a robust security layer to your RESTful endpoints.

References

Here are some useful web references that can help you increase your knowledge of implementing REST endpoints using .NET Core Minimal API with external authentication providers like Azure AD or Google:

1. Microsoft Learn – Minimal APIs in .NET

  • Overview: This documentation provides an in-depth introduction to Minimal APIs in .NET, covering how to create RESTful endpoints and integrate with authentication providers.
  • Microsoft Learn – Minimal APIs in .NET

2. Microsoft Learn – Azure AD Authentication in ASP.NET Core

3. Microsoft Identity Web Documentation

  • Overview: Documentation for the Microsoft.Identity.Web library, which simplifies integrating Azure AD authentication into .NET Core applications, including Minimal APIs.
  • Microsoft Identity Web Documentation

4. Microsoft Learn – Google Authentication in ASP.NET Core

5. Code Maze – Authentication in ASP.NET Core with Google

6. YouTube – ASP.NET Core Minimal APIs with Authentication by Tim Corey

7. GitHub – ASP.NET Core Minimal API Examples with Authentication

8. Pluralsight – Authentication and Authorization in ASP.NET Core

9. Azure Active Directory Developer Documentation

10. Google Identity Platform Documentation

  • Overview: Official documentation for Google Identity services, including OAuth 2.0 and OpenID Connect, and how to integrate them with your .NET Core applications.
  • Google Identity Platform Documentation

11. Microsoft Identity and Authentication Library (MSAL)

  • Overview: Documentation and tutorials for using MSAL (Microsoft Authentication Library) to authenticate users with Azure AD in .NET Core applications.
  • MSAL Documentation

12. TutorialsPoint – ASP.NET Core Minimal APIs

13. Stack Overflow – ASP.NET Core Minimal APIs with External Authentication

14. Reddit – .NET Core Minimal APIs and Authentication Discussion

15. Dev.to – ASP.NET Core Minimal API Authentication

These resources provide a comprehensive overview of how to implement REST endpoints using .NET Core Minimal API with external authentication providers like Azure AD and Google, helping you to enhance the security and functionality of your web applications.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *