Angel3 OpenID Connect Server
OpenID Connect for an OAuth 2.0 server of angel3_auth_server: an OpenID Provider that issues ID tokens, which tell an app who signed in, and serves its JSON Web Key Set, its configuration and the claims of its users.
- Installation
- Usage
- Signing keys
- ID tokens
- UserInfo
- Signing in, of prompt and max_age
- Logout
- Client registration
- Configuration
- What it does not do
Installation
dependencies:
angel3_oidc_server: ^10.0.0
Usage
OpenIdServer is an AuthorizationServer of angel3_auth_server, of everything it does, PKCE and all: implement its methods as that package's README tells, and these too:
import 'package:angel3_auth_server/angel3_auth_server.dart';
import 'package:angel3_oidc_server/angel3_oidc_server.dart';
class MyProvider extends OpenIdServer<Client, User> {
MyProvider(OpenIdSigningKey key)
: super(issuer: Uri.parse('https://id.example.com'), signingKeys: [key]);
/// The `client_id` of a client, the audience of its ID tokens.
@override
String clientIdOf(Client client) => client.id;
/// The subject of a user: an id of them that never changes.
@override
String subjectOf(User user) => user.id;
/// Their claims, of which UserInfo gives those of the scopes of a token.
@override
Map<String, dynamic> claimsOf(User user) =>
{'name': user.name, 'email': user.email, 'email_verified': true};
// ... and those of AuthorizationServer: findClient, verifyClient, and so on.
}
Route its endpoints:
app.group('/oauth2', (router) {
router
..get('/authorize', server.authorizationEndpoint)
..post('/authorize', server.authorizationEndpoint)
..post('/token', server.tokenEndpoint)
..get('/jwks', server.jwksEndpoint)
..get('/userinfo', server.userInfoEndpoint)
..post('/userinfo', server.userInfoEndpoint);
});
app.get(openIdConfigurationPath, server.openIdConfigurationEndpoint(
metadata,
jwksUri: Uri.parse('https://id.example.com/oauth2/jwks'),
userInfoEndpoint: Uri.parse('https://id.example.com/oauth2/userinfo'),
));
The issuer must be https, or http of localhost, and of no query nor fragment, as OpenID Connect Discovery requires.
Signing keys
ID tokens are signed with RS256, which every OpenID Provider must support, or ES256. Generate a key once, store its toJson(), a private JSON Web Key, as a secret, and load it on each start, so that the tokens it signed stay valid across restarts and every instance signs alike:
var key = OpenIdSigningKey.generate(keyId: '2026-11');
await storeSecretSomehow(json.encode(key.toJson()));
// On each start:
var loaded = OpenIdSigningKey.fromJwk(json.decode(await readSecretSomehow()));
The first key of a client's algorithm signs its ID tokens: of idTokenAlgorithmOf the client, or of RS256, the default of OpenID Connect, for a client of none. The JSON Web Key Set publishes all of them, of their public members alone. signingKeys cannot be changed: to rotate, build the server of a new key first among those of its algorithm, as on a restart, and remove the old one once the ID tokens it signed have expired. A key whose private part is not of its public one, as of a stored key that was damaged or mis-pasted, is refused as it loads, of a test signature that its public key verifies, of RS256 and ES256 alike. RSA keys must be of at least 2048 bits, and the server must have an RS256 key.
RS256 signatures are made with RSA blinding, as BoringSSL and OpenSSL make them, so that the time a signature takes tells nothing of the key, and each is checked before it is given out, against a fault of the computation, which could leak a factor of the key. The arithmetic is of pure Dart, and is not constant-time otherwise. ES256 signatures are of package:jose_plus, whose curve arithmetic is not constant-time: prefer RS256 where timing attacks against the server are a concern.
ID tokens
An authorization request of the openid scope asks for an ID token. requestAuthorizationCode is given its OpenIdRequest in req.container, as it is the Pkce: store its nonce with the code, and when the user authenticated. The OpenID Connect parameters of every authorization request are checked, of the checkAuthorizationRequest of angel3_auth_server, whether the app reads them or not: a malformed max_age or prompt is invalid_request, which the authorization endpoint redirects, as its other errors. prompt=none is the app's to answer, as only it knows whether the user is signed in: call interactions, below, or the user is prompted after all.
var openId = req.container!.make<OpenIdRequest>();
// openId.isOpenId, openId.nonce, openId.prompt, openId.maxAge
Decide whether to issue an ID token of the scopes granted, stored with the code, not of isOpenId: a request of no scope is not isOpenId, though the app may grant it openid by default, and then issue one.
Of prompt=none, the user must not be prompted, and of max_age, they must have authenticated within it, or authenticate again: see Signing in.
Issue the ID token with the access token in exchangeAuthorizationCodeForToken, as an IdTokenResponse:
var idToken = issueIdToken(
user: stored.user,
client: client!,
// Of its nonce and max_age, and of what the client registered, if it did.
request: stored.openId,
clientMetadata: stored.clientMetadata,
authTime: stored.authTime,
accessToken: accessToken,
);
return IdTokenResponse(accessToken, idToken: idToken, expiresIn: 3600);
It has the iss, sub, aud, exp and iat of OpenID Connect Core ยง2, which claims of your own, as acr or amr, may not set, nor its nonce, auth_time or at_hash, the nonce of the request, its auth_time, and the at_hash of the access token. Give it the request stored with the code, and the clientMetadata of a client that registered itself: of them, it takes the nonce, the client's algorithm, and whether the token must have an auth_time, of a max_age of the request, or of the client's require_auth_time or default_max_age, of which it throws an ArgumentError of no authTime, rather than issue a token without it. requireAuthTime and algorithm say so of your own. It is valid for idTokenLifetime (default 10 minutes). Of a refresh token grant, issue one of no nonce, and of the authTime of the first.
UserInfo
userInfoEndpoint gives, of an access token of the openid scope, of an Authorization: Bearer header or of the form of a POST, the sub of its user and their claims of claimsOf of the scopes of the token: profile, email, address and phone, of standardScopeClaims. Override scopeClaims to add scopes of your own. A token of no user, as of the client credentials grant, is invalid_token, a 401; one without the openid scope insufficient_scope, a 403. Its responses are not cached.
Signing in, of prompt and max_age
OpenIdRequest.interactions tells requestAuthorizationCode what to do with the user before it issues a code: sign them in again, as they are not, or not since its max_age (or the client's default_max_age), or of prompt=login; let them select an account, of prompt=select_account; ask for their consent, as they have not given it, or of prompt=consent; or none of these, to issue the code at once. Of prompt=none, of which the user may not be prompted, it throws login_required, account_selection_required or consent_required instead, which the authorization endpoint redirects to the client.
Ask it once, when the request first comes. If the user must be asked something, keep what the code needs in their session on the server, under an id that is random and used once, and send them to your login page with it:
var openId = req.container!.make<OpenIdRequest>();
var needed = openId.interactions(
signedIn: session.user != null,
authTime: session.authTime,
consented: await hasConsentedSomehow(session.user, client),
);
if (needed.isNotEmpty) {
var id = randomIdSomehow();
session.pending[id] = (
client: client,
// Never null here: the endpoint gives the registered one, of a request
// that left it out.
redirectUri: redirectUri!,
scopes: scopes.toList(),
state: state,
implicit: implicit,
openId: openId,
pkce: req.container!.make<Pkce>(),
needed: needed,
);
return res.redirect('/login?pending=$id');
}
Once the user has done what was asked, your own handler takes the pending request out of the session, so that it is used once, and issues its code without sending them back to the authorization endpoint. Its authTime is that of a login the user just made, or, of consent or an account selection alone, that of the session, which they did not sign in again of:
var pending = session.pending.remove(req.queryParameters['pending']);
if (pending == null) throw AngelHttpException.badRequest();
var signedInNow = pending.needed.contains(OpenIdInteraction.login);
var code = await storeCodeSomehow(
pending,
authTime: signedInNow ? DateTime.now() : session.authTime!,
);
await res.redirect(server.completeAuthorizationCode(
code,
Uri.parse(pending.redirectUri),
state: pending.state,
));
Of an implicit request, which allowsImplicitGrant must allow, give its token with completeImplicitGrant instead.
Sending the user back to the authorization endpoint instead would ask them again, as of prompt=login, select_account or consent, or of max_age=0, which ask whatever was done before; and anything the app put in that URL to say they had been asked, the user could set, and so skip a login the client asked for. A max_age above 0 needs a sign-in within it. max_age is of digits alone, and is capped at OpenIdRequest.maxMaxAge, some 68 years. The OpenID Connect parameters of a request whose scopes have no openid are not checked, as they are not of OpenID Connect; those of a request of no scope, or a blank one, are, as the app may grant openid by default, and may then be issued an ID token.
Logout
endSessionEndpoint signs a user out of the provider at the request of a client (OpenID Connect RP-Initiated Logout 1.0). Route a GET and a POST to it, give its URL to openIdConfigurationEndpoint as endSessionEndpoint, and implement:
@override
Iterable<Uri> postLogoutRedirectUrisOf(Client client) =>
OpenIdClientMetadata.of(client.metadata).postLogoutRedirectUris;
@override
Future<void> endSession(
EndSessionRequest<Client> request, RequestContext req, ResponseContext res) async {
await signOutSomehow(req, request.subject);
}
Its id_token_hint must be an ID token of the provider, of its keys and issuer, expired or not, of the type JWT or none, of a sub and an aud, and not a logout token, so that no other JWT of the provider's keys passes for one; its client_id the audience of the hint; and its post_logout_redirect_uri one of postLogoutRedirectUrisOf the client, or the request is invalid_request, a 400, which is never redirected. A request of no hint could be of anyone's link: ask the user whether to sign out first, in endSession, and redirect them to request.redirectUri once they did. Unless endSession answers, the user is redirected to the post_logout_redirect_uri, with the state, or told that they signed out. By default, endSession refuses, a 403.
Client registration
Of the registrationEndpoint of angel3_auth_server, checkClientMetadata checks the metadata of OpenID Connect Dynamic Client Registration 1.0 too, and gives its defaults: post_logout_redirect_uris, of the form of redirect_uris; id_token_signed_response_alg, of the algorithms of signingKeys (RS256); subject_type, public alone; default_max_age, capped at OpenIdRequest.maxMaxAge, as a request's max_age, and require_auth_time (false); application_type, web or native (web); and initiate_login_uri, of https. Metadata of what the server does not do, such as signed or encrypted UserInfo responses, encrypted ID tokens, request objects and pairwise subjects, is invalid_client_metadata. Read it back of the registration with OpenIdClientMetadata.of(registration.metadata), and give the client's algorithm to idTokenAlgorithmOf, of which issueIdToken signs its ID tokens with the first key of it.
Configuration
openIdConfigurationEndpoint serves the OpenID Provider configuration at openIdConfigurationPath (/.well-known/openid-configuration): the server metadata of angel3_auth_server, and its jwks_uri, userinfo_endpoint, end_session_endpoint, subject_types_supported (public), id_token_signing_alg_values_supported, prompt_values_supported, the openid scope and the claims of scopeClaims, and that it supports no claims requests nor request objects, of claims_parameter_supported, request_parameter_supported and request_uri_parameter_supported, whose default is true. The issuer of its ServerMetadata must be that of the server.
What it does not do
- The hybrid and implicit flows: ID tokens are of the authorization code flow. Implicit grants are refused by default, as by
angel3_auth_server. - Request objects (
request,request_uri),claimsrequests, pairwise subjects, encrypted ID tokens, and signed or encrypted UserInfo responses. - Front-channel and back-channel logout, and session management: logout is of the end session endpoint alone.
- Checking ID tokens as a client: that is the
openIdof theOAuth2Strategyofangel3_auth_client, for the app that signs users in.
Libraries
- angel3_oidc_server
- OpenID Connect for an OAuth 2.0 server of
angel3_auth_server.