feat: support public (secretless) native OIDC clients for Google and Microsoft (#8653)

This commit is contained in:
Dmitrii authored and GitHub committed 2026-10-10 02:02:49 +00:00
1 parent 10fa95e2ed
commit 0601d2bcba
8 files changed
+234 -8

No files matched your search

+1
View File
@@ -57,6 +57,7 @@ load_secrets() {
"OIDC_CONFIGURATION_URL"
"OIDC_CLIENT_ID"
"OIDC_NATIVE_CLIENT_ID"
"OIDC_CLIENT_SECRET"
)
@@ -29,7 +29,7 @@ If a user previously accessed Mealie via credentials and you want to no longer a
Because Mealie links an OIDC login to an existing account by matching on a claim (`OIDC_USER_CLAIM`, `email` by default), an IdP that lets a user self-assert an arbitrary, unverified email address would allow that user to log into someone else's Mealie account simply by claiming their email. To prevent this, Mealie requires the `email_verified` claim to be present and `true` before authenticating.
Most identity providers (Authentik, Authelia, Keycloak, Google, Entra ID, ...) emit this claim as part of the `email` scope, and require no changes. If a login is rejected for this reason, the following is written to the server logs:
Most identity providers (Authentik, Authelia, Keycloak, Google, Entra ID, ...) emit this claim as part of the `email` scope, and require no changes. Microsoft Entra ID does not emit it for personal Microsoft accounts. If a login is rejected for this reason, the following is written to the server logs:
[OIDC] email_verified claim is missing or false; refusing to authenticate
@@ -109,8 +109,25 @@ These endpoints are available automatically whenever OIDC is configured — ther
The native flow reuses your existing **confidential** OIDC client and `OIDC_CLIENT_SECRET` — the same setup as the web flow. The only additional step is in your identity provider: **register the native client's redirect URI** (a custom scheme such as `app-scheme://oauth/callback`, supplied by the app) on the same OIDC client. The provider validates this redirect URI, so it is the access control for native logins — no Mealie-side configuration is required.
!!! note
Providers that require a separate **public** (secret-less) native client — notably Google and Microsoft Entra — are not yet supported by this flow. Self-hosted providers that let you add a redirect URI to the existing confidential client (Pocket ID, Authentik, Authelia, Keycloak, …) work today.
### Public native clients (Google, Microsoft)
Some providers do not allow custom-scheme or loopback redirect URIs on a confidential web client, and instead require a separate native application registration that has no client secret and relies on PKCE. For those providers, register a second client for the mobile app, set `OIDC_NATIVE_CLIENT_ID` to its client ID, and set `OIDC_NATIVE_CONFIDENTIAL=false`. Mealie then omits the client secret when exchanging the code for native logins, while the web login keeps using `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET`. Self-hosted providers such as Authentik and Pocket ID can keep using the single web client, so these settings are not needed there.
**Google**
- Keep your existing Google OAuth client of type "Web application" as `OIDC_CLIENT_ID` and `OIDC_CLIENT_SECRET` for the web login.
- Create a second OAuth client of type "iOS" using the mobile app's bundle ID. It has no client secret. Set its client ID as `OIDC_NATIVE_CLIENT_ID` and set `OIDC_NATIVE_CONFIDENTIAL=false`.
- Google iOS clients have no redirect URI field. Google only accepts custom-scheme redirect URIs that contain a period, such as the app's bundle ID (`com.example.app:/oauth/callback`), so the app must use a redirect URI in that form for Google.
- Set `OIDC_CONFIGURATION_URL=https://accounts.google.com/.well-known/openid-configuration`.
**Microsoft Entra ID**
- Use a single app registration for both web and native logins: set the same Application (client) ID as both `OIDC_CLIENT_ID` and `OIDC_NATIVE_CLIENT_ID`, the client secret value as `OIDC_CLIENT_SECRET`, and `OIDC_NATIVE_CONFIDENTIAL=false`.
- Under Authentication, add the "Web" platform with your Mealie login redirect URI (`https://mealie.example.com/login`), and add the "Mobile and desktop applications" platform with the redirect URI supplied by the app as a custom redirect URI.
- Under Authentication, set "Allow public client flows" to Yes.
- Under Token configuration, add the `email` optional claim to the ID token (accept the prompt to turn on the Microsoft Graph email permission).
- Use the discovery URL for your tenant: `https://login.microsoftonline.com/<tenant>/v2.0/.well-known/openid-configuration`, where `<tenant>` is your Directory (tenant) ID, or `consumers` for personal Microsoft accounts.
- Personal Microsoft accounts do not include the `email_verified` claim, so logins are rejected until `OIDC_REQUIRES_EMAIL_VERIFICATION=false` is set. See [Email Verification](#email-verification).
## Examples
@@ -119,6 +119,8 @@ For usage, see [Usage - OpenID Connect](../authentication/oidc-v2.md)
| OIDC_SCOPES_OVERRIDE | None | Advanced configuration used to override the scopes requested from the IdP. **Most users won't need to change this**. At a minimum, 'openid profile email' are required. |
| OIDC_TLS_CACERTFILE | None | File path to Certificate Authority used to verify server certificate (e.g. `/path/to/ca.crt`) |
| OIDC_CLIENT_TIMEOUT | default | Configures the timeout value of the httpx client used for OIDC communications. If set to the string `default`, does not configure the value (uses the library's default of 5.0s). If set to the string `None`, disables the timeout entirely. If set to a numeric value, uses that as the timeout. |
| OIDC_NATIVE_CLIENT_ID<super>[&dagger;][secrets]</super> | None | Client ID used by the native (mobile/desktop) OIDC endpoints. Falls back to `OIDC_CLIENT_ID` when unset. Set this when your provider requires a separate native client, for example Google or Microsoft. |
| OIDC_NATIVE_CONFIDENTIAL | True | When `False`, the native client is treated as a public client: the client secret is omitted from the token exchange and PKCE alone is used. Only takes effect when `OIDC_NATIVE_CLIENT_ID` is set. The web login client is not affected. |
### AI
+8
View File
@@ -409,6 +409,14 @@ class AppSettings(AppLoggingSettings):
OIDC_TLS_CACERTFILE: str | None = None
OIDC_CLIENT_TIMEOUT: float | Literal["None", "default"] = "default"
OIDC_NATIVE_CLIENT_ID: str | None = None
"""Client ID used by the native (mobile/desktop) OIDC endpoints. Falls back to OIDC_CLIENT_ID when unset."""
OIDC_NATIVE_CONFIDENTIAL: bool = True
"""When false, the native client is treated as a public client: the client secret is omitted from the token
exchange and PKCE alone is relied on. Required for Google and Microsoft, which do not allow custom-scheme
redirects on confidential clients."""
@property
def OIDC_REQUIRES_GROUP_CLAIM(self) -> bool:
return self.OIDC_USER_GROUP is not None or self.OIDC_ADMIN_GROUP is not None
+35 -2
View File
@@ -29,6 +29,38 @@ logger = root_logger.get_logger("auth")
settings = get_app_settings()
def _register_native_oidc_client(oauth_registry, client_args: dict[str, Any]) -> None:
"""Register the "oidc_native" client used by the native endpoints.
It is the web client unless OIDC_NATIVE_CLIENT_ID is set. The secretless (public) mode only applies
when that id is set and OIDC_NATIVE_CONFIDENTIAL is false; the web client is never affected.
"""
client_id = settings.OIDC_NATIVE_CLIENT_ID or settings.OIDC_CLIENT_ID
client_secret = settings.OIDC_CLIENT_SECRET
native_client_args = client_args
if not settings.OIDC_NATIVE_CONFIDENTIAL:
if settings.OIDC_NATIVE_CLIENT_ID:
client_secret = None
native_client_args = {**client_args, "token_endpoint_auth_method": "none"}
else:
logger.warning(
"[OIDC] OIDC_NATIVE_CONFIDENTIAL=false has no effect without OIDC_NATIVE_CLIENT_ID; "
"the native endpoints will use the confidential client"
)
oauth_registry.register(
"oidc_native",
client_id=client_id,
client_secret=client_secret,
server_metadata_url=settings.OIDC_CONFIGURATION_URL,
client_kwargs=native_client_args,
code_challenge_method="S256",
)
oauth = None
if settings.OIDC_READY:
from authlib.integrations.starlette_client import OAuth
@@ -54,6 +86,7 @@ if settings.OIDC_READY:
client_kwargs=client_args,
code_challenge_method="S256",
)
_register_native_oidc_client(oauth, client_args)
SESSION_COOKIE_NAME = "mealie.access_token"
@@ -232,7 +265,7 @@ async def oauth_native_config():
detail="OIDC is not configured",
)
client = oauth.create_client("oidc")
client = oauth.create_client("oidc_native")
metadata = await client.load_server_metadata()
return OIDCNativeConfig(
authorization_endpoint=metadata["authorization_endpoint"],
@@ -262,7 +295,7 @@ async def oauth_native_token(
from authlib.integrations.starlette_client import OAuthError
client = oauth.create_client("oidc")
client = oauth.create_client("oidc_native")
try:
token = await client.fetch_access_token(
code=data.code,
@@ -18,10 +18,16 @@ native_token_request = {
class OAuthClientMock:
"""Stands in for the authlib OIDC client, failing the way a rejected code or id_token does"""
client_id = "native-client-id"
client_kwargs = {"scope": "openid email profile"}
def __init__(self, token_error: Exception | None = None, id_token_error: Exception | None = None):
self.token_error = token_error
self.id_token_error = id_token_error
async def load_server_metadata(self) -> dict:
return {"authorization_endpoint": "https://idp.example/authorize"}
async def fetch_access_token(self, **kwargs) -> dict:
if self.token_error:
raise self.token_error
@@ -36,17 +42,21 @@ class OAuthClientMock:
class OAuthMock:
def __init__(self, client: OAuthClientMock):
self.client = client
self.requested_names: list[str] = []
def create_client(self, name: str) -> OAuthClientMock:
self.requested_names.append(name)
return self.client
def setup_oidc(
monkeypatch: MonkeyPatch, token_error: Exception | None = None, id_token_error: Exception | None = None
) -> None:
) -> OAuthMock:
monkeypatch.setattr(type(auth_routes.settings), "OIDC_READY", property(lambda self: True))
client = OAuthClientMock(token_error=token_error, id_token_error=id_token_error)
monkeypatch.setattr(auth_routes, "oauth", OAuthMock(client), raising=False)
oauth_mock = OAuthMock(client)
monkeypatch.setattr(auth_routes, "oauth", oauth_mock, raising=False)
return oauth_mock
def test_native_config_returns_404_when_oidc_not_configured(api_client: TestClient):
@@ -64,11 +74,27 @@ def test_native_token_returns_404_when_oidc_not_configured(api_client: TestClien
def test_native_token_returns_401_when_code_is_rejected(api_client: TestClient, monkeypatch: MonkeyPatch):
setup_oidc(monkeypatch, token_error=OAuthError("invalid_grant", "authorization code is invalid or expired"))
oauth_mock = setup_oidc(
monkeypatch, token_error=OAuthError("invalid_grant", "authorization code is invalid or expired")
)
response = api_client.post(api_routes.auth_oauth_native_token, json=native_token_request)
assert response.status_code == 401
assert oauth_mock.requested_names == ["oidc_native"]
def test_native_config_returns_native_client_parameters(api_client: TestClient, monkeypatch: MonkeyPatch):
oauth_mock = setup_oidc(monkeypatch)
response = api_client.get(api_routes.auth_oauth_native_config)
assert response.status_code == 200
body = response.json()
assert body["client_id"] == OAuthClientMock.client_id
assert body["scope"] == OAuthClientMock.client_kwargs["scope"]
assert body["authorization_endpoint"] == "https://idp.example/authorize"
assert oauth_mock.requested_names == ["oidc_native"]
def test_native_token_returns_500_on_unexpected_errors(monkeypatch: MonkeyPatch):
+44
View File
@@ -395,6 +395,50 @@ def test_oidc_settings_validation(data: OIDCValidationCase, monkeypatch: pytest.
assert app_settings.OIDC_READY is data.is_valid
VALID_OIDC_ENV = {
"OIDC_AUTH_ENABLED": "true",
"OIDC_CLIENT_ID": "id",
"OIDC_CLIENT_SECRET": "secret",
"OIDC_CONFIGURATION_URL": "url",
}
native_oidc_cases = [
pytest.param({}, None, True, False, id="defaults"),
pytest.param({"OIDC_NATIVE_CLIENT_ID": "native-app"}, "native-app", True, False, id="native id set"),
pytest.param({"OIDC_NATIVE_CONFIDENTIAL": "false"}, None, False, False, id="public native client"),
pytest.param(
{**VALID_OIDC_ENV, "OIDC_NATIVE_CONFIDENTIAL": "false"},
None,
False,
True,
id="native settings optional for OIDC_READY",
),
]
@pytest.mark.parametrize(("env", "native_id", "confidential", "oidc_ready"), native_oidc_cases)
def test_oidc_native_settings(
env: dict[str, str],
native_id: str | None,
confidential: bool,
oidc_ready: bool,
monkeypatch: pytest.MonkeyPatch,
):
for name in ("OIDC_AUTH_ENABLED", "OIDC_CLIENT_ID", "OIDC_CLIENT_SECRET", "OIDC_CONFIGURATION_URL"):
monkeypatch.delenv(name, raising=False)
monkeypatch.delenv("OIDC_NATIVE_CLIENT_ID", raising=False)
monkeypatch.delenv("OIDC_NATIVE_CONFIDENTIAL", raising=False)
for name, value in env.items():
monkeypatch.setenv(name, value)
get_app_settings.cache_clear()
app_settings = get_app_settings()
assert app_settings.OIDC_NATIVE_CLIENT_ID == native_id
assert app_settings.OIDC_NATIVE_CONFIDENTIAL is confidential
assert app_settings.OIDC_READY is oidc_ready
def test_sensitive_settings_mask(monkeypatch: pytest.MonkeyPatch):
sensitive_settings = [
"LDAP_QUERY_PASSWORD",
@@ -0,0 +1,95 @@
import logging
from authlib.integrations.starlette_client import OAuth
from pytest import LogCaptureFixture, MonkeyPatch
from mealie.routes.auth import auth as auth_routes
WEB_CLIENT_ID = "web-client-id"
WEB_CLIENT_SECRET = "web-client-secret"
def register_native_client(monkeypatch: MonkeyPatch, native_id: str | None, confidential: bool):
monkeypatch.setattr(auth_routes.settings, "OIDC_CLIENT_ID", WEB_CLIENT_ID)
monkeypatch.setattr(auth_routes.settings, "OIDC_CLIENT_SECRET", WEB_CLIENT_SECRET)
monkeypatch.setattr(auth_routes.settings, "OIDC_NATIVE_CLIENT_ID", native_id)
monkeypatch.setattr(auth_routes.settings, "OIDC_NATIVE_CONFIDENTIAL", confidential)
client_args = {"scope": "openid email profile"}
snapshot = dict(client_args)
oauth = OAuth()
auth_routes._register_native_oidc_client(oauth, client_args)
assert client_args == snapshot, "client_args is shared with the web client and must not be mutated"
return oauth.create_client("oidc_native")
def test_no_native_id_uses_web_client(monkeypatch: MonkeyPatch):
client = register_native_client(monkeypatch, None, True)
assert client.client_id == WEB_CLIENT_ID
assert client.client_secret == WEB_CLIENT_SECRET
assert "token_endpoint_auth_method" not in client.client_kwargs
def test_native_id_confidential_keeps_secret(monkeypatch: MonkeyPatch):
client = register_native_client(monkeypatch, "native-app", True)
assert client.client_id == "native-app"
assert client.client_secret == WEB_CLIENT_SECRET
assert "token_endpoint_auth_method" not in client.client_kwargs
def test_native_id_public_drops_secret(monkeypatch: MonkeyPatch):
client = register_native_client(monkeypatch, "native-app", False)
assert client.client_id == "native-app"
assert client.client_secret is None
assert client.client_kwargs["token_endpoint_auth_method"] == "none"
assert client.client_kwargs["scope"] == "openid email profile"
def test_public_without_native_id_warns_and_stays_confidential(monkeypatch: MonkeyPatch, caplog: LogCaptureFixture):
caplog.set_level(logging.WARNING)
client = register_native_client(monkeypatch, None, False)
assert client.client_id == WEB_CLIENT_ID
assert client.client_secret == WEB_CLIENT_SECRET
assert "token_endpoint_auth_method" not in client.client_kwargs
assert "OIDC_NATIVE_CONFIDENTIAL=false has no effect" in caplog.text
def test_empty_native_id_falls_back_to_web_client(monkeypatch: MonkeyPatch):
client = register_native_client(monkeypatch, "", True)
assert client.client_id == WEB_CLIENT_ID
assert client.client_secret == WEB_CLIENT_SECRET
def test_public_native_client_leaves_web_client_unaffected(monkeypatch: MonkeyPatch):
monkeypatch.setattr(auth_routes.settings, "OIDC_CLIENT_ID", WEB_CLIENT_ID)
monkeypatch.setattr(auth_routes.settings, "OIDC_CLIENT_SECRET", WEB_CLIENT_SECRET)
monkeypatch.setattr(auth_routes.settings, "OIDC_NATIVE_CLIENT_ID", "native-app")
monkeypatch.setattr(auth_routes.settings, "OIDC_NATIVE_CONFIDENTIAL", False)
client_args = {"scope": "openid email profile"}
oauth = OAuth()
oauth.register(
"oidc",
client_id=auth_routes.settings.OIDC_CLIENT_ID,
client_secret=auth_routes.settings.OIDC_CLIENT_SECRET,
server_metadata_url=auth_routes.settings.OIDC_CONFIGURATION_URL,
client_kwargs=client_args,
code_challenge_method="S256",
)
auth_routes._register_native_oidc_client(oauth, client_args)
web = oauth.create_client("oidc")
assert web.client_id == WEB_CLIENT_ID
assert web.client_secret == WEB_CLIENT_SECRET
assert "token_endpoint_auth_method" not in web.client_kwargs
native = oauth.create_client("oidc_native")
assert native.client_id == "native-app"
assert native.client_secret is None
assert native.client_kwargs["token_endpoint_auth_method"] == "none"