Polhem.OAuth2 1.5.0: any OpenID Connect provider, Sign in with Apple, GitHub, and signing in through the back end whenever there is one
Polhem.OAuth2 now supports OpenID Connect, the sign-in standard built on top of OAuth2. Versions 1.4.0 and 1.5.0 added:
- Apple accounts
- GitHub accounts
- Custom OpenID Connect providers, such as Keycloak, GitLab and AWS Cognito
- Desktop apps signing in through a back end
- One rule for apps with a back end: the back end does the sign-in
The previous post, One OAuth2 Library for Every Kind of .NET App, introduced the library. It lets desktop apps, .NET MAUI, ASP.NET Core and older Web Forms sites add third-party sign-in the same way, and at the time it supported Google, Facebook, LINE, Microsoft Entra ID, Auth0 and Okta. This post covers what is new.
1️⃣ Supported platforms and accounts
First, the kinds of applications supported as of 1.5.0:
- Desktop and console apps: open the system browser and receive the callback on
127.0.0.1on the local machine. Works on Windows, macOS and Linux. They can talk to the provider directly, or go through a back end when there is one. - .NET MAUI apps on Android, iOS and Mac Catalyst: sign in through
WebAuthenticator, either directly with the provider or through your own back end. - ASP.NET Core websites.
- Web Forms and MVC sites on ASP.NET (System.Web).
- Other server frameworks: the core
OAuth2Clientsplits sign-in into two steps, creating the authorization URL and completing the sign-in, and does not depend on any HTTP framework.
| Package | Target frameworks | Used for |
|---|---|---|
| Polhem.OAuth2 | netstandard2.0, net8.0, net10.0 | The providers; desktop, console and .NET MAUI apps; other server frameworks |
| Polhem.OAuth2.AspNetCore | net10.0 | ASP.NET Core |
| Polhem.OAuth2.AspNet | net472 | Web Forms and MVC on System.Web |
The supported accounts, and how each one works in each kind of application:
| Account | Protocol | Desktop and console | .NET MAUI | Web |
|---|---|---|---|---|
| OAuth2 + OIDC | Directly or through the back end | Directly on iOS and Mac Catalyst; through the back end on Android | Yes | |
| OAuth2 | Directly or through the back end | Directly or through the back end | Yes | |
| LINE | OAuth2, email taken from the ID token | Directly or through the back end | Directly on iOS and Mac Catalyst; through the back end on Android | Yes |
| Microsoft Entra ID | OAuth2 + OIDC | Directly or through the back end | Directly or through the back end | Yes |
| Auth0 | OAuth2 + OIDC | Directly or through the back end | Directly or through the back end | Yes |
| Okta | OAuth2 + OIDC | Directly or through the back end | Directly or through the back end | Yes |
| GitHub (new in 1.4.0) | OAuth2 | Directly or through the back end | Only through the back end | Yes |
| Apple (new in 1.4.0) | OAuth2 + OIDC | Only through the back end | Only through the back end | Yes |
| Other OpenID Connect providers (new in 1.4.0), such as Keycloak and GitLab | OAuth2 + OIDC | Directly if the provider allows sign-in without a client secret, otherwise through the back end | Directly or through the back end | Yes |
An "OAuth2 + OIDC" provider also returns an ID token, a signed document that says who the user is and which application it was issued to. The library checks it, or reads the user from it. An "OAuth2" provider has its user data fetched from its own API instead.
Whichever provider you use, the result has the same shape: the user ID, name and email, plus the access, refresh and ID tokens.
"Through the back end" is the approach from the previous post: the app signs in through its own ASP.NET Core back end, the provider's tokens stay on the back end, and the app only gets a one-time code to exchange for the user's information. Starting with 1.5.0, desktop apps can sign in this way too. Section 5 has the details.
GitHub and Apple can only go through the back end on mobile because both require a client secret, the password the provider issues to an application, every time a code is exchanged for tokens. An app installed on a phone can be taken apart, and a client secret inside it can be extracted, so the secret has to stay on the back end, which signs in on the app's behalf. Apple adds one more restriction: after sign-in it only redirects to an https URL with a domain name, never to the 127.0.0.1 address a desktop app listens on, so desktop apps have to go through the back end as well.
2️⃣ Any OpenID Connect provider
Keycloak, GitLab, AWS Cognito and Authentik all follow OpenID Connect, and they mostly differ only in their endpoint URLs. Writing a class for each one is not worth it. So 1.4.0 added a generic OidcOAuth2Options, which reads the endpoints from the provider's discovery document (the configuration that OpenID Connect places at /.well-known/openid-configuration):
var keycloak = await OidcOAuth2Options.FromDiscoveryAsync("https://sso.example.com/realms/example");
keycloak.ProviderName = "Keycloak";
keycloak.ClientId = "your-client-id";
keycloak.ClientSecret = "your-client-secret";
keycloak.RedirectUri = "https://localhost:7032/auth/callback";
builder.Services.AddOAuth2Client("Keycloak", keycloak);
Once you have the options, they work like any other provider, and the controller from the previous post does not change. A few design considerations:
- Discovery is read once, at startup. Reading the document is asynchronous, so it is a separate factory method, and the options themselves stay synchronous. That way the configuration is checked when the client is created, instead of failing the first time a user clicks sign in.
-
ProviderNamehas no default. Users are identified by provider name plus user ID, and two providers can issue the same ID to different people. With a default name, an application that adds a second provider and forgets to name it would treat users from both as the same person. - The discovery document is checked when it is read: the issuer must equal the URL passed in, the endpoints must be https, and if the document lists supported PKCE methods,
S256must be among them. - A provider without a userinfo endpoint still works. The user is read from the ID token instead.
Keycloak 26.4 and GitLab.com have both been signed in to with real accounts. For Google and Okta, the users returned through the generic options are the same as through their dedicated options.
When a website connects to several providers, watch out for mix-up attacks: a malicious or compromised provider steers the user to sign in at another provider, then tries to get the authorization code from that sign-in. What stops it is the client secret and PKCE the other provider requires when exchanging the code, so the code is useless in the attacker's hands. So, where the provider allows it, give every website client a client secret, keep PKCE on (the default), and only connect to providers you trust.
3️⃣ Sign in with Apple
Apple is also an OpenID Connect provider, but its client secret is not a fixed string. It is a JWT signed with the private key file (.p8) that Apple gives you. The library signs it for you and re-signs it before it expires, so you only hand it the private key:
builder.Services.AddOAuth2Client("Apple", new AppleOAuth2Options
{
ClientId = "com.example.web", // Services ID
TeamId = "your-team-id",
KeyId = "your-key-id",
PrivateKey = File.ReadAllText(keyPath), // contents of the .p8 file; keep it out of source control
RedirectUri = "https://www.example.com/auth/callback"
});
A few things to keep in mind:
- The callback URL must be https with a domain name. During development, use a public URL such as a tunnel.
- Apple returns to the callback URL with a form POST, so the callback endpoint has to accept both GET and POST.
- The user's name is only given once, the first time the user authorizes your app, so store it then.
- Desktop and mobile apps have to sign in through the back end.
How to write the callback endpoint and what to register in Apple's developer portal are covered in the repo's Sign in with Apple document.
4️⃣ GitHub
GitHub user sign-in is OAuth2 only, without OpenID Connect, so it has its own GitHubOAuth2Options. It works with both GitHub Apps and OAuth Apps.
-
UserIdis the numeric account ID. A user's login changes when they rename their account, and the old name can even be registered by someone else, but the numeric ID never changes. - If the user has no public email, the library looks up their primary, verified email. If there is none, the email is null and sign-in still succeeds.
- When GitHub exchanges a code for tokens, some errors come back with HTTP 200. The library treats these as failures and includes GitHub's error code, rather than just reporting that there was no access token.
GitHub requires the client secret on every exchange, so a desktop app that signs in directly has to carry the secret inside the app. With a back end, signing in through it avoids that. A .NET MAUI app can only sign in through the back end.
5️⃣ With a back end, the back end signs in
An app without its own back end signs in directly and uses the result itself. An app with a back end is different: the back end needs to know who signed in, so it can map them to its own account and issue a session.
The obvious approach is for the front end to sign in to the provider and hand the access token to the back end, which calls the provider's userinfo endpoint with it. That is not safe enough. Every other application the user has signed in to also holds a valid token for this user. If one of those applications sends that token to your back end, the userinfo endpoint returns the same user, and the application can sign in to your back end as that user. This is called token substitution.
In 1.4.0, GetUserInfoAsync(accessToken) dealt with this: it first asked the provider who the token was issued to, and returned the user only if it was your own client ID. 1.5.0 removed it and replaced it with one rule: when there is a back end, the back end always does the sign-in, whatever the provider, OpenID Connect providers included.
| Front end | How it signs in |
|---|---|
| Web | The back end runs the web sign-in and gives the browser a cookie session |
| .NET MAUI on Android, iOS and Mac Catalyst | Through the back end with WebAuthenticator
|
| Desktop and console apps, and .NET MAUI on Windows | Through the back end with LoopbackRelayClient, new in 1.5.0 |
This way the back end confirms the user with the provider itself and does not have to trust anything the front end sends. The provider's tokens and the client secret also stay on the back end.
The relay works roughly like this:
- The app generates a PKCE code verifier and opens the back end's sign-in URL in the system browser, passing its own callback URL and the code challenge.
- The back end redirects the browser to the provider's authorization URL using its own web client, so nothing extra has to be registered with the provider for the app.
- After the user signs in, the provider redirects back to the back end, which exchanges the code for tokens and the user's information.
- The back end stores the user's information under a one-time code and redirects to the app's callback URL.
- The app sends the code and the verifier to the back end and gets the user back. Even if another program intercepts the code, it is useless without the verifier.
In a desktop app:
var client = new LoopbackRelayClient("http://127.0.0.1:0/callback");
RelaySignInResult result = await client.SignInAsync((redirectUri, codeChallenge) => new Uri(
$"https://api.example.com/auth/app/GitHub?redirect_uri={Uri.EscapeDataString(redirectUri.AbsoluteUri)}&code_challenge={codeChallenge}"));
if (result.IsSuccess)
{
// Send result.Code and result.CodeVerifier to the back end, which issues its own session.
}
On the back end, register the loopback callback URL without a port, and the desktop app can listen on any free port each time:
builder.Services.AddOAuth2AppRelay(options =>
{
options.AppRedirectUris.Add("com.example.app:/relay"); // mobile app
options.AppRedirectUris.Add("http://127.0.0.1/callback"); // desktop app, any port
});
- Only
127.0.0.1and[::1]are accepted, notlocalhost, becauselocalhostcan resolve to another address. - Any web page in the browser can send requests to a loopback address, so
LoopbackRelayClientadds astateto the callback URL and only accepts a redirect that carries it. - Other programs on the machine can also listen on loopback ports. If your app can always use the same port, register it with that port.
- The URL that starts sign-in and the endpoint that redeems the code are a contract between your app and your own back end. The library does not prescribe their form.
GitHub and Facebook do not issue ID tokens, so an app with a back end used to have no option but to send the access token from the front end. Both have now been signed in to with real accounts through the back-end relay, and the console sample runs exactly this flow with --back-end.
6️⃣ Before you upgrade
1.4.0 and 1.5.0 have three breaking changes between them. The two in 1.4.0 are both for security, and they affect apps that use Google, Auth0, Okta or Microsoft Entra ID.
The ID token returned by sign-in is now checked. It must be issued to this client (its audience includes the client ID), and its subject must match the user's information. For Google and Auth0, the issuer is checked as well. These are the checks the OpenID Connect Core specification requires. What gets blocked is a token issued to another client, or one whose user does not match, both of which used to pass. As long as ClientId is set correctly, your app does not need to change. After the checks were added, all four providers were signed in to again with real accounts, and none were wrongly rejected.
Unverified emails are no longer returned. When the provider marks email_verified as false, UserInfo.Email is null. If an app maps sign-ins to existing accounts by email, someone could take over an account with an email they never verified, and this change is there to stop that. Identify users by provider name plus UserId instead.
1.5.0 removes access token verification. GetUserInfoAsync(accessToken) and AcceptedClientIds are gone, and code that uses them will no longer compile. To migrate, move sign-in to the back end, as described in section 5.
✅ Wrapping up
Install or upgrade the core package:
dotnet add package Polhem.OAuth2
The "Supported accounts" table in the README links to a document for each provider, covering what to register with the provider and the results of real sign-in tests.
The trade-offs behind generic OpenID Connect, Apple, and back-end sign-in are recorded in the repo as ADR-008, ADR-009 and ADR-011. An ADR (Architecture Decision Record) is a document that records a design decision and the reasons for it.
The scope of the library is the same as in the previous post: it handles signing in and getting the user's information and tokens, and does not manage accounts or permissions after sign-in. If you only have a website, ASP.NET Core's built-in authentication is enough, and you may not need to switch. The library fits best when you have desktop, mobile and web apps at the same time and want to connect Apple, GitHub or a self-hosted Keycloak the same way in all of them. Feedback, issues and pull requests are welcome.
Further reading
- OpenID Connect Core 1.0: on checking the ID token's audience, issuer and subject
- RFC 9700, OAuth 2.0 Security Best Current Practice: on mix-up attacks and PKCE
📘 Original article on HackMD, in Traditional Chinese:
👉 https://hackmd.io/@jeff377/polhem-oauth2-oidc
📢 You are welcome to republish this, please credit the source.
📬 Follow for more engineering notes:
Facebook | HackMD | GitHub | NuGet
Top comments (0)