Skip to main content

Sign-in for an ASP.NET Core app

Add cookie sign-in with OpenID Connect to an ASP.NET Core app, and bearer tokens for its API.

RecipeReadyView source
Works with
C# / .NETASP.NET Core

What it shows​

  1. AddLumoAuth registers the SDK. It reads LUMOAUTH_URL and LUMOAUTH_ORG_ID, and the app needs no API key.
  2. AddLumoAuthWebAppAuthentication adds a cookie scheme and the OpenID Connect handler of ASP.NET Core, with PKCE. A signed-out browser goes to the hosted sign-in page.
  3. After sign-in the cookie holds the session, and each page reads the person from the claims.
  4. AddLumoAuthBearer accepts access tokens on /api/me. The SDK asks LumoAuth who the token belongs to.
  5. /signout ends the session of the app, then sends the browser to LumoAuth to end the session there. The sign-out form carries an antiforgery token of ASP.NET Core.

Before you start​

  • The .NET 10 SDK. The app is one file that dotnet run starts without a project file.
  • A trusted development certificate for https://localhost:5001. Run dotnet dev-certs https --trust once.
  • An API key with the scopes admin:clients:read and admin:clients:write. Create it in the portal under Applications & developer tools, API keys.
  • A confidential application with the redirect URI https://localhost:5001/signin-lumoauth. The setup script creates it.
VariableValue
LUMOAUTH_URLThe address of LumoAuth: https://app.lumoauth.dev, or https://eu.app.lumoauth.dev for the EU region.
LUMOAUTH_ORG_IDYour organization, for example acme-corp.
LUMOAUTH_API_KEYAn API key with the scopes admin:clients:read and admin:clients:write. Only the setup script uses it.
APP_URLOptional. The address of your app, when it is not https://localhost:5001. The setup script and the app read it.
LUMOAUTH_CLIENT_IDThe client ID of the application. The setup script prints it.
LUMOAUTH_CLIENT_SECRETThe client secret of the application. The setup script prints it.

The setup script creates the application through the Admin API and prints the variables of the app. LumoAuth shows a client secret only once, so each run makes a new secret.

node sign-in/aspnet-core/setup.mjs
setup.mjs
// Creates the application that the ASP.NET Core app signs in with: a
// confidential application with the callback address of the app. Run it again
// at any time.
//
// node sign-in/aspnet-core/setup.mjs
//
// The API key needs the scopes admin:clients:read and admin:clients:write.
// APP_URL is the address of your app. The default is https://localhost:5001.
// The address for the return after sign-out is set in the portal: the Admin
// API has no field for it.
import { call, list, printEnv } from '../../_lib/admin.mjs';

const appUrl = (process.env.APP_URL ?? 'https://localhost:5001').replace(/\/+$/, '');
const name = 'ASP.NET Core sign-in';
// The OpenID Connect handler of the SDK receives the code at this path.
const redirectUris = [`${appUrl}/signin-lumoauth`];

let secret;
let client = (await list('/admin/clients')).find((c) => c.name === name);
if (client) {
// LumoAuth shows a client secret only once, so a second run makes a new one.
await call('PATCH', `/admin/clients/${client.id}`, { redirectUris });
secret = (await call('POST', `/admin/clients/${client.id}/rotate-secret`)).data.secret;
} else {
client = (await call('POST', '/admin/clients', { name, redirectUris, isConfidential: true })).data;
secret = client.secret;
}

console.log(`Application "${name}" is ready. Its redirect URI is ${redirectUris[0]}.`);
printEnv({
LUMOAUTH_CLIENT_ID: client.clientId,
LUMOAUTH_CLIENT_SECRET: secret,
});

Copy the export lines that the script prints into the terminal where you start the app.

Sign-out returns to your app only when the address is registered. The Admin API has no field for it, so add it in the portal:

  1. Open Applications and select ASP.NET Core sign-in.
  2. Open the Configuration tab and go to the section Logout.
  3. Under Post-logout redirect URIs, enter https://localhost:5001/signout-callback-lumoauth.
  4. Select Save configuration.

Code​

Run each command from the recipes folder of the examples repository. Set the folder up once for your language. Every version below was run against a LumoAuth organization. A browser signed in and out through the hosted page with .NET 10, and the API route was called with an access token. A form on another site that posted to /signout got 403.

sign-in/aspnet-core/csharp/SignIn.cs
#:sdk Microsoft.NET.Sdk.Web
#:package LumoAuth.AspNetCore@1.7.0
#:property PublishAot=false
// An ASP.NET Core app with sign-in: the hosted sign-in page, a cookie
// session, a protected page, an API route for bearer tokens, and a sign-out
// that also ends the session at LumoAuth.
//
// dotnet run sign-in/aspnet-core/csharp/SignIn.cs
using System.Net;
using System.Security.Claims;
using System.Security.Cryptography;
using LumoAuth.AspNetCore;
using LumoAuth.AspNetCore.Authentication;
using Microsoft.AspNetCore.Antiforgery;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Caching.Memory;

var builder = WebApplication.CreateBuilder(args);

// LumoAuth sends the browser back to this address, so it must match the
// redirect URI of the application.
var appUrl = builder.Configuration["APP_URL"] ?? "https://localhost:5001";
builder.WebHost.UseUrls(appUrl);

// Registers the SDK. LUMOAUTH_URL and LUMOAUTH_ORG_ID name the organization.
// The app only signs people in, so it needs no API key.
builder.Services.AddLumoAuth(lumo => lumo.CredentialOptional = true);

// A cookie session and OpenID Connect sign-in for browsers. LumoAuth returns
// the code to /signin-lumoauth. The bearer scheme is for the API route.
var states = new MemoryCache(new MemoryCacheOptions());
builder.Services
.AddLumoAuthWebAppAuthentication(
login =>
{
login.ClientId = builder.Configuration["LUMOAUTH_CLIENT_ID"];
login.ClientSecret = builder.Configuration["LUMOAUTH_CLIENT_SECRET"];
},
// The default `state` is too long for LumoAuth. See ShortState below.
oidc => oidc.StateDataFormat = new ShortState(states))
.AddLumoAuthBearer();
builder.Services.AddAuthorization();
// The sign-out form carries an antiforgery token, so that no other site can
// send it.
builder.Services.AddAntiforgery();

var app = builder.Build();
app.UseAuthentication();
app.UseAuthorization();

static IResult Html(string body) => Results.Content(body, "text/html; charset=utf-8");
static string Encode(string? text) => WebUtility.HtmlEncode(text ?? "");
// The hidden field with the antiforgery token, for a form of this app.
static string TokenField(IAntiforgery antiforgery, HttpContext context)
{
var token = antiforgery.GetAndStoreTokens(context);
return $"<input type=\"hidden\" name=\"{token.FormFieldName}\" value=\"{token.RequestToken}\">";
}

// A public page. It shows who is signed in, if anybody.
app.MapGet("/", (ClaimsPrincipal user, HttpContext context, IAntiforgery antiforgery) => Html(
user.Identity?.IsAuthenticated == true
? $"<p>Signed in as {Encode(user.FindFirstValue("email"))}.</p>"
+ "<p><a href=\"/dashboard\">Dashboard</a></p>"
+ $"<form method=\"post\" action=\"/signout\">{TokenField(antiforgery, context)}<button>Sign out</button></form>"
: "<p>Nobody is signed in.</p><p><a href=\"/signin\">Sign in</a></p>"));

// Sends the browser to the hosted sign-in page, then back to the dashboard.
app.MapGet("/signin", () => Results.Challenge(new AuthenticationProperties { RedirectUri = "/dashboard" }));

// A protected page. A browser with no session goes to the hosted sign-in page.
app.MapGet("/dashboard", (ClaimsPrincipal user) => Html(
$"<h1>Dashboard</h1><p>User ID: {Encode(user.GetLumoAuthSubject())}</p>"
+ $"<p>Name: {Encode(user.FindFirstValue("name"))}</p><p><a href=\"/\">Home</a></p>"))
.RequireAuthorization();

// An API route. It accepts an access token of LumoAuth and answers 401
// without one. The SDK asks LumoAuth who the token belongs to.
app.MapGet("/api/me", (ClaimsPrincipal user) => new
{
sub = user.GetLumoAuthSubject(),
email = user.FindFirstValue(ClaimTypes.Email),
})
.RequireAuthorization(new AuthorizeAttribute { AuthenticationSchemes = LumoAuthDefaults.BearerScheme });

// Sign-out. The cookie scheme removes the session of the app. The OpenID
// Connect scheme then sends the browser to LumoAuth with the ID token. LumoAuth
// ends its session and returns to /signout-callback-lumoauth. Another site
// must not be able to sign a person out: a form without the antiforgery token
// of this app gets 403.
app.MapPost("/signout", async (HttpContext context, IAntiforgery antiforgery) =>
await antiforgery.IsRequestValidAsync(context)
? Results.SignOut(
new AuthenticationProperties { RedirectUri = "/" },
[LumoAuthDefaults.CookieScheme, LumoAuthDefaults.OpenIdConnectScheme])
: Results.StatusCode(StatusCodes.Status403Forbidden));

app.Run();

// Keeps the sign-in data of the OpenID Connect handler on the server and
// sends only a random key as `state`. The handler puts its data (the return
// address, the PKCE verifier, the correlation ID) into `state`, encrypted.
// That value is about 400 characters long, and LumoAuth accepts a `state` of
// at most 255 characters.
sealed class ShortState(IMemoryCache cache) : ISecureDataFormat<AuthenticationProperties>
{
// A sign-in that takes longer than this starts again.
static readonly TimeSpan Lifetime = TimeSpan.FromMinutes(15);

public string Protect(AuthenticationProperties data) => Protect(data, null);

public string Protect(AuthenticationProperties data, string? purpose)
{
var key = Convert.ToHexString(RandomNumberGenerator.GetBytes(16));
cache.Set(key, data, Lifetime);
return key;
}

public AuthenticationProperties? Unprotect(string? protectedText) => Unprotect(protectedText, null);

public AuthenticationProperties? Unprotect(string? protectedText, string? purpose)
{
if (protectedText is null || !cache.TryGetValue(protectedText, out AuthenticationProperties? data))
{
return null;
}
// Each key works once, so a callback cannot be used twice.
cache.Remove(protectedText);
return data;
}
}
dotnet run sign-in/aspnet-core/csharp/SignIn.cs

Check the result​

Open https://localhost:5001 in a browser, select Sign in, and sign in as a user of your organization.

Output
Signed out
GET / 200 Nobody is signed in.
GET /dashboard 302 https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?client_id=…
GET /api/me 401

Signed in
GET / 200 Signed in as maya.chen@example.com.
GET /dashboard 200 User ID: 0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10 Name: Maya Chen

With a bearer token
GET /api/me 200 {"sub":"0195c1e2-7a41-7c3e-9b1d-2f6a8d4e5c10","email":"maya.chen@example.com"}

After Sign out
GET /dashboard 302 https://app.lumoauth.dev/orgs/acme-corp/api/v1/oauth/authorize?client_id=…
(the hosted page asks for the email address again)
  • The session is the cookie .AspNetCore.LumoAuthCookie, marked httpOnly. It holds the tokens, encrypted by ASP.NET Core. At about 5 KB, ASP.NET Core splits it into two or three cookies.
  • /api/me answers 401 with WWW-Authenticate: Bearer realm="LumoAuth" to a request with no token. A browser cookie does not count on this route.
  • Sign out sends the browser to LumoAuth and back to /signout-callback-lumoauth, then to /. After that, /dashboard shows the hosted sign-in page again.
  • A form on another site that posts to /signout gets 403, because it has no antiforgery token of the app. The person stays signed in.

To call the API with a bearer token, send an access token of a signed-in person:

curl -H "Authorization: Bearer $ACCESS_TOKEN" https://localhost:5001/api/me

Limits​

  • The OpenID Connect handler puts its sign-in data in state, encrypted, which makes a value of about 400 characters. LumoAuth refuses a state of more than 255 characters: see Limits on state and nonce. The class ShortState therefore keeps the data on the server and sends a random key of 32 characters.
  • ShortState keeps the data in the memory of one process. If the app runs on several servers, store it in a shared cache, so that the callback finds it on any server.
  • The bearer scheme asks the UserInfo endpoint about each token, on every request. It does not check the token locally.
  • Without the OpenID Connect scheme in the call to Results.SignOut, /signout ends only the session of the app. The person stays signed in at LumoAuth.