angel3_oidc_server 10.0.1
angel3_oidc_server: ^10.0.1 copied to clipboard
OpenID Connect for an Angel3 OAuth 2.0 server of angel3_auth_server, of ID tokens, JWKS, discovery and UserInfo.
Angel3 OpenID Connect Server #
Add OpenID Connect to an OAuth 2.0 server built with angel3_auth_server. Your server becomes an OpenID Provider. It issues ID tokens, which tell an app who signed in, and serves its JSON Web Key Set, its configuration and its users' claims.
- Installation
- Usage
- Signing keys
- ID tokens
- UserInfo
- Signing in: 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 from angel3_auth_server, so it does everything that one does, PKCE included. Implement its methods as that package's README describes, and these as well:
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, which is the audience of its ID tokens.
@override
String clientIdOf(Client client) => client.id;
/// The subject of a user: an id for them that never changes.
@override
String subjectOf(User user) => user.id;
/// The user's claims. UserInfo gives those that a token's scopes allow.
@override
Map<String, dynamic> claimsOf(User user) =>
{'name': user.name, 'email': user.email, 'email_verified': true};
// ... plus 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 an https URL, or an http URL on localhost, with no query or fragment, as OpenID Connect Discovery requires.
Signing keys #
ID tokens are signed with RS256 or ES256. Every OpenID Provider must support RS256.
Generate a key once and store its toJson(), which is a private JSON Web Key, as a secret. Load it on each start. That way, tokens it signed stay valid across restarts, and every instance signs with the same key.
var key = OpenIdSigningKey.generate(keyId: '2026-11');
await storeSecretSomehow(json.encode(key.toJson()));
// On each start:
var loaded = OpenIdSigningKey.fromJwk(json.decode(await readSecretSomehow()));
- Which key signs. A client's ID tokens are signed with the first key of the client's algorithm. The algorithm is the
algorithmgiven toissueIdToken, or else the oneidTokenAlgorithmOfreturns, or else the one in theclientMetadatagiven toissueIdToken, or elseRS256, the OpenID Connect default. - What is published. The JSON Web Key Set publishes every key, with only its public members.
- Requirements. RSA keys must be at least 2048 bits, and the server must have an
RS256key. - Damaged keys. A key whose private part doesn't match its public part, such as a stored key that was damaged or pasted wrongly, is refused when it loads. The check makes a test signature and verifies it with the public key, for both
RS256andES256.
Rotating keys #
signingKeys can't be changed while the server runs. To rotate:
- Build the server with the new key placed first among the keys of its algorithm, for example on a restart.
- Keep the old key in the list until the ID tokens it signed have expired, then remove it.
Timing and faults #
RS256is blinded.RS256signatures use RSA blinding, as BoringSSL and OpenSSL do, so the time a signature takes reveals nothing about the key.- Each signature is checked. It is verified before it is given out. This guards against a computation fault, which could leak a factor of the key.
- Not constant-time otherwise. The arithmetic is pure Dart.
ES256is not constant-time. Its signatures come frompackage:jose_plus, whose curve arithmetic is not constant-time. PreferRS256where timing attacks against the server are a concern.
ID tokens #
The authorization request #
An authorization request with the openid scope asks for an ID token. requestAuthorizationCode finds its OpenIdRequest in req.container, just as it finds the Pkce. Store its nonce with the code, together with the time the user authenticated.
var openId = req.container!.make<OpenIdRequest>();
// openId.isOpenId, openId.nonce, openId.prompt, openId.maxAge
- Parameters are always checked. The OpenID Connect parameters of every authorization request are checked through
checkAuthorizationRequestfromangel3_auth_server, whether your app reads them or not. A malformedmax_ageorpromptgetsinvalid_request, which the authorization endpoint redirects like its other errors. prompt=noneis the app's to answer. Only the app knows whether the user is signed in. Callinteractions(see Signing in), or the user may be prompted after all.max_age. The user must have authenticated within it, or authenticate again.- Deciding on an ID token. Go by the scopes granted and stored with the code, not by
isOpenId. A request with no scope is notisOpenId, but your app may grant itopenidby default and then issue an ID token.
Issuing the ID token #
In exchangeAuthorizationCodeForToken, issue the ID token along with the access token, as an IdTokenResponse:
var idToken = issueIdToken(
user: stored.user,
client: client!,
// Gives the nonce and max_age, and 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);
What the token contains:
iss,sub,aud,expandiat(OpenID Connect Core §2);- the request's
nonce; auth_time;- the
at_hashof the access token; - any
claimsof your own, such asacroramr. They can't replace the standard claims above.
What to pass in:
request: theOpenIdRequeststored with the code. It supplies thenonce.clientMetadata: the metadata of a client that registered itself. It supplies the client's algorithm.requireAuthTimeandalgorithm: set these yourself when you don't passclientMetadata.
Rules:
auth_timemay be required. It is required if the request had amax_age, or the client registeredrequire_auth_timeordefault_max_age. In that caseissueIdTokenthrows anArgumentErrorifauthTimeis missing, rather than issue a token without it.- No
openidscope, no ID token. It throws anArgumentErrorfor arequestthat had scopes but notopenid. - Lifetime. The token is valid for
idTokenLifetime, 10 minutes by default. - Refresh token grants. Issue an ID token with no
nonceand norequest, but with theauthTimeof the original sign-in. Keep that time with the refresh token, since a client withrequire_auth_timeordefault_max_ageneeds it in every ID token.
UserInfo #
userInfoEndpoint takes an access token with the openid scope, from an Authorization: Bearer header or from the form of a POST. It returns:
- the
subof the token's user; - the user's claims from
claimsOf, limited to those the token's scopes allow.
The standard scopes are profile, email, address and phone, defined in standardScopeClaims. Override scopeClaims to add scopes of your own.
Errors:
- A token with no user, such as one from the client credentials grant, gets
invalid_token, a 401. - A token without the
openidscope getsinsufficient_scope, a 403.
Its responses are not cached.
Signing in: prompt and max_age #
OpenIdRequest.interactions tells requestAuthorizationCode what to do with the user before it issues a code. It returns a set of OpenIdInteractions:
login. Sign the user in again. This happens if they aren't signed in, if they haven't signed in within themax_age, or if the request saysprompt=login. When the request has nomax_age, pass the client'sdefault_max_ageasdefaultMaxAge.selectAccount. Let the user pick an account, forprompt=select_account.consent. Ask for the user's consent, if they haven't given it or the request saysprompt=consent.- Empty. Issue the code at once.
With prompt=none the user must not be prompted. In that case it throws login_required, account_selection_required or consent_required instead (see OpenIdErrors). The authorization endpoint redirects that error to the client.
Asking the user #
Call interactions once, when the request first arrives. If the user has to be asked something:
- Keep what the code needs in their session on the server, under an id that is random and used only once.
- Send them to your login page with that id.
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 when the
// request 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');
}
Issuing the code afterwards #
Once the user has done what was asked, your own handler:
- takes the pending request out of the session, so it can only be used once;
- issues the code without sending the user back to the authorization endpoint.
The authTime to store depends on what the user did:
- They signed in just now: use the time of that login.
- They only consented or picked an account: use the session's existing time, because they didn't sign in again.
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,
));
For an implicit request, which allowsImplicitGrant must allow, give the token with completeImplicitGrant instead.
Why not go back to the authorization endpoint #
Sending the user back to the authorization endpoint would ask them all over again:
prompt=login,select_account,consentandmax_age=0ask every time, whatever happened before.- A
max_ageabove 0 needs a sign-in within it. - Your app could put a marker in that URL to say the user had been asked. But the user could set that marker themselves, and so skip a login the client asked for.
How max_age and the OpenID parameters are read #
max_agemust be digits only. It is capped atOpenIdRequest.maxMaxAge, about 68 years.- The OpenID Connect parameters of a request whose scopes don't include
openidare not checked, because that request isn't OpenID Connect. - The parameters of a request with no scope, or a blank one, are checked. Your app may grant it
openidby default and then issue an ID token.
Logout #
endSessionEndpoint signs a user out of the provider at a client's request (OpenID Connect RP-Initiated Logout 1.0). To set it up:
- Route both a GET and a POST to it.
- Give its URL to
openIdConfigurationEndpointasendSessionEndpoint. - Implement these two methods:
@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);
}
Checks. If any of these fails, the request gets invalid_request, a 400, which is never redirected:
-
id_token_hint: an ID token from this provider. It must:- be signed with the provider's keys and have its issuer. It may have expired;
- have the type
JWT, or no type; - have a
suband anaud; - not be a logout token.
These checks stop any other JWT signed with the provider's keys from passing as one.
-
client_id: the audience of the hint. -
post_logout_redirect_uri: one of the client'spostLogoutRedirectUrisOf.
What endSession should do:
- A request without a hint could come from anyone's link. In
endSession, ask the user whether to sign out first, and once they agree, redirect them torequest.redirectUri. - If
endSessiondoesn't answer the request itself, the user is redirected to thepost_logout_redirect_uriwith thestate, or told that they signed out. - By default,
endSessionrefuses with a 403.
Client registration #
At the registrationEndpoint from angel3_auth_server, checkClientMetadata also checks the metadata of OpenID Connect Dynamic Client Registration 1.0, and fills in defaults:
| Metadata | Rule | Default |
|---|---|---|
post_logout_redirect_uris |
Same rules as redirect_uris |
none |
id_token_signed_response_alg |
One of the algorithms of signingKeys |
RS256 |
subject_type |
Only public |
public |
default_max_age |
Capped at OpenIdRequest.maxMaxAge, like a request's max_age |
none |
require_auth_time |
A boolean | false |
application_type |
web or native |
web |
initiate_login_uri |
https |
none |
Metadata for features the server doesn't have gets invalid_client_metadata. These features are signed or encrypted UserInfo responses, encrypted ID tokens, request objects and pairwise subjects.
To use the metadata after registration:
- Read it back with
OpenIdClientMetadata.of(registration.metadata), and pass it toissueIdTokenasclientMetadata. - Or return the client's algorithm from
idTokenAlgorithmOf.issueIdTokenthen signs the client's ID tokens with the first key of that algorithm.
Configuration #
openIdConfigurationEndpoint serves the OpenID Provider configuration at openIdConfigurationPath (/.well-known/openid-configuration). It contains:
- the server metadata from
angel3_auth_server; jwks_uri,userinfo_endpointandend_session_endpoint;subject_types_supported, which ispublic;id_token_signing_alg_values_supportedandprompt_values_supported;- the
openidscope, and the claims ofscopeClaims; claims_parameter_supported,request_parameter_supportedandrequest_uri_parameter_supported, allfalse. They are listed because their default istrue, and the server supports neitherclaimsrequests nor request objects.
The issuer of the ServerMetadata you pass must be the server's own issuer.
What it does not do #
- The hybrid and implicit flows. ID tokens come only from the authorization code flow. Implicit grants are refused by default, as in
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 only through the end session endpoint.
- Checking ID tokens as a client. For the app that signs users in, use the
openIdoption ofOAuth2Strategyinangel3_auth_client.