diff --git a/OpenIddict.slnx b/OpenIddict.slnx index c7a81f71..a71b579c 100644 --- a/OpenIddict.slnx +++ b/OpenIddict.slnx @@ -48,6 +48,12 @@ + + + + + + diff --git a/templates/OpenIddict.Templates.csproj b/templates/OpenIddict.Templates.csproj new file mode 100644 index 00000000..37b30aa5 --- /dev/null +++ b/templates/OpenIddict.Templates.csproj @@ -0,0 +1,51 @@ + + + + net10.0 + Template + true + true + false + false + false + true + true + false + false + $(NoWarn);NU5128;NU5110;NU5111 + + + + dotnet new templates for OpenIddict: authorization server (ASP.NET Core Identity), minimal authorization server and backend-for-frontend (BFF). + $(PackageTags);templates;aspnetcore;server;bff + + + + + + + + + + + <_OpenIddictTemplateVersion>$(VersionPrefix)-$(PreReleaseVersionLabel).$(PreReleaseVersionIteration) + + + + <_OpenIddictTemplateManifest Include="$(MSBuildProjectDirectory)\content\OpenIddict.*\.template.config\template.json" /> + <_OpenIddictInvalidTemplateManifest Include="@(_OpenIddictTemplateManifest)" + Condition=" !$([System.IO.File]::ReadAllText('%(FullPath)').Contains('"defaultValue": "$(_OpenIddictTemplateVersion)"')) " /> + + + + + + + diff --git a/templates/README.md b/templates/README.md new file mode 100644 index 00000000..c7985a44 --- /dev/null +++ b/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. diff --git a/templates/content/Directory.Build.props b/templates/content/Directory.Build.props new file mode 100644 index 00000000..8ea6d180 --- /dev/null +++ b/templates/content/Directory.Build.props @@ -0,0 +1,3 @@ + + + diff --git a/templates/content/Directory.Build.targets b/templates/content/Directory.Build.targets new file mode 100644 index 00000000..8ea6d180 --- /dev/null +++ b/templates/content/Directory.Build.targets @@ -0,0 +1,3 @@ + + + diff --git a/templates/content/Directory.Packages.props b/templates/content/Directory.Packages.props new file mode 100644 index 00000000..af851053 --- /dev/null +++ b/templates/content/Directory.Packages.props @@ -0,0 +1,6 @@ + + + + false + + diff --git a/templates/content/OpenIddict.Bff/.template.config/template.json b/templates/content/OpenIddict.Bff/.template.config/template.json new file mode 100644 index 00000000..f4a2dd80 --- /dev/null +++ b/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" } ] +} diff --git a/templates/content/OpenIddict.Bff/Company.Bff.csproj b/templates/content/OpenIddict.Bff/Company.Bff.csproj new file mode 100644 index 00000000..236933d5 --- /dev/null +++ b/templates/content/OpenIddict.Bff/Company.Bff.csproj @@ -0,0 +1,15 @@ + + + + net10.0 + enable + enable + OPENIDDICT_VERSION + + + + + + + + diff --git a/templates/content/OpenIddict.Bff/Program.cs b/templates/content/OpenIddict.Bff/Program.cs new file mode 100644 index 00000000..f5f6df32 --- /dev/null +++ b/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() ?? [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(); diff --git a/templates/content/OpenIddict.Bff/Properties/launchSettings.json b/templates/content/OpenIddict.Bff/Properties/launchSettings.json new file mode 100644 index 00000000..9fb543fc --- /dev/null +++ b/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" + } + } + } +} diff --git a/templates/content/OpenIddict.Bff/appsettings.json b/templates/content/OpenIddict.Bff/appsettings.json new file mode 100644 index 00000000..880f1d54 --- /dev/null +++ b/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": "*" +} diff --git a/templates/content/OpenIddict.Bff/wwwroot/index.html b/templates/content/OpenIddict.Bff/wwwroot/index.html new file mode 100644 index 00000000..17c0aa2e --- /dev/null +++ b/templates/content/OpenIddict.Bff/wwwroot/index.html @@ -0,0 +1,51 @@ + + + + + Company.Bff + + +

Company.Bff

+ +

Loading...

+ +

+ + + +

+ +

+
+    
+
+
diff --git a/templates/content/OpenIddict.Server.Empty/.template.config/template.json b/templates/content/OpenIddict.Server.Empty/.template.config/template.json
new file mode 100644
index 00000000..6c68774b
--- /dev/null
+++ b/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" } ]
+}
diff --git a/templates/content/OpenIddict.Server.Empty/Company.Server.csproj b/templates/content/OpenIddict.Server.Empty/Company.Server.csproj
new file mode 100644
index 00000000..d969c946
--- /dev/null
+++ b/templates/content/OpenIddict.Server.Empty/Company.Server.csproj
@@ -0,0 +1,16 @@
+
+
+  
+    net10.0
+    enable
+    enable
+    OPENIDDICT_VERSION
+  
+
+  
+    
+    
+    
+  
+
+
diff --git a/templates/content/OpenIddict.Server.Empty/Program.cs b/templates/content/OpenIddict.Server.Empty/Program.cs
new file mode 100644
index 00000000..04477491
--- /dev/null
+++ b/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(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();
+    })
+    .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();
+
+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(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($"""
+        
+        
+        
+            

Development login

+

Any user name is accepted: replace this page by a real authentication mechanism.

+
+ + + + +
+ + + """); +}); + +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 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] +}; diff --git a/templates/content/OpenIddict.Server.Empty/Properties/launchSettings.json b/templates/content/OpenIddict.Server.Empty/Properties/launchSettings.json new file mode 100644 index 00000000..c9c0d8cb --- /dev/null +++ b/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" + } + } + } +} diff --git a/templates/content/OpenIddict.Server.Empty/Worker.cs b/templates/content/OpenIddict.Server.Empty/Worker.cs new file mode 100644 index 00000000..b0e7a963 --- /dev/null +++ b/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; + +/// +/// Creates the database and, in development, registers a sample client application. +/// +/// In production, the database should be created using migrations as part of the deployment. +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(); + await context.Database.EnsureCreatedAsync(cancellationToken); + + if (!environment.IsDevelopment()) + { + return; + } + + var manager = scope.ServiceProvider.GetRequiredService(); + + // 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; +} diff --git a/templates/content/OpenIddict.Server.Empty/appsettings.json b/templates/content/OpenIddict.Server.Empty/appsettings.json new file mode 100644 index 00000000..0fc74f82 --- /dev/null +++ b/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": "*" +} diff --git a/templates/content/OpenIddict.Server.Identity/.template.config/template.json b/templates/content/OpenIddict.Server.Identity/.template.config/template.json new file mode 100644 index 00000000..75f2d03e --- /dev/null +++ b/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" } ] +} diff --git a/templates/content/OpenIddict.Server.Identity/ClientDefinition.cs b/templates/content/OpenIddict.Server.Identity/ClientDefinition.cs new file mode 100644 index 00000000..e50ce4d7 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/ClientDefinition.cs @@ -0,0 +1,77 @@ +using OpenIddict.Abstractions; +using static OpenIddict.Abstractions.OpenIddictConstants; + +namespace Company.Server; + +/// +/// Represents a client application declared in the "OpenIddict:Clients" configuration section. +/// +public sealed class ClientDefinition +{ + public string ClientId { get; set; } = string.Empty; + + /// + /// Gets or sets the client secret. Clients without a secret are registered as public clients. + /// + public string? ClientSecret { get; set; } + + public string? DisplayName { get; set; } + + public string ConsentType { get; set; } = ConsentTypes.Explicit; + + public List GrantTypes { get; set; } = []; + + public List Scopes { get; set; } = []; + + public List RedirectUris { get; set; } = []; + + public List PostLogoutRedirectUris { get; set; } = []; + + /// + /// Creates the application descriptor corresponding to this client definition. + /// + 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; + } +} diff --git a/templates/content/OpenIddict.Server.Identity/Company.Server.csproj b/templates/content/OpenIddict.Server.Identity/Company.Server.csproj new file mode 100644 index 00000000..eaf66e4d --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Company.Server.csproj @@ -0,0 +1,18 @@ + + + + net10.0 + enable + enable + OPENIDDICT_VERSION + + + + + + + + + + + diff --git a/templates/content/OpenIddict.Server.Identity/Controllers/AuthorizationController.cs b/templates/content/OpenIddict.Server.Identity/Controllers/AuthorizationController.cs new file mode 100644 index 00000000..7f560dae --- /dev/null +++ b/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 signInManager, + UserManager userManager) : Controller +{ + private const string IgnoreAuthenticationChallenge = "IgnoreAuthenticationChallenge"; + + [HttpGet("~/connect/authorize")] + [HttpPost("~/connect/authorize")] + [IgnoreAntiforgeryToken] + public async Task 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 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 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 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 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 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 SignInAsync(IdentityUser user, object application, + object? authorization, IEnumerable 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 CreateIdentityAsync(IdentityUser user, IEnumerable 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 + { + [OpenIddictServerAspNetCoreConstants.Properties.Error] = error, + [OpenIddictServerAspNetCoreConstants.Properties.ErrorDescription] = description + })); + + private static IEnumerable 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; + } + } +} diff --git a/templates/content/OpenIddict.Server.Identity/Controllers/UserinfoController.cs b/templates/content/OpenIddict.Server.Identity/Controllers/UserinfoController.cs new file mode 100644 index 00000000..338b550b --- /dev/null +++ b/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 userManager) : Controller +{ + [Authorize(AuthenticationSchemes = OpenIddictServerAspNetCoreDefaults.AuthenticationScheme)] + [HttpGet("~/connect/userinfo"), HttpPost("~/connect/userinfo")] + [IgnoreAntiforgeryToken, Produces("application/json")] + public async Task Userinfo() + { + var user = await userManager.FindByIdAsync(User.GetClaim(Claims.Subject)!); + if (user is null) + { + return Challenge( + authenticationSchemes: OpenIddictServerAspNetCoreDefaults.AuthenticationScheme, + properties: new AuthenticationProperties(new Dictionary + { + [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(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); + } +} diff --git a/templates/content/OpenIddict.Server.Identity/Data/ApplicationDbContext.cs b/templates/content/OpenIddict.Server.Identity/Data/ApplicationDbContext.cs new file mode 100644 index 00000000..d71a97bf --- /dev/null +++ b/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 options) : IdentityDbContext(options) +{ +} diff --git a/templates/content/OpenIddict.Server.Identity/Helpers/FormValueRequiredAttribute.cs b/templates/content/OpenIddict.Server.Identity/Helpers/FormValueRequiredAttribute.cs new file mode 100644 index 00000000..a68b4cb8 --- /dev/null +++ b/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; + +/// +/// Selects an action only when the request is a form POST containing the specified form value. +/// +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]); + } +} diff --git a/templates/content/OpenIddict.Server.Identity/Pages/Index.cshtml b/templates/content/OpenIddict.Server.Identity/Pages/Index.cshtml new file mode 100644 index 00000000..343dc51c --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Pages/Index.cshtml @@ -0,0 +1,16 @@ +@page +@{ + ViewData["Title"] = "Home"; +} + +

Company.Server

+ +

OpenID Connect server powered by OpenIddict and ASP.NET Core Identity.

+ + + +

Client applications are registered from the OpenIddict:Clients configuration section at startup.

diff --git a/templates/content/OpenIddict.Server.Identity/Pages/_ViewImports.cshtml b/templates/content/OpenIddict.Server.Identity/Pages/_ViewImports.cshtml new file mode 100644 index 00000000..04f74ff3 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Pages/_ViewImports.cshtml @@ -0,0 +1,2 @@ +@using Company.Server +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/templates/content/OpenIddict.Server.Identity/Pages/_ViewStart.cshtml b/templates/content/OpenIddict.Server.Identity/Pages/_ViewStart.cshtml new file mode 100644 index 00000000..820a2f6e --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Pages/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ + Layout = "_Layout"; +} diff --git a/templates/content/OpenIddict.Server.Identity/Policies.cs b/templates/content/OpenIddict.Server.Identity/Policies.cs new file mode 100644 index 00000000..434653f9 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Policies.cs @@ -0,0 +1,9 @@ +namespace Company.Server; + +public static class Policies +{ + /// + /// Name of the authorization policy protecting the OpenIddict admin API. + /// + public const string Admin = "openiddict-admin"; +} diff --git a/templates/content/OpenIddict.Server.Identity/Program.cs b/templates/content/OpenIddict.Server.Identity/Program.cs new file mode 100644 index 00000000..cc5b840f --- /dev/null +++ b/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(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(options => options.SignIn.RequireConfirmedAccount = false) + .AddRoles() + .AddEntityFrameworkStores(); + +builder.Services.AddOpenIddict() + + // Register the OpenIddict core components (Entity Framework Core stores and models). + .AddCore(options => + { + options.UseEntityFrameworkCore() + .UseDbContext(); + }) + + // 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(); + +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("OpenIddict:EnableAdminApi")) +{ + app.MapOpenIddictAdminApi(Policies.Admin); +} + +app.Run(); diff --git a/templates/content/OpenIddict.Server.Identity/Properties/launchSettings.json b/templates/content/OpenIddict.Server.Identity/Properties/launchSettings.json new file mode 100644 index 00000000..fc03871a --- /dev/null +++ b/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" + } + } + } +} diff --git a/templates/content/OpenIddict.Server.Identity/ViewModels/AuthorizeViewModel.cs b/templates/content/OpenIddict.Server.Identity/ViewModels/AuthorizeViewModel.cs new file mode 100644 index 00000000..8f580ec0 --- /dev/null +++ b/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; } +} diff --git a/templates/content/OpenIddict.Server.Identity/ViewModels/VerifyViewModel.cs b/templates/content/OpenIddict.Server.Identity/ViewModels/VerifyViewModel.cs new file mode 100644 index 00000000..7a39e973 --- /dev/null +++ b/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; } +} diff --git a/templates/content/OpenIddict.Server.Identity/Views/Authorization/Authorize.cshtml b/templates/content/OpenIddict.Server.Identity/Views/Authorization/Authorize.cshtml new file mode 100644 index 00000000..1a85e3d2 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Views/Authorization/Authorize.cshtml @@ -0,0 +1,21 @@ +@using Microsoft.Extensions.Primitives +@model AuthorizeViewModel +@{ + ViewData["Title"] = "Authorization"; +} + +

Authorization

+ +

Do you want to grant @Model.ApplicationName access to your data? (scopes requested: @Model.Scope)

+ +
+ @* Flow the request parameters so they can be received by the Accept/Deny actions: *@ + @foreach (var parameter in Context.Request.HasFormContentType ? + (IEnumerable>) Context.Request.Form : Context.Request.Query) + { + + } + + + + diff --git a/templates/content/OpenIddict.Server.Identity/Views/Authorization/EndSession.cshtml b/templates/content/OpenIddict.Server.Identity/Views/Authorization/EndSession.cshtml new file mode 100644 index 00000000..4f16764f --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Views/Authorization/EndSession.cshtml @@ -0,0 +1,19 @@ +@using Microsoft.Extensions.Primitives +@{ + ViewData["Title"] = "Log out"; +} + +

Log out

+ +

Are you sure you want to sign out?

+ +
+ @* Flow the request parameters so they can be received by the EndSessionPost action: *@ + @foreach (var parameter in Context.Request.HasFormContentType ? + (IEnumerable>) Context.Request.Form : Context.Request.Query) + { + + } + + + diff --git a/templates/content/OpenIddict.Server.Identity/Views/Authorization/Verify.cshtml b/templates/content/OpenIddict.Server.Identity/Views/Authorization/Verify.cshtml new file mode 100644 index 00000000..6e48c5a5 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Views/Authorization/Verify.cshtml @@ -0,0 +1,50 @@ +@using Microsoft.Extensions.Primitives +@model VerifyViewModel +@{ + ViewData["Title"] = "Device authorization"; +} + +

Authorization

+ +@if (string.IsNullOrEmpty(Model.UserCode) || !string.IsNullOrEmpty(Model.Error)) +{ + @if (!string.IsNullOrEmpty(Model.Error) && !string.IsNullOrEmpty(Model.ErrorDescription)) + { +

+ An error occurred: +
+ @Model.ErrorDescription (@Model.Error) +

+ } + +

Enter the user code given by the client application:

+ +
+
+ +
+ + +
+} +else +{ +

Do you want to grant @Model.ApplicationName access to your data? (scopes requested: @Model.Scope)

+

+ Make sure that the code displayed on the device is @Model.UserCode. +
+ If the two codes don't match, press "No" to reject the authorization demand. +

+ +
+ @* Flow the request parameters so they can be received by the VerifyAccept/VerifyDeny actions: *@ + @foreach (var parameter in Context.Request.HasFormContentType ? + (IEnumerable>) Context.Request.Form : Context.Request.Query) + { + + } + + + + +} diff --git a/templates/content/OpenIddict.Server.Identity/Views/Shared/_Layout.cshtml b/templates/content/OpenIddict.Server.Identity/Views/Shared/_Layout.cshtml new file mode 100644 index 00000000..de3246e6 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Views/Shared/_Layout.cshtml @@ -0,0 +1,23 @@ + + + + + + @ViewData["Title"] - Company.Server + + + + + +
+ @RenderBody() +
+ + @await RenderSectionAsync("Scripts", required: false) + + diff --git a/templates/content/OpenIddict.Server.Identity/Views/Shared/_LoginPartial.cshtml b/templates/content/OpenIddict.Server.Identity/Views/Shared/_LoginPartial.cshtml new file mode 100644 index 00000000..a2519800 --- /dev/null +++ b/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. *@ + diff --git a/templates/content/OpenIddict.Server.Identity/Views/_ViewImports.cshtml b/templates/content/OpenIddict.Server.Identity/Views/_ViewImports.cshtml new file mode 100644 index 00000000..ca772368 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Views/_ViewImports.cshtml @@ -0,0 +1,3 @@ +@using Company.Server +@using Company.Server.ViewModels +@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers diff --git a/templates/content/OpenIddict.Server.Identity/Views/_ViewStart.cshtml b/templates/content/OpenIddict.Server.Identity/Views/_ViewStart.cshtml new file mode 100644 index 00000000..820a2f6e --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Views/_ViewStart.cshtml @@ -0,0 +1,3 @@ +@{ + Layout = "_Layout"; +} diff --git a/templates/content/OpenIddict.Server.Identity/Worker.cs b/templates/content/OpenIddict.Server.Identity/Worker.cs new file mode 100644 index 00000000..94898ca7 --- /dev/null +++ b/templates/content/OpenIddict.Server.Identity/Worker.cs @@ -0,0 +1,34 @@ +using Company.Server.Data; +using OpenIddict.Abstractions; + +namespace Company.Server; + +/// +/// Creates the database and registers the client applications declared in the "OpenIddict:Clients" section. +/// +/// In production, the database should be created using migrations as part of the deployment. +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(); + await context.Database.EnsureCreatedAsync(cancellationToken); + + var manager = scope.ServiceProvider.GetRequiredService(); + + foreach (var client in configuration.GetSection("OpenIddict:Clients").Get>() ?? []) + { + 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; +} diff --git a/templates/content/OpenIddict.Server.Identity/appsettings.Development.json b/templates/content/OpenIddict.Server.Identity/appsettings.Development.json new file mode 100644 index 00000000..3e5fb25c --- /dev/null +++ b/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" ] + } + ] + } +} diff --git a/templates/content/OpenIddict.Server.Identity/appsettings.json b/templates/content/OpenIddict.Server.Identity/appsettings.json new file mode 100644 index 00000000..329bcb6b --- /dev/null +++ b/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": "*" +} diff --git a/templates/verify.sh b/templates/verify.sh new file mode 100644 index 00000000..e96a6ec3 --- /dev/null +++ b/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 + +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"