Browse Source

Add OpenIddict.Templates dotnet new template pack

- openiddict-server-identity: ASP.NET Core Identity + EF Core, authorization/consent, device verification, end session, token and userinfo endpoints generalized from the sandbox; config-seeded clients; optional admin API
- openiddict-server-empty: minimal APIs with pass-through endpoints and a development-only login placeholder
- openiddict-bff: OpenIddict client + BFF package + YARP routes
- Pack project fails if the default OpenIddictVersion differs from eng/Versions.props
- templates/verify.sh: packs local packages, instantiates, builds and smoke-tests each template
pull/2549/head
pieroviano 3 months ago
parent
commit
56cd9786bc
  1. 6
      OpenIddict.slnx
  2. 51
      templates/OpenIddict.Templates.csproj
  3. 32
      templates/README.md
  4. 3
      templates/content/Directory.Build.props
  5. 3
      templates/content/Directory.Build.targets
  6. 6
      templates/content/Directory.Packages.props
  7. 60
      templates/content/OpenIddict.Bff/.template.config/template.json
  8. 15
      templates/content/OpenIddict.Bff/Company.Bff.csproj
  9. 93
      templates/content/OpenIddict.Bff/Program.cs
  10. 13
      templates/content/OpenIddict.Bff/Properties/launchSettings.json
  11. 32
      templates/content/OpenIddict.Bff/appsettings.json
  12. 51
      templates/content/OpenIddict.Bff/wwwroot/index.html
  13. 46
      templates/content/OpenIddict.Server.Empty/.template.config/template.json
  14. 16
      templates/content/OpenIddict.Server.Empty/Company.Server.csproj
  15. 252
      templates/content/OpenIddict.Server.Empty/Program.cs
  16. 14
      templates/content/OpenIddict.Server.Empty/Properties/launchSettings.json
  17. 56
      templates/content/OpenIddict.Server.Empty/Worker.cs
  18. 12
      templates/content/OpenIddict.Server.Empty/appsettings.json
  19. 46
      templates/content/OpenIddict.Server.Identity/.template.config/template.json
  20. 77
      templates/content/OpenIddict.Server.Identity/ClientDefinition.cs
  21. 18
      templates/content/OpenIddict.Server.Identity/Company.Server.csproj
  22. 387
      templates/content/OpenIddict.Server.Identity/Controllers/AuthorizationController.cs
  23. 62
      templates/content/OpenIddict.Server.Identity/Controllers/UserinfoController.cs
  24. 8
      templates/content/OpenIddict.Server.Identity/Data/ApplicationDbContext.cs
  25. 29
      templates/content/OpenIddict.Server.Identity/Helpers/FormValueRequiredAttribute.cs
  26. 16
      templates/content/OpenIddict.Server.Identity/Pages/Index.cshtml
  27. 2
      templates/content/OpenIddict.Server.Identity/Pages/_ViewImports.cshtml
  28. 3
      templates/content/OpenIddict.Server.Identity/Pages/_ViewStart.cshtml
  29. 9
      templates/content/OpenIddict.Server.Identity/Policies.cs
  30. 102
      templates/content/OpenIddict.Server.Identity/Program.cs
  31. 13
      templates/content/OpenIddict.Server.Identity/Properties/launchSettings.json
  32. 12
      templates/content/OpenIddict.Server.Identity/ViewModels/AuthorizeViewModel.cs
  33. 25
      templates/content/OpenIddict.Server.Identity/ViewModels/VerifyViewModel.cs
  34. 21
      templates/content/OpenIddict.Server.Identity/Views/Authorization/Authorize.cshtml
  35. 19
      templates/content/OpenIddict.Server.Identity/Views/Authorization/EndSession.cshtml
  36. 50
      templates/content/OpenIddict.Server.Identity/Views/Authorization/Verify.cshtml
  37. 23
      templates/content/OpenIddict.Server.Identity/Views/Shared/_Layout.cshtml
  38. 17
      templates/content/OpenIddict.Server.Identity/Views/Shared/_LoginPartial.cshtml
  39. 3
      templates/content/OpenIddict.Server.Identity/Views/_ViewImports.cshtml
  40. 3
      templates/content/OpenIddict.Server.Identity/Views/_ViewStart.cshtml
  41. 34
      templates/content/OpenIddict.Server.Identity/Worker.cs
  42. 14
      templates/content/OpenIddict.Server.Identity/appsettings.Development.json
  43. 17
      templates/content/OpenIddict.Server.Identity/appsettings.json
  44. 135
      templates/verify.sh

6
OpenIddict.slnx

@ -48,6 +48,12 @@
<Project Path="shared/OpenIddict.Extensions/OpenIddict.Extensions.csproj" />
</Folder>
<Folder Name="/templates/">
<Project Path="templates/OpenIddict.Templates.csproj" />
<File Path="templates/README.md" />
<File Path="templates/verify.sh" />
</Folder>
<Folder Name="/src/">
<Project Path="src/OpenIddict.Abstractions/OpenIddict.Abstractions.csproj" />
<Project Path="src/OpenIddict.AspNetCore/OpenIddict.AspNetCore.csproj" />

51
templates/OpenIddict.Templates.csproj

@ -0,0 +1,51 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<PackageType>Template</PackageType>
<IsPackable>true</IsPackable>
<IsShipping>true</IsShipping>
<IncludeBuildOutput>false</IncludeBuildOutput>
<IncludeSymbols>false</IncludeSymbols>
<EnableDefaultItems>false</EnableDefaultItems>
<NoDefaultExcludes>true</NoDefaultExcludes>
<SuppressDependenciesWhenPacking>true</SuppressDependenciesWhenPacking>
<GenerateDocumentationFile>false</GenerateDocumentationFile>
<SignAssembly>false</SignAssembly>
<NoWarn>$(NoWarn);NU5128;NU5110;NU5111</NoWarn>
</PropertyGroup>
<PropertyGroup>
<Description>dotnet new templates for OpenIddict: authorization server (ASP.NET Core Identity), minimal authorization server and backend-for-frontend (BFF).</Description>
<PackageTags>$(PackageTags);templates;aspnetcore;server;bff</PackageTags>
</PropertyGroup>
<ItemGroup>
<None Include="content\**\*"
Exclude="content\*.props;content\*.targets;content\**\bin\**;content\**\obj\**;content\**\*.user;content\**\*.sqlite3*"
Pack="true" PackagePath="content" />
</ItemGroup>
<!--
Note: the OpenIddict package version used by default by the generated projects is hardcoded in the
template.json files. To ensure it is not forgotten when bumping the version, the pack fails if it differs.
-->
<Target Name="EnsureTemplateVersionsMatch" BeforeTargets="GenerateNuspec"
Condition=" '$(PreReleaseVersionLabel)' != '' And '$(DotNetFinalVersionKind)' != 'release' ">
<PropertyGroup>
<_OpenIddictTemplateVersion>$(VersionPrefix)-$(PreReleaseVersionLabel).$(PreReleaseVersionIteration)</_OpenIddictTemplateVersion>
</PropertyGroup>
<ItemGroup>
<_OpenIddictTemplateManifest Include="$(MSBuildProjectDirectory)\content\OpenIddict.*\.template.config\template.json" />
<_OpenIddictInvalidTemplateManifest Include="@(_OpenIddictTemplateManifest)"
Condition=" !$([System.IO.File]::ReadAllText('%(FullPath)').Contains('&quot;defaultValue&quot;: &quot;$(_OpenIddictTemplateVersion)&quot;')) " />
</ItemGroup>
<Error Condition=" '@(_OpenIddictTemplateManifest)' == '' " Text="No template manifest was found." />
<Error Condition=" '@(_OpenIddictInvalidTemplateManifest)' != '' "
Text="The template manifests must use '$(_OpenIddictTemplateVersion)' as the default OpenIddict version: @(_OpenIddictInvalidTemplateManifest)." />
</Target>
</Project>

32
templates/README.md

@ -0,0 +1,32 @@
# OpenIddict templates
`dotnet new` template pack (`OpenIddict.Templates`).
| Short name | Folder | Content |
|---|---|---|
| `openiddict-server-identity` | `content/OpenIddict.Server.Identity` | ASP.NET Core Identity (default UI) + EF Core SQLite; MVC authorization/consent, device verification, end session, token (code, device, refresh, client credentials), userinfo; clients seeded from `OpenIddict:Clients`; optional admin API (`OpenIddict:EnableAdminApi`, role `OpenIddict:AdminRole`) |
| `openiddict-server-empty` | `content/OpenIddict.Server.Empty` | Minimal APIs + EF Core SQLite; pass-through authorization/token/end session/userinfo; cookie login placeholder (development only, returns 501 otherwise) |
| `openiddict-bff` | `content/OpenIddict.Bff` | OpenIddict client + `OpenIddict.Client.AspNetCore.Bff` (session endpoints, refresh, antiforgery, in-memory session store) + YARP routes from `ReverseProxy` |
## Parameters
| Parameter | Templates | Default |
|---|---|---|
| `--OpenIddictVersion` | all | `8.0.0-preview.5` (pack fails if it differs from `eng/Versions.props`) |
| `--Authority`, `--ClientId` | `openiddict-bff` | `https://localhost:44310/`, `bff` |
## Usage
```sh
dotnet new install templates/content/OpenIddict.Server.Identity # or the packed OpenIddict.Templates nupkg
dotnet new openiddict-server-identity -n MyServer
```
## Verification
`templates/verify.sh` packs the required `src` packages into a temporary feed, instantiates each template, builds it and runs HTTP smoke tests (code flow end to end for both servers, BFF anonymous checks). Requires bash, curl, openssl, python and a trusted ASP.NET Core development certificate.
## Notes
- `content/Directory.*.props|targets` isolate the template sources from the repository build; they are not packed.
- Development signing/encryption certificates must be replaced in production.

3
templates/content/Directory.Build.props

@ -0,0 +1,3 @@
<Project>
<!-- Isolates the template sources from the repository build settings (not included in the template pack). -->
</Project>

3
templates/content/Directory.Build.targets

@ -0,0 +1,3 @@
<Project>
<!-- Isolates the template sources from the repository build settings (not included in the template pack). -->
</Project>

6
templates/content/Directory.Packages.props

@ -0,0 +1,6 @@
<Project>
<!-- Isolates the template sources from the repository central package management (not included in the template pack). -->
<PropertyGroup>
<ManagePackageVersionsCentrally>false</ManagePackageVersionsCentrally>
</PropertyGroup>
</Project>

60
templates/content/OpenIddict.Bff/.template.config/template.json

@ -0,0 +1,60 @@
{
"$schema": "http://json.schemastore.org/template",
"author": "OpenIddict",
"classifications": [ "Web", "OpenIddict", "OAuth", "OpenID Connect", "BFF" ],
"identity": "OpenIddict.Templates.Bff",
"groupIdentity": "OpenIddict.Templates.Bff",
"name": "OpenIddict backend-for-frontend (BFF)",
"description": "Backend-for-frontend host using the OpenIddict client, OpenIddict.Client.AspNetCore.Bff (session endpoints, token refresh, antiforgery) and YARP to proxy API calls.",
"shortName": "openiddict-bff",
"sourceName": "Company.Bff",
"preferNameDirectory": true,
"defaultName": "Bff",
"tags": {
"language": "C#",
"type": "project"
},
"symbols": {
"OpenIddictVersion": {
"type": "parameter",
"datatype": "text",
"description": "The version of the OpenIddict packages referenced by the project.",
"defaultValue": "8.0.0-preview.5",
"replaces": "OPENIDDICT_VERSION"
},
"Authority": {
"type": "parameter",
"datatype": "text",
"description": "The URI of the OpenID Connect server.",
"defaultValue": "https://localhost:44310/",
"replaces": "https://localhost:44310/"
},
"ClientId": {
"type": "parameter",
"datatype": "text",
"description": "The client identifier registered in the OpenID Connect server.",
"defaultValue": "bff",
"replaces": "CLIENT_ID"
},
"HttpsPort": {
"type": "generated",
"generator": "port",
"parameters": { "low": 44300, "high": 44399 },
"replaces": "44312"
},
"HttpPort": {
"type": "generated",
"generator": "port",
"parameters": { "low": 5000, "high": 5300 },
"replaces": "5012"
}
},
"sources": [
{
"modifiers": [
{ "exclude": [ "bin/**", "obj/**", "**/*.user" ] }
]
}
],
"primaryOutputs": [ { "path": "Company.Bff.csproj" } ]
}

15
templates/content/OpenIddict.Bff/Company.Bff.csproj

@ -0,0 +1,15 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OpenIddictVersion>OPENIDDICT_VERSION</OpenIddictVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="OpenIddict.Client.AspNetCore.Bff" Version="$(OpenIddictVersion)" />
<PackageReference Include="OpenIddict.Client.SystemNetHttp" Version="$(OpenIddictVersion)" />
</ItemGroup>
</Project>

93
templates/content/OpenIddict.Bff/Program.cs

@ -0,0 +1,93 @@
using System.Security.Claims;
using Microsoft.AspNetCore.Authentication.Cookies;
using OpenIddict.Client;
using static OpenIddict.Abstractions.OpenIddictConstants;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.Cookie.HttpOnly = true;
options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
options.ExpireTimeSpan = TimeSpan.FromHours(8);
options.SlidingExpiration = true;
});
builder.Services.AddAuthorization();
builder.Services.AddOpenIddict()
.AddClient(options =>
{
options.AllowAuthorizationCodeFlow()
.AllowRefreshTokenFlow();
// Note: the BFF doesn't use a database: the state tokens are self-contained.
options.DisableTokenStorage();
// Note: the development certificates must be replaced by persistent certificates in production.
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
options.UseSystemNetHttp()
.SetProductInformation(typeof(Program).Assembly);
var settings = builder.Configuration.GetSection("OpenIddict");
var registration = new OpenIddictClientRegistration
{
Issuer = new Uri(settings["Authority"] ?? throw new InvalidOperationException("The authority is missing."), UriKind.Absolute),
ClientId = settings["ClientId"],
ClientSecret = string.IsNullOrEmpty(settings["ClientSecret"]) ? null : settings["ClientSecret"],
// Note: these URIs must match the paths used by the BFF endpoints and must be registered in the server.
RedirectUri = new Uri("bff/callback/login", UriKind.Relative),
PostLogoutRedirectUri = new Uri("bff/callback/logout", UriKind.Relative)
};
registration.Scopes.UnionWith(settings.GetSection("Scopes").Get<string[]>() ?? [Scopes.OpenId]);
options.AddRegistration(registration);
// Register the BFF services: session endpoints, automatic token refresh and antiforgery checks.
options.UseBff(bff => bff.UseInMemorySessionStore());
});
// Proxy the API calls declared in the "ReverseProxy" section (the user access token is attached by the BFF transforms).
builder.Services.AddReverseProxy()
.LoadFromConfig(builder.Configuration.GetSection("ReverseProxy"))
.AddOpenIddictBffTransforms();
var app = builder.Build();
if (!app.Environment.IsDevelopment())
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseOpenIddictBff();
app.UseAuthorization();
// Map the login (/bff/login), logout (/bff/logout), user (/bff/user),
// callback and back-channel logout (/bff/backchannel-logout) endpoints.
app.MapOpenIddictBffEndpoints();
// Local API endpoint: requires an authenticated user and the "X-CSRF: 1" header.
app.MapGet("/api/me", (ClaimsPrincipal user) => Results.Ok(new
{
Name = user.Identity?.Name,
Claims = user.Claims.Select(claim => new { claim.Type, claim.Value })
}))
.RequireAuthorization()
.AsOpenIddictBffApiEndpoint();
app.MapReverseProxy();
app.Run();

13
templates/content/OpenIddict.Bff/Properties/launchSettings.json

@ -0,0 +1,13 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:44312;http://localhost:5012",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

32
templates/content/OpenIddict.Bff/appsettings.json

@ -0,0 +1,32 @@
{
"OpenIddict": {
"Authority": "https://localhost:44310/",
"ClientId": "CLIENT_ID",
"ClientSecret": "",
"Scopes": [ "openid", "profile", "offline_access" ]
},
"ReverseProxy": {
"Routes": {
"api": {
"ClusterId": "api",
"Match": { "Path": "/api/remote/{**catch-all}" },
"Transforms": [ { "PathRemovePrefix": "/api/remote" } ],
"Metadata": { "OpenIddict.Bff.AccessToken": "User" }
}
},
"Clusters": {
"api": {
"Destinations": {
"default": { "Address": "https://localhost:5001/" }
}
}
}
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

51
templates/content/OpenIddict.Bff/wwwroot/index.html

@ -0,0 +1,51 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Company.Bff</title>
</head>
<body>
<h1>Company.Bff</h1>
<p id="status">Loading...</p>
<p>
<a id="login" href="/bff/login" hidden>Log in</a>
<a id="logout" href="#" hidden>Log out</a>
<button id="call" hidden>Call /api/me</button>
</p>
<pre id="output"></pre>
<script>
// Note: the "X-CSRF" header is required by the BFF endpoints to mitigate CSRF attacks.
const headers = { "X-CSRF": "1" };
async function load() {
const response = await fetch("/bff/user", { headers });
if (response.status !== 200) {
document.getElementById("status").textContent = "Not logged in.";
document.getElementById("login").hidden = false;
return;
}
const claims = await response.json();
const name = claims.find(claim => claim.type === "name")?.value ?? claims.find(claim => claim.type === "sub")?.value;
document.getElementById("status").textContent = `Logged in as ${name}.`;
document.getElementById("logout").href = claims.find(claim => claim.type === "bff:logout_url").value;
document.getElementById("logout").hidden = false;
document.getElementById("call").hidden = false;
}
document.getElementById("call").addEventListener("click", async () => {
const response = await fetch("/api/me", { headers });
document.getElementById("output").textContent = response.ok
? JSON.stringify(await response.json(), null, 2)
: `${response.status} ${response.statusText}`;
});
load();
</script>
</body>
</html>

46
templates/content/OpenIddict.Server.Empty/.template.config/template.json

@ -0,0 +1,46 @@
{
"$schema": "http://json.schemastore.org/template",
"author": "OpenIddict",
"classifications": [ "Web", "OpenIddict", "OAuth", "OpenID Connect" ],
"identity": "OpenIddict.Templates.Server.Empty",
"groupIdentity": "OpenIddict.Templates.Server.Empty",
"name": "OpenIddict authorization server (empty)",
"description": "Minimal OpenID Connect server using minimal APIs, Entity Framework Core (SQLite) and pass-through authorization, token, end session and userinfo endpoints.",
"shortName": "openiddict-server-empty",
"sourceName": "Company.Server",
"preferNameDirectory": true,
"defaultName": "AuthorizationServer",
"tags": {
"language": "C#",
"type": "project"
},
"symbols": {
"OpenIddictVersion": {
"type": "parameter",
"datatype": "text",
"description": "The version of the OpenIddict packages referenced by the project.",
"defaultValue": "8.0.0-preview.5",
"replaces": "OPENIDDICT_VERSION"
},
"HttpsPort": {
"type": "generated",
"generator": "port",
"parameters": { "low": 44300, "high": 44399 },
"replaces": "44311"
},
"HttpPort": {
"type": "generated",
"generator": "port",
"parameters": { "low": 5000, "high": 5300 },
"replaces": "5011"
}
},
"sources": [
{
"modifiers": [
{ "exclude": [ "bin/**", "obj/**", "**/*.user", "**/*.sqlite3*" ] }
]
}
],
"primaryOutputs": [ { "path": "Company.Server.csproj" } ]
}

16
templates/content/OpenIddict.Server.Empty/Company.Server.csproj

@ -0,0 +1,16 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OpenIddictVersion>OPENIDDICT_VERSION</OpenIddictVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.11" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="$(OpenIddictVersion)" />
<PackageReference Include="OpenIddict.Server.AspNetCore" Version="$(OpenIddictVersion)" />
</ItemGroup>
</Project>

252
templates/content/OpenIddict.Server.Empty/Program.cs

@ -0,0 +1,252 @@
using System.Security.Claims;
using System.Text.Encodings.Web;
using Company.Server;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using static OpenIddict.Abstractions.OpenIddictConstants;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<DbContext>(options =>
{
// Configure Entity Framework Core to use SQLite (replace with the provider of your choice).
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
// Register the entity sets needed by OpenIddict.
options.UseOpenIddict();
});
// Note: the cookie handler stores the identity of the logged in user between the
// login page and the authorization endpoint. Replace it by your own user store.
builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options => options.LoginPath = "/account/login");
builder.Services.AddAuthorization();
builder.Services.AddAntiforgery();
builder.Services.AddOpenIddict()
.AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<DbContext>();
})
.AddServer(options =>
{
options.SetAuthorizationEndpointUris("connect/authorize")
.SetEndSessionEndpointUris("connect/endsession")
.SetTokenEndpointUris("connect/token")
.SetUserInfoEndpointUris("connect/userinfo");
options.AllowAuthorizationCodeFlow()
.AllowClientCredentialsFlow()
.AllowRefreshTokenFlow();
options.RegisterScopes(Scopes.Email, Scopes.Profile);
// Note: the development certificates must be replaced by persistent certificates
// in production (or by automatic key management, see EnableAutomaticKeyManagement()).
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
options.UseAspNetCore()
.EnableAuthorizationEndpointPassthrough()
.EnableEndSessionEndpointPassthrough()
.EnableTokenEndpointPassthrough()
.EnableUserInfoEndpointPassthrough();
});
// Create the database and, in development, register a sample client application.
builder.Services.AddHostedService<Worker>();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapMethods("/connect/authorize", [HttpMethods.Get, HttpMethods.Post], async context =>
{
var request = context.GetOpenIddictServerRequest() ??
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
// Redirect the user agent to the login page if the user is not logged in.
var result = await context.AuthenticateAsync(CookieAuthenticationDefaults.AuthenticationScheme);
if (result is not { Succeeded: true })
{
await context.ChallengeAsync(CookieAuthenticationDefaults.AuthenticationScheme, new AuthenticationProperties
{
RedirectUri = context.Request.PathBase + context.Request.Path + QueryString.Create(
context.Request.HasFormContentType ? context.Request.Form : context.Request.Query)
});
return;
}
// TODO: display a consent form if necessary and create a permanent authorization
// (see IOpenIddictAuthorizationManager) to avoid asking for consent every time.
var identity = new ClaimsIdentity(
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
identity.SetClaim(Claims.Subject, result.Principal.FindFirst(ClaimTypes.NameIdentifier)?.Value)
.SetClaim(Claims.Name, result.Principal.Identity?.Name);
identity.SetScopes(request.GetScopes());
identity.SetDestinations(GetDestinations);
await context.SignInAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
});
app.MapPost("/connect/token", async context =>
{
var request = context.GetOpenIddictServerRequest() ??
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
ClaimsIdentity identity;
if (request.IsAuthorizationCodeGrantType() || request.IsRefreshTokenGrantType())
{
// Retrieve the claims principal stored in the authorization code/refresh token.
var result = await context.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
// TODO: ensure the user still exists and is still allowed to sign in and refresh the user claims.
identity = new ClaimsIdentity(result.Principal!.Claims,
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
}
else if (request.IsClientCredentialsGrantType())
{
// Note: the client credentials are automatically validated by OpenIddict.
identity = new ClaimsIdentity(
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
identity.SetClaim(Claims.Subject, request.ClientId);
identity.SetScopes(request.GetScopes());
}
else
{
throw new InvalidOperationException("The specified grant type is not supported.");
}
identity.SetDestinations(GetDestinations);
await context.SignInAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
});
app.MapMethods("/connect/endsession", [HttpMethods.Get, HttpMethods.Post], async context =>
{
// Delete the local authentication cookie and ask OpenIddict to redirect the user
// agent to the post_logout_redirect_uri specified by the client application.
await context.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
await context.SignOutAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
new AuthenticationProperties { RedirectUri = "/" });
});
app.MapMethods("/connect/userinfo", [HttpMethods.Get, HttpMethods.Post], async context =>
{
var result = await context.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
if (result is not { Succeeded: true })
{
await context.ChallengeAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
return;
}
var claims = new Dictionary<string, object?>(StringComparer.Ordinal)
{
// Note: the "sub" claim is a mandatory claim and must be included in the JSON response.
[Claims.Subject] = result.Principal.GetClaim(Claims.Subject)
};
if (result.Principal.HasScope(Scopes.Profile))
{
claims[Claims.Name] = result.Principal.GetClaim(Claims.Name);
}
await context.Response.WriteAsJsonAsync(claims);
});
app.MapGet("/account/login", async (HttpContext context, IAntiforgery antiforgery) =>
{
if (!app.Environment.IsDevelopment())
{
// TODO: implement user authentication (e.g using ASP.NET Core Identity or an external provider).
context.Response.StatusCode = StatusCodes.Status501NotImplemented;
return;
}
var tokens = antiforgery.GetAndStoreTokens(context);
var encoder = HtmlEncoder.Default;
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.WriteAsync($"""
<!DOCTYPE html>
<html>
<body>
<h1>Development login</h1>
<p>Any user name is accepted: replace this page by a real authentication mechanism.</p>
<form method="post">
<input type="hidden" name="{encoder.Encode(tokens.FormFieldName)}" value="{encoder.Encode(tokens.RequestToken ?? string.Empty)}" />
<input type="hidden" name="ReturnUrl" value="{encoder.Encode(context.Request.Query["ReturnUrl"].ToString())}" />
<input name="UserName" placeholder="User name" required />
<button type="submit">Log in</button>
</form>
</body>
</html>
""");
});
app.MapPost("/account/login", async (HttpContext context, IAntiforgery antiforgery) =>
{
if (!app.Environment.IsDevelopment())
{
context.Response.StatusCode = StatusCodes.Status501NotImplemented;
return;
}
await antiforgery.ValidateRequestAsync(context);
var form = await context.Request.ReadFormAsync();
var name = form["UserName"].ToString();
if (string.IsNullOrWhiteSpace(name))
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, name));
identity.AddClaim(new Claim(ClaimTypes.Name, name));
await context.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity));
// Only allow local return URLs to prevent open redirect attacks.
var url = form["ReturnUrl"].ToString();
context.Response.Redirect(!string.IsNullOrEmpty(url) && url.StartsWith('/') && !url.StartsWith("//") && !url.StartsWith("/\\") ? url : "/");
});
app.MapGet("/", () => "OpenIddict server: see /.well-known/openid-configuration.");
app.Run();
static IEnumerable<string> GetDestinations(Claim claim) => claim.Type switch
{
// Note: by default, claims are NOT automatically included in the access and identity tokens.
Claims.Name when claim.Subject!.HasScope(Scopes.Profile) => [Destinations.AccessToken, Destinations.IdentityToken],
_ => [Destinations.AccessToken]
};

14
templates/content/OpenIddict.Server.Empty/Properties/launchSettings.json

@ -0,0 +1,14 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": ".well-known/openid-configuration",
"applicationUrl": "https://localhost:44311;http://localhost:5011",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

56
templates/content/OpenIddict.Server.Empty/Worker.cs

@ -0,0 +1,56 @@
using Microsoft.EntityFrameworkCore;
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Company.Server;
/// <summary>
/// Creates the database and, in development, registers a sample client application.
/// </summary>
/// <remarks>In production, the database should be created using migrations as part of the deployment.</remarks>
public class Worker(IServiceProvider provider, IHostEnvironment environment) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
await using var scope = provider.CreateAsyncScope();
var context = scope.ServiceProvider.GetRequiredService<DbContext>();
await context.Database.EnsureCreatedAsync(cancellationToken);
if (!environment.IsDevelopment())
{
return;
}
var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();
// Public client application usable with https://oidcdebugger.com/ (authorization code flow + PKCE).
if (await manager.FindByClientIdAsync("oidc-debugger", cancellationToken) is null)
{
await manager.CreateAsync(new OpenIddictApplicationDescriptor
{
ClientId = "oidc-debugger",
ClientType = ClientTypes.Public,
DisplayName = "OpenID Connect debugger",
RedirectUris = { new Uri("https://oidcdebugger.com/debug") },
Permissions =
{
Permissions.Endpoints.Authorization,
Permissions.Endpoints.EndSession,
Permissions.Endpoints.Token,
Permissions.GrantTypes.AuthorizationCode,
Permissions.GrantTypes.RefreshToken,
Permissions.ResponseTypes.Code,
Permissions.Scopes.Email,
Permissions.Scopes.Profile
},
Requirements =
{
Requirements.Features.ProofKeyForCodeExchange
}
}, cancellationToken);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

12
templates/content/OpenIddict.Server.Empty/appsettings.json

@ -0,0 +1,12 @@
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=Company.Server.sqlite3"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

46
templates/content/OpenIddict.Server.Identity/.template.config/template.json

@ -0,0 +1,46 @@
{
"$schema": "http://json.schemastore.org/template",
"author": "OpenIddict",
"classifications": [ "Web", "OpenIddict", "OAuth", "OpenID Connect", "Identity" ],
"identity": "OpenIddict.Templates.Server.Identity",
"groupIdentity": "OpenIddict.Templates.Server.Identity",
"name": "OpenIddict authorization server (ASP.NET Core Identity)",
"description": "OpenID Connect server using ASP.NET Core Identity, Entity Framework Core (SQLite) and MVC authorization, device verification, end session and userinfo endpoints.",
"shortName": "openiddict-server-identity",
"sourceName": "Company.Server",
"preferNameDirectory": true,
"defaultName": "AuthorizationServer",
"tags": {
"language": "C#",
"type": "project"
},
"symbols": {
"OpenIddictVersion": {
"type": "parameter",
"datatype": "text",
"description": "The version of the OpenIddict packages referenced by the project.",
"defaultValue": "8.0.0-preview.5",
"replaces": "OPENIDDICT_VERSION"
},
"HttpsPort": {
"type": "generated",
"generator": "port",
"parameters": { "low": 44300, "high": 44399 },
"replaces": "44310"
},
"HttpPort": {
"type": "generated",
"generator": "port",
"parameters": { "low": 5000, "high": 5300 },
"replaces": "5010"
}
},
"sources": [
{
"modifiers": [
{ "exclude": [ "bin/**", "obj/**", "**/*.user", "**/*.sqlite3*" ] }
]
}
],
"primaryOutputs": [ { "path": "Company.Server.csproj" } ]
}

77
templates/content/OpenIddict.Server.Identity/ClientDefinition.cs

@ -0,0 +1,77 @@
using OpenIddict.Abstractions;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Company.Server;
/// <summary>
/// Represents a client application declared in the "OpenIddict:Clients" configuration section.
/// </summary>
public sealed class ClientDefinition
{
public string ClientId { get; set; } = string.Empty;
/// <summary>
/// Gets or sets the client secret. Clients without a secret are registered as public clients.
/// </summary>
public string? ClientSecret { get; set; }
public string? DisplayName { get; set; }
public string ConsentType { get; set; } = ConsentTypes.Explicit;
public List<string> GrantTypes { get; set; } = [];
public List<string> Scopes { get; set; } = [];
public List<Uri> RedirectUris { get; set; } = [];
public List<Uri> PostLogoutRedirectUris { get; set; } = [];
/// <summary>
/// Creates the application descriptor corresponding to this client definition.
/// </summary>
public OpenIddictApplicationDescriptor CreateDescriptor()
{
var descriptor = new OpenIddictApplicationDescriptor
{
ClientId = ClientId,
ClientSecret = ClientSecret,
ClientType = string.IsNullOrEmpty(ClientSecret) ? ClientTypes.Public : ClientTypes.Confidential,
ConsentType = ConsentType,
DisplayName = DisplayName ?? ClientId,
Permissions = { Permissions.Endpoints.Token }
};
descriptor.RedirectUris.UnionWith(RedirectUris);
descriptor.PostLogoutRedirectUris.UnionWith(PostLogoutRedirectUris);
if (descriptor.ClientType is ClientTypes.Confidential)
{
descriptor.Permissions.Add(Permissions.Endpoints.Introspection);
descriptor.Permissions.Add(Permissions.Endpoints.Revocation);
}
foreach (var type in GrantTypes)
{
descriptor.AddGrantTypePermissions(type);
switch (type)
{
case OpenIddictConstants.GrantTypes.AuthorizationCode:
descriptor.Permissions.Add(Permissions.Endpoints.Authorization);
descriptor.Permissions.Add(Permissions.Endpoints.EndSession);
descriptor.Permissions.Add(Permissions.ResponseTypes.Code);
descriptor.Requirements.Add(Requirements.Features.ProofKeyForCodeExchange);
break;
case OpenIddictConstants.GrantTypes.DeviceCode:
descriptor.Permissions.Add(Permissions.Endpoints.DeviceAuthorization);
break;
}
}
descriptor.AddScopePermissions([.. Scopes]);
return descriptor;
}
}

18
templates/content/OpenIddict.Server.Identity/Company.Server.csproj

@ -0,0 +1,18 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<OpenIddictVersion>OPENIDDICT_VERSION</OpenIddictVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" Version="10.0.11" />
<PackageReference Include="Microsoft.AspNetCore.Identity.UI" Version="10.0.11" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="10.0.11" />
<PackageReference Include="OpenIddict.Server.AspNetCore" Version="$(OpenIddictVersion)" />
<PackageReference Include="OpenIddict.EntityFrameworkCore" Version="$(OpenIddictVersion)" />
</ItemGroup>
</Project>

387
templates/content/OpenIddict.Server.Identity/Controllers/AuthorizationController.cs

@ -0,0 +1,387 @@
using System.Globalization;
using System.Security.Claims;
using Company.Server.Helpers;
using Company.Server.ViewModels;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.IdentityModel.Tokens;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Company.Server.Controllers;
public class AuthorizationController(
IOpenIddictApplicationManager applicationManager,
IOpenIddictAuthorizationManager authorizationManager,
IOpenIddictScopeManager scopeManager,
SignInManager<IdentityUser> signInManager,
UserManager<IdentityUser> userManager) : Controller
{
private const string IgnoreAuthenticationChallenge = "IgnoreAuthenticationChallenge";
[HttpGet("~/connect/authorize")]
[HttpPost("~/connect/authorize")]
[IgnoreAntiforgeryToken]
public async Task<IActionResult> Authorize()
{
// Note: the request contains the parameters sent to the authorization endpoint (or to the pushed
// authorization endpoint) and MUST NOT be returned unprotected to the user agent.
var request = HttpContext.GetOpenIddictServerRequest() ??
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
// Retrieve the user principal stored in the authentication cookie and redirect the user agent
// to the login page if it can't be extracted, if prompt=login was specified, or if max_age
// was specified and the authentication cookie is not considered "fresh" enough.
var result = await HttpContext.AuthenticateAsync(IdentityConstants.ApplicationScheme);
if (result is not { Succeeded: true } ||
((request.HasPromptValue(PromptValues.Login) || request.MaxAge is 0 ||
(request.MaxAge is not null && result.Properties?.IssuedUtc is not null &&
TimeProvider.System.GetUtcNow() - result.Properties.IssuedUtc > TimeSpan.FromSeconds(request.MaxAge.Value))) &&
TempData[IgnoreAuthenticationChallenge] is null or false))
{
// If the client application requested promptless authentication,
// return an error indicating that the user is not logged in.
if (request.HasPromptValue(PromptValues.None))
{
return Forbid(Errors.LoginRequired, "The user is not logged in.");
}
// To avoid endless login -> authorization redirects, a temp data entry
// is used to skip the challenge if the user has just been redirected.
TempData[IgnoreAuthenticationChallenge] = true;
return Challenge(new AuthenticationProperties
{
RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
Request.HasFormContentType ? Request.Form : Request.Query)
}, IdentityConstants.ApplicationScheme);
}
var user = await userManager.GetUserAsync(result.Principal);
if (user is null)
{
return Challenge(new AuthenticationProperties
{
RedirectUri = Request.PathBase + Request.Path + QueryString.Create(
Request.HasFormContentType ? Request.Form : Request.Query)
}, IdentityConstants.ApplicationScheme);
}
var application = await applicationManager.FindByClientIdAsync(request.ClientId!) ??
throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
// Retrieve the permanent authorizations associated with the user and the calling client application.
var authorizations = await authorizationManager.FindAsync(
query: (
Subject : await userManager.GetUserIdAsync(user),
ApplicationId : await applicationManager.GetIdAsync(application),
Status : Statuses.Valid,
Type : AuthorizationTypes.Permanent,
RequiredScopes: request.GetScopes())).ToListAsync();
switch (await applicationManager.GetConsentTypeAsync(application))
{
// If the consent is external (e.g when authorizations are granted by an administrator),
// immediately return an error if no authorization can be found in the database.
case ConsentTypes.External when authorizations.Count is 0:
return Forbid(Errors.ConsentRequired, "The logged in user is not allowed to access this client application.");
// If the consent is implicit or if an authorization was found,
// return an authorization response without displaying the consent form.
case ConsentTypes.Implicit:
case ConsentTypes.External when authorizations.Count is not 0:
case ConsentTypes.Explicit when authorizations.Count is not 0 && !request.HasPromptValue(PromptValues.Consent):
return await SignInAsync(user, application, authorizations.LastOrDefault(), request.GetScopes());
// At this point, no authorization was found in the database and an error must be returned
// if the client application specified prompt=none in the authorization request.
case ConsentTypes.Explicit when request.HasPromptValue(PromptValues.None):
case ConsentTypes.Systematic when request.HasPromptValue(PromptValues.None):
return Forbid(Errors.ConsentRequired, "Interactive user consent is required.");
// In every other case, render the consent form.
default: return View(new AuthorizeViewModel
{
ApplicationName = await applicationManager.GetLocalizedDisplayNameAsync(application, CultureInfo.CurrentCulture),
Scope = request.Scope
});
}
}
[Authorize, FormValueRequired("submit.Accept")]
[HttpPost("~/connect/authorize"), ValidateAntiForgeryToken]
public async Task<IActionResult> Accept()
{
var request = HttpContext.GetOpenIddictServerRequest() ??
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
var user = await userManager.GetUserAsync(User);
if (user is null)
{
return Forbid(Errors.LoginRequired, "The account associated with the logged in user was removed.");
}
var application = await applicationManager.FindByClientIdAsync(request.ClientId!) ??
throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
var authorizations = await authorizationManager.FindAsync(
query: (
Subject : await userManager.GetUserIdAsync(user),
ApplicationId : await applicationManager.GetIdAsync(application),
Status : Statuses.Valid,
Type : AuthorizationTypes.Permanent,
RequiredScopes: request.GetScopes())).ToListAsync();
// Note: the same check is already made in the other action but is repeated here to ensure
// this POST-only endpoint can't be abused to bypass the external authorization requirement.
if (authorizations.Count is 0 && await applicationManager.HasConsentTypeAsync(application, ConsentTypes.External))
{
return Forbid(Errors.ConsentRequired, "The logged in user is not allowed to access this client application.");
}
return await SignInAsync(user, application, authorizations.LastOrDefault(), request.GetScopes());
}
[Authorize, FormValueRequired("submit.Deny")]
[HttpPost("~/connect/authorize"), ValidateAntiForgeryToken]
// Notify OpenIddict that the authorization grant has been denied by the resource owner.
public IActionResult Deny() => Forbid(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
[Authorize, HttpGet("~/connect/verify"), IgnoreAntiforgeryToken]
public async Task<IActionResult> Verify()
{
// Retrieve the claims principal associated with the user code.
var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
if (result is { Succeeded: true } && !string.IsNullOrEmpty(result.Principal.GetClaim(Claims.ClientId)))
{
var application = await applicationManager.FindByClientIdAsync(result.Principal.GetClaim(Claims.ClientId)!) ??
throw new InvalidOperationException("Details concerning the calling client application cannot be found.");
return View(new VerifyViewModel
{
ApplicationName = await applicationManager.GetLocalizedDisplayNameAsync(application, CultureInfo.CurrentCulture),
Scope = string.Join(' ', result.Principal.GetScopes()),
UserCode = result.Properties.GetTokenValue(OpenIddictServerAspNetCoreConstants.Tokens.UserCode)
});
}
if (!string.IsNullOrEmpty(result.Properties?.GetTokenValue(OpenIddictServerAspNetCoreConstants.Tokens.UserCode)))
{
return View(new VerifyViewModel
{
Error = Errors.InvalidToken,
ErrorDescription = "The specified user code is not valid. Please make sure you typed it correctly."
});
}
// Otherwise, render a form asking the user to enter the user code manually.
return View(new VerifyViewModel());
}
[Authorize, FormValueRequired("submit.Accept")]
[HttpPost("~/connect/verify"), ValidateAntiForgeryToken]
public async Task<IActionResult> VerifyAccept()
{
var user = await userManager.GetUserAsync(User);
if (user is null)
{
return Forbid(Errors.LoginRequired, "The account associated with the logged in user was removed.");
}
var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
if (result is { Succeeded: true } && !string.IsNullOrEmpty(result.Principal.GetClaim(Claims.ClientId)))
{
var identity = await CreateIdentityAsync(user, result.Principal.GetScopes());
// The redirect URI is the address the user is redirected to after the demand is validated.
return SignIn(new ClaimsPrincipal(identity), new AuthenticationProperties { RedirectUri = "/" },
OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
return View(new VerifyViewModel
{
Error = Errors.InvalidToken,
ErrorDescription = "The specified user code is not valid. Please make sure you typed it correctly."
});
}
[Authorize, FormValueRequired("submit.Deny")]
[HttpPost("~/connect/verify"), ValidateAntiForgeryToken]
public IActionResult VerifyDeny() => Forbid(new AuthenticationProperties { RedirectUri = "/" },
OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
[HttpGet("~/connect/endsession")]
public IActionResult EndSession() => View();
[ActionName(nameof(EndSession)), HttpPost("~/connect/endsession"), ValidateAntiForgeryToken]
public async Task<IActionResult> EndSessionPost()
{
// Delete the local authentication cookie.
await signInManager.SignOutAsync();
// Ask OpenIddict to redirect the user agent to the post_logout_redirect_uri
// specified by the client application or to the RedirectUri specified below.
return SignOut(new AuthenticationProperties { RedirectUri = "/" },
OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
[HttpPost("~/connect/token"), IgnoreAntiforgeryToken, Produces("application/json")]
public async Task<IActionResult> Exchange()
{
var request = HttpContext.GetOpenIddictServerRequest() ??
throw new InvalidOperationException("The OpenID Connect request cannot be retrieved.");
if (request.IsAuthorizationCodeGrantType() || request.IsDeviceCodeGrantType() || request.IsRefreshTokenGrantType())
{
// Retrieve the claims principal stored in the authorization code/device code/refresh token.
var result = await HttpContext.AuthenticateAsync(OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
var user = await userManager.FindByIdAsync(result.Principal!.GetClaim(Claims.Subject)!);
if (user is null)
{
return Forbid(Errors.InvalidGrant, "The token is no longer valid.");
}
// Ensure the user is still allowed to sign in.
if (!await signInManager.CanSignInAsync(user))
{
return Forbid(Errors.InvalidGrant, "The user is no longer allowed to sign in.");
}
var identity = new ClaimsIdentity(result.Principal!.Claims,
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
// Override the user claims present in the principal in case they changed since the token was issued.
await SetUserClaimsAsync(identity, user);
identity.SetDestinations(GetDestinations);
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
if (request.IsClientCredentialsGrantType())
{
// Note: the client credentials are automatically validated by OpenIddict.
var application = await applicationManager.FindByClientIdAsync(request.ClientId!) ??
throw new InvalidOperationException("The application details cannot be found in the database.");
var identity = new ClaimsIdentity(
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
// Use the client_id as the subject identifier.
identity.SetClaim(Claims.Subject, await applicationManager.GetClientIdAsync(application))
.SetClaim(Claims.Name, await applicationManager.GetDisplayNameAsync(application));
identity.SetScopes(request.GetScopes());
identity.SetResources(await scopeManager.ListResourcesAsync(identity.GetScopes()).ToListAsync());
identity.SetDestinations(GetDestinations);
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
throw new InvalidOperationException("The specified grant type is not supported.");
}
private async Task<IActionResult> SignInAsync(IdentityUser user, object application,
object? authorization, IEnumerable<string> scopes)
{
var identity = await CreateIdentityAsync(user, scopes);
// Automatically create a permanent authorization to avoid requiring explicit consent
// for future authorization or token requests containing the same scopes.
authorization ??= await authorizationManager.CreateAsync(new OpenIddictAuthorizationDescriptor
{
ApplicationId = await applicationManager.GetIdAsync(application),
Principal = new ClaimsPrincipal(identity),
Scopes = [.. identity.GetScopes()],
Subject = await userManager.GetUserIdAsync(user),
Type = AuthorizationTypes.Permanent
});
identity.SetAuthorizationId(await authorizationManager.GetIdAsync(authorization));
return SignIn(new ClaimsPrincipal(identity), OpenIddictServerAspNetCoreDefaults.AuthenticationScheme);
}
private async Task<ClaimsIdentity> CreateIdentityAsync(IdentityUser user, IEnumerable<string> scopes)
{
// Create the claims-based identity that will be used by OpenIddict to generate tokens.
var identity = new ClaimsIdentity(
authenticationType: TokenValidationParameters.DefaultAuthenticationType,
nameType: Claims.Name,
roleType: Claims.Role);
await SetUserClaimsAsync(identity, user);
// Note: the granted scopes match the requested scopes but you may want to allow
// the user to uncheck specific scopes: for that, restrict the list of scopes here.
identity.SetScopes(scopes);
identity.SetResources(await scopeManager.ListResourcesAsync(identity.GetScopes()).ToListAsync());
identity.SetDestinations(GetDestinations);
return identity;
}
private async Task SetUserClaimsAsync(ClaimsIdentity identity, IdentityUser user)
{
identity.SetClaim(Claims.Subject, await userManager.GetUserIdAsync(user))
.SetClaim(Claims.Email, await userManager.GetEmailAsync(user))
.SetClaim(Claims.Name, await userManager.GetUserNameAsync(user))
.SetClaim(Claims.PreferredUsername, await userManager.GetUserNameAsync(user))
.SetClaims(Claims.Role, [.. await userManager.GetRolesAsync(user)]);
}
private ForbidResult Forbid(string error, string description) => Forbid(
authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
properties: new AuthenticationProperties(new Dictionary<string, string?>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = error,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = description
}));
private static IEnumerable<string> GetDestinations(Claim claim)
{
// Note: by default, claims are NOT automatically included in the access and identity tokens.
// To allow OpenIddict to serialize them, a destination must be attached to each claim.
switch (claim.Type)
{
case Claims.Name or Claims.PreferredUsername:
yield return Destinations.AccessToken;
if (claim.Subject!.HasScope(Scopes.Profile))
yield return Destinations.IdentityToken;
yield break;
case Claims.Email:
yield return Destinations.AccessToken;
if (claim.Subject!.HasScope(Scopes.Email))
yield return Destinations.IdentityToken;
yield break;
case Claims.Role:
yield return Destinations.AccessToken;
if (claim.Subject!.HasScope(Scopes.Roles))
yield return Destinations.IdentityToken;
yield break;
// Never include the security stamp in the access and identity tokens, as it's a secret value.
case "AspNet.Identity.SecurityStamp": yield break;
default:
yield return Destinations.AccessToken;
yield break;
}
}
}

62
templates/content/OpenIddict.Server.Identity/Controllers/UserinfoController.cs

@ -0,0 +1,62 @@
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using static OpenIddict.Abstractions.OpenIddictConstants;
namespace Company.Server.Controllers;
public class UserinfoController(UserManager<IdentityUser> userManager) : Controller
{
[Authorize(AuthenticationSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)]
[HttpGet("~/connect/userinfo"), HttpPost("~/connect/userinfo")]
[IgnoreAntiforgeryToken, Produces("application/json")]
public async Task<IActionResult> Userinfo()
{
var user = await userManager.FindByIdAsync(User.GetClaim(Claims.Subject)!);
if (user is null)
{
return Challenge(
authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme,
properties: new AuthenticationProperties(new Dictionary<string, string?>
{
[OpenIddictServerAspNetCoreConstants.Properties.Error] = Errors.InvalidToken,
[OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] =
"The specified access token is bound to an account that no longer exists."
}));
}
var claims = new Dictionary<string, object?>(StringComparer.Ordinal)
{
// Note: the "sub" claim is a mandatory claim and must be included in the JSON response.
[Claims.Subject] = await userManager.GetUserIdAsync(user)
};
if (User.HasScope(Scopes.Profile))
{
claims[Claims.Name] = await userManager.GetUserNameAsync(user);
claims[Claims.PreferredUsername] = await userManager.GetUserNameAsync(user);
}
if (User.HasScope(Scopes.Email))
{
claims[Claims.Email] = await userManager.GetEmailAsync(user);
claims[Claims.EmailVerified] = await userManager.IsEmailConfirmedAsync(user);
}
if (User.HasScope(Scopes.Phone))
{
claims[Claims.PhoneNumber] = await userManager.GetPhoneNumberAsync(user);
claims[Claims.PhoneNumberVerified] = await userManager.IsPhoneNumberConfirmedAsync(user);
}
if (User.HasScope(Scopes.Roles))
{
claims[Claims.Role] = await userManager.GetRolesAsync(user);
}
return Ok(claims);
}
}

8
templates/content/OpenIddict.Server.Identity/Data/ApplicationDbContext.cs

@ -0,0 +1,8 @@
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
namespace Company.Server.Data;
public class ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : IdentityDbContext(options)
{
}

29
templates/content/OpenIddict.Server.Identity/Helpers/FormValueRequiredAttribute.cs

@ -0,0 +1,29 @@
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.ActionConstraints;
namespace Company.Server.Helpers;
/// <summary>
/// Selects an action only when the request is a form POST containing the specified form value.
/// </summary>
public sealed class FormValueRequiredAttribute(string name) : ActionMethodSelectorAttribute
{
public override bool IsValidForRequest(RouteContext routeContext, ActionDescriptor action)
{
var request = routeContext.HttpContext.Request;
if (HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method) ||
HttpMethods.IsDelete(request.Method) || HttpMethods.IsTrace(request.Method))
{
return false;
}
if (string.IsNullOrEmpty(request.ContentType) ||
!request.ContentType.StartsWith("application/x-www-form-urlencoded", StringComparison.OrdinalIgnoreCase))
{
return false;
}
return !string.IsNullOrEmpty(request.Form[name]);
}
}

16
templates/content/OpenIddict.Server.Identity/Pages/Index.cshtml

@ -0,0 +1,16 @@
@page
@{
ViewData["Title"] = "Home";
}
<h1>Company.Server</h1>
<p class="lead">OpenID Connect server powered by OpenIddict and ASP.NET Core Identity.</p>
<ul>
<li><a href="~/.well-known/openid-configuration">Discovery document</a></li>
<li><a href="~/.well-known/jwks">JSON Web Key Set</a></li>
<li><a href="~/connect/verify">Device verification</a></li>
</ul>
<p>Client applications are registered from the <code>OpenIddict:Clients</code> configuration section at startup.</p>

2
templates/content/OpenIddict.Server.Identity/Pages/_ViewImports.cshtml

@ -0,0 +1,2 @@
@using Company.Server
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

3
templates/content/OpenIddict.Server.Identity/Pages/_ViewStart.cshtml

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

9
templates/content/OpenIddict.Server.Identity/Policies.cs

@ -0,0 +1,9 @@
namespace Company.Server;
public static class Policies
{
/// <summary>
/// Name of the authorization policy protecting the OpenIddict admin API.
/// </summary>
public const string Admin = "openiddict-admin";
}

102
templates/content/OpenIddict.Server.Identity/Program.cs

@ -0,0 +1,102 @@
using Company.Server;
using Company.Server.Data;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using static OpenIddict.Abstractions.OpenIddictConstants;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<ApplicationDbContext>(options =>
{
// Configure Entity Framework Core to use SQLite (replace with the provider of your choice).
options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection"));
// Register the entity sets needed by OpenIddict.
options.UseOpenIddict();
});
builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = false)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddOpenIddict()
// Register the OpenIddict core components (Entity Framework Core stores and models).
.AddCore(options =>
{
options.UseEntityFrameworkCore()
.UseDbContext<ApplicationDbContext>();
})
// Register the OpenIddict server components.
.AddServer(options =>
{
options.SetAuthorizationEndpointUris("connect/authorize")
.SetDeviceAuthorizationEndpointUris("connect/device")
.SetEndSessionEndpointUris("connect/endsession")
.SetEndUserVerificationEndpointUris("connect/verify")
.SetIntrospectionEndpointUris("connect/introspect")
.SetRevocationEndpointUris("connect/revoke")
.SetTokenEndpointUris("connect/token")
.SetUserInfoEndpointUris("connect/userinfo");
options.AllowAuthorizationCodeFlow()
.AllowClientCredentialsFlow()
.AllowDeviceAuthorizationFlow()
.AllowRefreshTokenFlow();
options.RegisterScopes(Scopes.Email, Scopes.Profile, Scopes.Roles);
// Note: the development certificates must be replaced by persistent certificates
// in production (or by automatic key management, see EnableAutomaticKeyManagement()).
options.AddDevelopmentEncryptionCertificate()
.AddDevelopmentSigningCertificate();
options.UseAspNetCore()
.EnableStatusCodePagesIntegration()
.EnableAuthorizationEndpointPassthrough()
.EnableEndSessionEndpointPassthrough()
.EnableEndUserVerificationEndpointPassthrough()
.EnableTokenEndpointPassthrough()
.EnableUserInfoEndpointPassthrough();
});
builder.Services.AddAuthorizationBuilder()
.AddPolicy(Policies.Admin, policy => policy.RequireRole(builder.Configuration["OpenIddict:AdminRole"] ?? "admin"));
// Create the database and register the client applications declared in the configuration.
builder.Services.AddHostedService<Worker>();
var app = builder.Build();
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.MapRazorPages();
// Optionally expose the OpenIddict admin API (applications, scopes, authorizations, tokens and keys).
if (app.Configuration.GetValue<bool>("OpenIddict:EnableAdminApi"))
{
app.MapOpenIddictAdminApi(Policies.Admin);
}
app.Run();

13
templates/content/OpenIddict.Server.Identity/Properties/launchSettings.json

@ -0,0 +1,13 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"https": {
"commandName": "Project",
"launchBrowser": true,
"applicationUrl": "https://localhost:44310;http://localhost:5010",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
}
}
}

12
templates/content/OpenIddict.Server.Identity/ViewModels/AuthorizeViewModel.cs

@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace Company.Server.ViewModels;
public class AuthorizeViewModel
{
[Display(Name = "Application")]
public string? ApplicationName { get; set; }
[Display(Name = "Scope")]
public string? Scope { get; set; }
}

25
templates/content/OpenIddict.Server.Identity/ViewModels/VerifyViewModel.cs

@ -0,0 +1,25 @@
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using OpenIddict.Abstractions;
namespace Company.Server.ViewModels;
public class VerifyViewModel
{
[Display(Name = "Application")]
public string? ApplicationName { get; set; }
[BindNever, Display(Name = "Error")]
public string? Error { get; set; }
[BindNever, Display(Name = "Error description")]
public string? ErrorDescription { get; set; }
[Display(Name = "Scope")]
public string? Scope { get; set; }
[FromQuery(Name = OpenIddictConstants.Parameters.UserCode)]
[Display(Name = "User code")]
public string? UserCode { get; set; }
}

21
templates/content/OpenIddict.Server.Identity/Views/Authorization/Authorize.cshtml

@ -0,0 +1,21 @@
@using Microsoft.Extensions.Primitives
@model AuthorizeViewModel
@{
ViewData["Title"] = "Authorization";
}
<h1>Authorization</h1>
<p class="lead">Do you want to grant <strong>@Model.ApplicationName</strong> access to your data? (scopes requested: @Model.Scope)</p>
<form asp-controller="Authorization" asp-action="Authorize" method="post">
@* Flow the request parameters so they can be received by the Accept/Deny actions: *@
@foreach (var parameter in Context.Request.HasFormContentType ?
(IEnumerable<KeyValuePair<string, StringValues>>) Context.Request.Form : Context.Request.Query)
{
<input type="hidden" name="@parameter.Key" value="@parameter.Value" />
}
<input class="btn btn-lg btn-success" name="submit.Accept" type="submit" value="Yes" />
<input class="btn btn-lg btn-danger" name="submit.Deny" type="submit" value="No" />
</form>

19
templates/content/OpenIddict.Server.Identity/Views/Authorization/EndSession.cshtml

@ -0,0 +1,19 @@
@using Microsoft.Extensions.Primitives
@{
ViewData["Title"] = "Log out";
}
<h1>Log out</h1>
<p class="lead">Are you sure you want to sign out?</p>
<form asp-controller="Authorization" asp-action="EndSession" method="post">
@* Flow the request parameters so they can be received by the EndSessionPost action: *@
@foreach (var parameter in Context.Request.HasFormContentType ?
(IEnumerable<KeyValuePair<string, StringValues>>) Context.Request.Form : Context.Request.Query)
{
<input type="hidden" name="@parameter.Key" value="@parameter.Value" />
}
<input class="btn btn-lg btn-success" name="Confirm" type="submit" value="Yes" />
</form>

50
templates/content/OpenIddict.Server.Identity/Views/Authorization/Verify.cshtml

@ -0,0 +1,50 @@
@using Microsoft.Extensions.Primitives
@model VerifyViewModel
@{
ViewData["Title"] = "Device authorization";
}
<h1>Authorization</h1>
@if (string.IsNullOrEmpty(Model.UserCode) || !string.IsNullOrEmpty(Model.Error))
{
@if (!string.IsNullOrEmpty(Model.Error) && !string.IsNullOrEmpty(Model.ErrorDescription))
{
<p class="alert alert-warning">
An error occurred:
<br />
@Model.ErrorDescription (@Model.Error)
</p>
}
<p class="lead">Enter the user code given by the client application:</p>
<form asp-controller="Authorization" asp-action="Verify" method="get">
<div class="mb-3">
<input class="form-control" name="user_code" type="text" />
</div>
<input class="btn btn-lg btn-success" type="submit" value="Submit" />
</form>
}
else
{
<p class="lead">Do you want to grant <strong>@Model.ApplicationName</strong> access to your data? (scopes requested: @Model.Scope)</p>
<p class="alert alert-warning">
Make sure that the code displayed on the device is <strong>@Model.UserCode</strong>.
<br />
If the two codes don't match, press "No" to reject the authorization demand.
</p>
<form asp-controller="Authorization" asp-action="Verify" method="post">
@* Flow the request parameters so they can be received by the VerifyAccept/VerifyDeny actions: *@
@foreach (var parameter in Context.Request.HasFormContentType ?
(IEnumerable<KeyValuePair<string, StringValues>>) Context.Request.Form : Context.Request.Query)
{
<input type="hidden" name="@parameter.Key" value="@parameter.Value" />
}
<input class="btn btn-lg btn-success" name="submit.Accept" type="submit" value="Yes" />
<input class="btn btn-lg btn-danger" name="submit.Deny" type="submit" value="No" />
</form>
}

23
templates/content/OpenIddict.Server.Identity/Views/Shared/_Layout.cshtml

@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>@ViewData["Title"] - Company.Server</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" />
</head>
<body>
<nav class="navbar navbar-expand navbar-light bg-light border-bottom mb-4">
<div class="container">
<a class="navbar-brand" href="~/">Company.Server</a>
<partial name="_LoginPartial" />
</div>
</nav>
<main class="container">
@RenderBody()
</main>
@await RenderSectionAsync("Scripts", required: false)
</body>
</html>

17
templates/content/OpenIddict.Server.Identity/Views/Shared/_LoginPartial.cshtml

@ -0,0 +1,17 @@
@* Note: this partial view is also used by the default ASP.NET Core Identity UI layout. *@
<ul class="navbar-nav ms-auto">
@if (User.Identity?.IsAuthenticated is true)
{
<li class="nav-item"><a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Manage/Index">@User.Identity.Name</a></li>
<li class="nav-item">
<form asp-area="Identity" asp-page="/Account/Logout" asp-route-returnUrl="/" method="post">
<button type="submit" class="btn btn-link nav-link text-dark">Log out</button>
</form>
</li>
}
else
{
<li class="nav-item"><a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Register">Register</a></li>
<li class="nav-item"><a class="nav-link text-dark" asp-area="Identity" asp-page="/Account/Login">Log in</a></li>
}
</ul>

3
templates/content/OpenIddict.Server.Identity/Views/_ViewImports.cshtml

@ -0,0 +1,3 @@
@using Company.Server
@using Company.Server.ViewModels
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

3
templates/content/OpenIddict.Server.Identity/Views/_ViewStart.cshtml

@ -0,0 +1,3 @@
@{
Layout = "_Layout";
}

34
templates/content/OpenIddict.Server.Identity/Worker.cs

@ -0,0 +1,34 @@
using Company.Server.Data;
using OpenIddict.Abstractions;
namespace Company.Server;
/// <summary>
/// Creates the database and registers the client applications declared in the "OpenIddict:Clients" section.
/// </summary>
/// <remarks>In production, the database should be created using migrations as part of the deployment.</remarks>
public class Worker(IServiceProvider provider, IConfiguration configuration) : IHostedService
{
public async Task StartAsync(CancellationToken cancellationToken)
{
await using var scope = provider.CreateAsyncScope();
var context = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
await context.Database.EnsureCreatedAsync(cancellationToken);
var manager = scope.ServiceProvider.GetRequiredService<IOpenIddictApplicationManager>();
foreach (var client in configuration.GetSection("OpenIddict:Clients").Get<List<ClientDefinition>>() ?? [])
{
if (string.IsNullOrEmpty(client.ClientId) ||
await manager.FindByClientIdAsync(client.ClientId, cancellationToken) is not null)
{
continue;
}
await manager.CreateAsync(client.CreateDescriptor(), cancellationToken);
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}

14
templates/content/OpenIddict.Server.Identity/appsettings.Development.json

@ -0,0 +1,14 @@
{
"OpenIddict": {
"Clients": [
{
"ClientId": "oidc-debugger",
"DisplayName": "OpenID Connect debugger",
"ConsentType": "explicit",
"GrantTypes": [ "authorization_code", "refresh_token" ],
"Scopes": [ "openid", "email", "profile", "roles", "offline_access" ],
"RedirectUris": [ "https://oidcdebugger.com/debug" ]
}
]
}
}

17
templates/content/OpenIddict.Server.Identity/appsettings.json

@ -0,0 +1,17 @@
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=Company.Server.sqlite3"
},
"OpenIddict": {
"EnableAdminApi": false,
"AdminRole": "admin",
"Clients": []
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}

135
templates/verify.sh

@ -0,0 +1,135 @@
#!/usr/bin/env bash
# Packs the OpenIddict packages used by the templates into a temporary feed, instantiates
# each template, builds the generated projects and runs HTTP smoke tests against them.
#
# Requirements: bash, curl, openssl, python and a trusted ASP.NET Core development certificate.
# Usage: templates/verify.sh [work directory]
set -u
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
WORK="${1:-$(mktemp -d)}"
mkdir -p "$WORK/feed" "$WORK/home" "$WORK/packages" "$WORK/out"
if [ -x "$REPO/.dotnet/dotnet" ] || [ -x "$REPO/.dotnet/dotnet.exe" ]; then
export DOTNET_ROOT="$REPO/.dotnet"
DN="$REPO/.dotnet/dotnet"
else
DN="dotnet"
fi
export DOTNET_CLI_HOME="$WORK/home"
export NUGET_PACKAGES="$WORK/packages"
export DOTNET_NOLOGO=1
export ASPNETCORE_ENVIRONMENT=Development
FAILURES=0
check() { # name expected actual
if [ "$2" == "$3" ]; then echo " PASS $1"; else echo " FAIL $1: expected $2, got $3"; FAILURES=$((FAILURES + 1)); fi
}
echo "== pack"
for p in OpenIddict.Abstractions OpenIddict.Core OpenIddict.Server OpenIddict.Server.AspNetCore \
OpenIddict.EntityFrameworkCore.Models OpenIddict.EntityFrameworkCore OpenIddict.Client \
OpenIddict.Client.AspNetCore OpenIddict.Client.SystemNetHttp OpenIddict.Client.AspNetCore.Bff; do
"$DN" pack "$REPO/src/$p/$p.csproj" -o "$WORK/feed" > "$WORK/out/pack-$p.log" 2>&1 || { echo " FAIL pack $p (see $WORK/out/pack-$p.log)"; exit 1; }
done
VERSION="$(ls "$WORK/feed" | sed -n 's/^OpenIddict\.Abstractions\.\(.*\)\.nupkg$/\1/p' | head -1)"
echo " version $VERSION"
cat > "$WORK/nuget.config" <<EOF
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="local" value="$WORK/feed" />
<add key="nuget" value="https://api.nuget.org/v3/index.json" />
</packageSources>
</configuration>
EOF
cd "$WORK"
echo "== instantiate and build"
for t in Server.Identity:openiddict-server-identity:IdentityServer Server.Empty:openiddict-server-empty:EmptyServer Bff:openiddict-bff:BffHost; do
IFS=: read -r folder name project <<< "$t"
"$DN" new install "$REPO/templates/content/OpenIddict.$folder" > /dev/null 2>&1 || { echo " FAIL install $name"; exit 1; }
rm -rf "$project"
"$DN" new "$name" -n "$project" --OpenIddictVersion "$VERSION" > /dev/null || { echo " FAIL new $name"; exit 1; }
if "$DN" build "$project/$project.csproj" > "$WORK/out/build-$project.log" 2>&1; then echo " PASS build $name"; else echo " FAIL build $name (see $WORK/out/build-$project.log)"; exit 1; fi
done
start() { # project port
rm -f "$1"/*.sqlite3*
(cd "$1" && "$DN" "bin/Debug/net10.0/$1.dll" --urls "https://127.0.0.1:$2" > "$WORK/out/run-$1.log" 2>&1 &)
for _ in $(seq 1 60); do curl -sk -o /dev/null "https://127.0.0.1:$2/" && return; sleep 1; done
}
stop() { # port
if command -v taskkill > /dev/null; then
for pid in $(netstat -ano | grep "127.0.0.1:$1 .*LISTENING" | awk '{print $5}' | sort -u); do taskkill //F //PID "$pid" > /dev/null; done
else
fuser -k "$1/tcp" > /dev/null 2>&1
fi
sleep 1
}
status() { curl -sk -o /dev/null -w '%{http_code}' "$@"; }
VERIFIER="dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXkdBjftJeZ4CVP"
CHALLENGE=$(printf '%s' "$VERIFIER" | openssl dgst -sha256 -binary | base64 | tr '+/' '-_' | tr -d '=')
QUERY="client_id=oidc-debugger&response_type=code&redirect_uri=https%3A%2F%2Foidcdebugger.com%2Fdebug&scope=openid%20profile%20email&code_challenge=$CHALLENGE&code_challenge_method=S256"
json() { python -c "import json,sys;print(json.dumps(json.load(sys.stdin).get('$1')))"; }
redeem() { # base
curl -sk --data-urlencode "grant_type=authorization_code" --data-urlencode "client_id=oidc-debugger" --data-urlencode "code=$CODE" \
--data-urlencode "code_verifier=$VERIFIER" --data-urlencode "redirect_uri=https://oidcdebugger.com/debug" "$1/connect/token" |
python -c "import json,sys;print(json.load(sys.stdin).get('access_token',''))"
}
echo "== smoke openiddict-server-identity"
start IdentityServer 5198
B=https://127.0.0.1:5198; J="$WORK/identity.cookies"; rm -f "$J"
check discovery 200 "$(status "$B/.well-known/openid-configuration")"
check admin-api-disabled 404 "$(status "$B/openiddict/admin/applications")"
TOKEN=$(curl -sk -c "$J" -b "$J" "$B/Identity/Account/Register" | grep -o 'name="__RequestVerificationToken" type="hidden" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"$//')
check register 302 "$(status -c "$J" -b "$J" --data-urlencode "__RequestVerificationToken=$TOKEN" --data-urlencode "Input.Email=alice@example.com" \
--data-urlencode "Input.Password=Passw0rd!Passw0rd" --data-urlencode "Input.ConfirmPassword=Passw0rd!Passw0rd" "$B/Identity/Account/Register")"
PAGE=$(curl -sk -c "$J" -b "$J" "$B/connect/authorize?$QUERY")
TOKEN=$(printf '%s' "$PAGE" | grep -o 'name="__RequestVerificationToken" type="hidden" value="[^"]*"' | head -1 | sed 's/.*value="//;s/"$//')
check consent-form yes "$([ -n "$TOKEN" ] && echo yes || echo no)"
LOCATION=$(curl -sk -c "$J" -b "$J" -o /dev/null -w '%{redirect_url}' --data "$QUERY" --data-urlencode "__RequestVerificationToken=$TOKEN" --data-urlencode "submit.Accept=Yes" "$B/connect/authorize")
CODE=$(printf '%s' "$LOCATION" | grep -o 'code=[^&]*' | head -1 | cut -d= -f2)
check authorization-code yes "$([ -n "$CODE" ] && echo yes || echo no)"
ACCESS=$(redeem "$B")
check userinfo '"alice@example.com"' "$(curl -sk -H "Authorization: Bearer $ACCESS" "$B/connect/userinfo" | json email)"
stop 5198
echo "== smoke openiddict-server-empty"
start EmptyServer 5197
B=https://127.0.0.1:5197; J="$WORK/empty.cookies"; rm -f "$J"
AUTHZ="/connect/authorize?$QUERY"
check discovery 200 "$(status "$B/.well-known/openid-configuration")"
check authorize-challenge 302 "$(status -c "$J" -b "$J" "$B$AUTHZ")"
TOKEN=$(curl -sk -c "$J" -b "$J" "$B/account/login" | grep -o 'name="__RequestVerificationToken" value="[^"]*"' | sed 's/.*value="//;s/"$//')
check login 302 "$(status -c "$J" -b "$J" --data-urlencode "__RequestVerificationToken=$TOKEN" --data-urlencode "UserName=alice" --data-urlencode "ReturnUrl=$AUTHZ" "$B/account/login")"
LOCATION=$(curl -sk -c "$J" -b "$J" -o /dev/null -w '%{redirect_url}' "$B$AUTHZ")
CODE=$(printf '%s' "$LOCATION" | grep -o 'code=[^&]*' | head -1 | cut -d= -f2)
check authorization-code yes "$([ -n "$CODE" ] && echo yes || echo no)"
ACCESS=$(redeem "$B")
check userinfo '"alice"' "$(curl -sk -H "Authorization: Bearer $ACCESS" "$B/connect/userinfo" | json sub)"
stop 5197
echo "== smoke openiddict-bff"
start BffHost 5196
B=https://127.0.0.1:5196
check index 200 "$(status "$B/")"
check user-anonymous 401 "$(status -H 'X-CSRF: 1' "$B/bff/user")"
check api-without-antiforgery-header 401 "$(status "$B/api/me")"
check api-anonymous 401 "$(status -H 'X-CSRF: 1' "$B/api/me")"
stop 5196
for t in Server.Identity Server.Empty Bff; do "$DN" new uninstall "$REPO/templates/content/OpenIddict.$t" > /dev/null 2>&1; done
echo "== $FAILURES failure(s)"
exit "$FAILURES"
Loading…
Cancel
Save