Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions .github/workflows/publish_entraid.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
name: Publish Microsoft Entra ID for Simple Authentication on NuGet

permissions:
contents: write
id-token: write

on:
push:
branches: [ master ]
paths: [ 'src/SimpleAuthentication.EntraId/**' ]
workflow_dispatch:

env:
NET_VERSION: '11.x'
PROJECT_NAME: src/SimpleAuthentication.EntraId
PROJECT_FILE: SimpleAuthentication.EntraId.csproj
TAG_NAME: entraid
RELEASE_NAME: SimpleAuthenticationTools.EntraId

jobs:
build:
name: Publish Microsoft Entra ID for Simple Authentication on NuGet
runs-on: ubuntu-latest

steps:
- name: Checkout
uses: actions/checkout@v6
with:
fetch-depth: 0 # avoid shallow clone so nbgv can do its work.

- name: Setup .NET SDK ${{ env.NET_VERSION }}
uses: actions/setup-dotnet@v5
with:
dotnet-version: ${{ env.NET_VERSION }}
dotnet-quality: 'ga'

- name: Nerdbank.GitVersioning
uses: dotnet/nbgv@v0.4
id: nbgv
with:
path: ${{ env.PROJECT_NAME }}

- name: Package
run: dotnet pack -c Release -o . '${{ env.PROJECT_NAME }}/${{ env.PROJECT_FILE }}'

- name: NuGet login (OIDC → temp API key)
uses: NuGet/login@v1
id: login
with:
user: ${{ secrets.NUGET_USER }}

- name: Publish on NuGet
run: dotnet nuget push *.nupkg --api-key ${{steps.login.outputs.NUGET_API_KEY}} -s https://api.nuget.org/v3/index.json

- name: Create release
uses: softprops/action-gh-release@v2
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: v${{ steps.nbgv.outputs.NuGetPackageVersion }}
name: ${{ env.RELEASE_NAME }} ${{ steps.nbgv.outputs.NuGetPackageVersion }}
draft: false
prerelease: false
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -352,3 +352,4 @@ MigrationBackup/
/src/SimpleAuthentication/SimpleAuthentication.xml
/src/SimpleAuthentication.Abstractions/SimpleAuthentication.Abstractions.xml
/src/SimpleAuthentication.Swashbuckle/SimpleAuthentication.Swashbuckle.xml
/src/SimpleAuthentication.EntraId/SimpleAuthentication.EntraId.xml
49 changes: 48 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
[![NuGet](https://img.shields.io/nuget/dt/SimpleAuthenticationTools)](https://www.nuget.org/packages/SimpleAuthenticationTools)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/marcominerva/SimpleAuthentication/blob/master/LICENSE)

A library to easily integrate Authentication in ASP.NET Core projects. Currently it supports JWT Bearer, API Key and Basic Authentication in both Controller-based and Minimal API projects.
A library to easily integrate Authentication in ASP.NET Core projects. Currently it supports JWT Bearer, API Key and Basic Authentication in both Controller-based and Minimal API projects. Service-to-service authentication with Microsoft Entra ID is available as an [optional package](#microsoft-entra-id-authentication).

> [!IMPORTANT]
> **Update from Version 2.x to 3.x**
Expand Down Expand Up @@ -378,11 +378,58 @@ app.MapGet("api/me", (ClaimsPrincipal user) =>
.RequireAuthorization(policyNames: "UserProfile")
```

## Microsoft Entra ID authentication

If your services use Microsoft Entra ID to talk to each other, you can install the optional [SimpleAuthentication.EntraId](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId) package. Search for *SimpleAuthenticationTools.EntraId* in the **Package Manager GUI** or run the following command in the **.NET CLI**:

```shell
dotnet add package SimpleAuthenticationTools.EntraId
```

The package is built on top of [Microsoft.Identity.Web](https://learn.microsoft.com/entra/msidweb/) and adds a Microsoft Entra ID scheme next to the ones you are already using, without changing the default scheme and without adding a fallback policy:

```csharp
using SimpleAuthentication;

var builder = WebApplication.CreateBuilder(args);

// Registers the schemes defined in the Authentication section, then adds a scheme (named EntraId)
// that validates the access tokens issued by a single Microsoft Entra ID tenant.
builder.Services.AddSimpleAuthentication(builder.Configuration)
.AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd"))
// The following lines are required only if the application calls other APIs.
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();

// Registers an HTTP client that calls another API using an app-only access token.
builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory"))
.AddTypedClient<InventoryClient>();

var app = builder.Build();

// ...

// Requires an app-only access token that contains the Orders.Read application role.
app.MapGet("api/orders", () => TypedResults.Ok())
.RequireEntraIdApplicationRole("Orders.Read");

app.Run();
```

In short:

- only the endpoints that explicitly require it are protected by Microsoft Entra ID. Policies based on application roles accept app-only tokens and reject the ones issued on behalf of a user;
- HTTP clients acquire app-only tokens using the credentials (for example a managed identity federated with the app registration) and the token cache configured for Microsoft.Identity.Web. They can send requests only to the configured HTTPS base address and never forward the token of the incoming request;
- HTTP clients use timeouts, retries and circuit breaker, but the requests that can write data are never retried automatically.

Refer to the [documentation of the package](https://github.com/marcominerva/SimpleAuthentication/tree/master/src/SimpleAuthentication.EntraId) for configuration and usage details.

## Samples

- JWT Bearer ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/JwtBearerSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/JwtBearerSample))
- API Key ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/ApiKeySample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/ApiKeySample))
- Basic Authentication ([Controller](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/Controllers/BasicAuthenticationSample) | [Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/BasicAuthenticationSample))
- Microsoft Entra ID ([Minimal API](https://github.com/marcominerva/SimpleAuthentication/tree/master/samples/MinimalApis/EntraIdMicroservices))

## Contribute

Expand Down
8 changes: 8 additions & 0 deletions SimpleAuthentication.slnx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,21 @@
<Project Path="samples/MinimalApis/JwtBearerSample/JwtBearerSample.csproj" />
<Project Path="samples/MinimalApis/JwtBearerSample.Swashbuckle/JwtBearerSample.Swashbuckle.csproj" />
</Folder>
<Folder Name="/samples/Minimal APIs/EntraIdMicroservices/">
<Project Path="samples/MinimalApis/EntraIdMicroservices/InventoryApi/InventoryApi.csproj" />
<Project Path="samples/MinimalApis/EntraIdMicroservices/OrdersApi/OrdersApi.csproj" />
</Folder>
<Folder Name="/Solution Items/">
<File Path=".editorconfig" />
<File Path="src/Directory.Build.props" />
</Folder>
<Folder Name="/src/">
<Project Path="src/SimpleAuthentication.Abstractions/SimpleAuthentication.Abstractions.csproj" />
<Project Path="src/SimpleAuthentication.EntraId/SimpleAuthentication.EntraId.csproj" />
<Project Path="src/SimpleAuthentication.Swashbuckle/SimpleAuthentication.Swashbuckle.csproj" />
<Project Path="src/SimpleAuthentication/SimpleAuthentication.csproj" />
</Folder>
<Folder Name="/tests/">
<Project Path="tests/SimpleAuthentication.EntraId.Tests/SimpleAuthentication.EntraId.Tests.csproj" />
</Folder>
</Solution>
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>simpleauthentication-entraid-inventoryapi</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\..\src\SimpleAuthentication.EntraId\SimpleAuthentication.EntraId.csproj" />
</ItemGroup>

</Project>
34 changes: 34 additions & 0 deletions samples/MinimalApis/EntraIdMicroservices/InventoryApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
using SimpleAuthentication;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddProblemDetails();

// This API accepts Microsoft Entra ID tokens only and does not call other APIs,
// so the scheme is added to the standard authentication builder and no credentials are required.
builder.Services.AddAuthentication()
.AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd"));

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();

app.UseExceptionHandler();
app.UseStatusCodePages();

app.UseAuthentication();
app.UseAuthorization();

// This endpoint requires an app-only access token that contains the 'Inventory.Read' application role.
app.MapGet("api/products", () =>
{
Product[] products = [new(1, "Keyboard", 12), new(2, "Monitor", 0)];
return TypedResults.Ok(products);
})
.RequireEntraIdApplicationRole("Inventory.Read");

app.Run();

public record class Product(int Id, string Name, int AvailableQuantity);
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"InventoryApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7102;http://localhost:5102",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<tenant-id>", // Required: the ID of the Microsoft Entra ID tenant
"ClientId": "<inventory-api-client-id>" // Required: the application (client) ID of the Inventory API
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net11.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>simpleauthentication-entraid-ordersapi</UserSecretsId>
</PropertyGroup>

<ItemGroup>
<ProjectReference Include="..\..\..\..\src\SimpleAuthentication.EntraId\SimpleAuthentication.EntraId.csproj" />
<ProjectReference Include="..\..\..\..\src\SimpleAuthentication\SimpleAuthentication.csproj" />
</ItemGroup>

</Project>
53 changes: 53 additions & 0 deletions samples/MinimalApis/EntraIdMicroservices/OrdersApi/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
using Microsoft.Identity.Web;
using SimpleAuthentication;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddProblemDetails();

// Add the authentication schemes defined in the Authentication section of the configuration (none in this sample),
// then add Microsoft Entra ID as an additional scheme. Default schemes and authorization policies are not changed.
builder.Services.AddSimpleAuthentication(builder.Configuration)
.AddEntraIdJwtBearer(builder.Configuration.GetSection("AzureAd"))
// The following lines are needed only because this API calls another API using its own identity.
.EnableTokenAcquisitionToCallDownstreamApi()
.AddInMemoryTokenCaches();

// Register the HTTP client that calls the Inventory API using an app-only access token.
builder.Services.AddEntraIdHttpClient("Inventory", builder.Configuration.GetSection("DownstreamApis:Inventory"))
.AddTypedClient<InventoryClient>();

var app = builder.Build();

// Configure the HTTP request pipeline.
app.UseHttpsRedirection();

app.UseExceptionHandler();
app.UseStatusCodePages();

app.UseAuthentication();
app.UseAuthorization();

// This endpoint requires an app-only access token that contains the 'Orders.Read' application role.
app.MapGet("api/orders", async (InventoryClient inventoryClient, CancellationToken cancellationToken) =>
{
// The availability of the ordered products is provided by the Inventory API.
var products = await inventoryClient.GetProductsAsync(cancellationToken);
var orders = products.Select(product => new Order(product.Id, product.Name, Quantity: 1, IsAvailable: product.AvailableQuantity > 0));

return TypedResults.Ok(orders);
})
.RequireEntraIdApplicationRole("Orders.Read");

app.Run();

public record class Order(int Id, string ProductName, int Quantity, bool IsAvailable);

public record class Product(int Id, string Name, int AvailableQuantity);

public class InventoryClient(HttpClient httpClient)
{
public async Task<IEnumerable<Product>> GetProductsAsync(CancellationToken cancellationToken = default)
=> await httpClient.GetFromJsonAsync<IEnumerable<Product>>("api/products", cancellationToken) ?? [];
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"OrdersApi": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": false,
"applicationUrl": "https://localhost:7101;http://localhost:5101",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
{
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"TenantId": "<tenant-id>", // Required: the ID of the Microsoft Entra ID tenant
"ClientId": "<orders-api-client-id>", // Required: the application (client) ID of the Orders API
// Credentials are needed because this API calls the Inventory API.
// In Azure, use a managed identity that is federated with the app registration, so that no secret is required.
// For local development, see the README file.
"ClientCredentials": [
{
"SourceType": "SignedAssertionFromManagedIdentity",
"ManagedIdentityClientId": "<managed-identity-client-id>"
}
]
},
"DownstreamApis": {
"Inventory": {
"BaseAddress": "https://localhost:7102/", // Required: it must use HTTPS and end with a trailing slash
"Scope": "api://<inventory-api-client-id>/.default" // Required: the Application ID URI of the Inventory API, followed by /.default
//"AuthenticationScheme": "EntraId", // Default: EntraId
//"AllowHttpOnLoopback": false, // Default: false
//"Resilience": {
// "TotalRequestTimeout": {
// "Timeout": "00:00:30" // Default: 30 seconds
// },
// "AttemptTimeout": {
// "Timeout": "00:00:10" // Default: 10 seconds
// },
// "Retry": {
// "MaxRetryAttempts": 3 // Default: 3
// }
//}
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Loading