Skip to content

Commit

Permalink
Improved config options for OIDC (#9)
Browse files Browse the repository at this point in the history
Added many new configuration options, including claim configuration and client_secret/confidential client support. Also enables user linking & creates person entries upon first sign in.
  • Loading branch information
christiaangoossens authored Dec 28, 2024
1 parent ca83e86 commit db4c6bc
Show file tree
Hide file tree
Showing 18 changed files with 623 additions and 175 deletions.
4 changes: 3 additions & 1 deletion .pylintrc
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,9 @@ disable=raw-checker-failed,
use-symbolic-message-instead,
use-implicit-booleaness-not-comparison-to-string,
use-implicit-booleaness-not-comparison-to-zero,
relative-beyond-top-level
relative-beyond-top-level,
# Allow keeping TODOs in the code
fixme

# Enable the message, report, category or checker with the given id(s). You can
# either give multiple identifier separated by comma (,) or put this option
Expand Down
58 changes: 49 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
# OIDC Auth for Home Assistant

> [!CAUTION]
> This is an alpha release. I give no guarantees about code quality, error handling or security at this stage. Please treat this repo as a proof of concept for now and only use it on development HA installs.
> This is an alpha release. I give no guarantees about code quality, error handling or security at this stage. Use at your own risk.
Provides an OIDC implementation for Home Assistant.
Provides an OpenID Connect (OIDC) implementation for Home Assistant through a custom component/integration. Through this integration, you can create an SSO (single-sign-on) environment within your self-hosted application stack / homelab.

### Background
If you would like to read the background/open letter that lead to this component, please see https://community.home-assistant.io/t/open-letter-for-improving-home-assistants-authentication-system-oidc-sso/494223. It is currently one of the most upvoted feature requests for Home Assistant.
Expand All @@ -28,11 +28,13 @@ Register your client with your OIDC Provider (e.g. Authentik/Authelia) as a publ
For example:
```yaml
auth_oidc:
client_id: "someValueForTheClientId"
discovery_url: "https://example.com/application/o/application/.well-known/openid-configuration"
client_id: "someValueForTheClientId"
discovery_url: "https://example.com/application/o/application/.well-known/openid-configuration"
```

Afterwards, restart Home Assistant.
Afterwards, restart Home Assistant.

You can find all possible configuration options below.

### Login
You should now be able to see a second option on your login screen ("OpenID Connect (SSO)"). It provides you with a single input field.
Expand All @@ -46,6 +48,44 @@ So, for example, you may start at http://homeassistant.local:8123/auth/oidc/welc
> [!TIP]
> You can use a different device to login instead. Open the `/auth/oidc/welcome` link on device A and then type the obtained code into the normal HA login on device B (can also be the mobile app) to login.

> [!TIP]
> For a seamless user experience, configure a new domain on your proxy to redirect to the `/auth/oidc/welcome` path or configure that path on your homelab dashboard or in Authentik. Users will then always start on the OIDC welcome page, which will allow them to visit the dashboard if they are already logged in.


With the default configuration, [a person entry](https://www.home-assistant.io/integrations/person/) will be created for every new OIDC user logging in. New OIDC users will get their own fresh user, linked to their persistent ID (subject) at the OpenID Connect provider. You may change your name, username or email at the provider and still have the same Home Assistant user profile.

### Configuration Options

| Option | Type | Required | Default | Description |
|-----------------------------|----------|----------|----------------------|---------------------------------------------------------------------------------------------------------|
| `client_id` | `string` | Yes | | The Client ID as registered with your OpenID Connect provider. |
| `client_secret` | `string` | No | | The Client Secret for enabling confidential client mode. |
| `discovery_url` | `string` | Yes | | The OIDC well-known configuration URL. |
| `display_name` | `string` | No | `"OpenID Connect (SSO)"` | The name to display on the login screen, both for the Home Assistant screen and the OIDC welcome screen. |
| `id_token_signing_alg` | `string` | No | `RS256` | The signing algorithm that is used for your id_tokens.
| `features.automatic_user_linking` | `boolean`| No | `false` | Automatically links users to existing Home Assistant users based on the OIDC username claim. Disabled by default for security. When disabled, OIDC users will get their own new user profile upon first login. |
| `features.automatic_person_creation` | `boolean` | No | `true` | Automatically creates a person entry for new user profiles created by this integration. Recommended if you would like to assign presence detection to OIDC users. |
| `features.disable_rfc7636` | `boolean`| No | `false` | Disables PKCE (RFC 7636) for OIDC providers that don't support it. You should not need this with most providers. |
| `claims.display_name` | `string` | No | `name` | The claim to use to obtain the display name.
| `claims.username` | `string` | No | `preferred_username` | The claim to use to obtain the username.
| `claims.groups` | `string` | No | `groups` | The claim to use to obtain the user's group(s). |

#### Example: Migrating from HA username/password users to OIDC users
If you already have users created within Home Assistant and would like to re-use the current user profile for your OIDC login, you can (temporarily) enable `features.automatic_user_linking`, with the following config (example):

```yaml
auth_oidc:
client_id: "someValueForTheClientId"
discovery_url: "https://example.com/application/o/application/.well-known/openid-configuration"
features:
automatic_user_linking: true
```

Upon login, OIDC users will then automatically be linked to the HA user with the same username.

> [!IMPORTANT]
> It's recommended to only enable this temporarily as it may pose a security risk. Any OIDC user with a username corresponding to a user in Home Assistant can get access to that user, and it's existing rights (admin), even if MFA is currently enabled for that account. After you have migrated your users (and linked OIDC to all existing accounts) you can disable the feature and keep using the linked users.

## Development
This project uses the Rye package manager for development. You can find installation instructions here: https://rye.astral.sh/guide/installation/.
Start by installing the dependencies using `rye sync` and then point your editor towards the environment created in the `.venv` directory.
Expand All @@ -61,10 +101,10 @@ Currently, this is a pre-alpha, so I welcome issues but I cannot guarantee I can
- [X] Implement a final link back to the main page from the finish page
- [X] Improve welcome screen UI, should render a simple centered Tailwind UI instructing users that you should login externally to obtain a code.
- [X] Improve finish screen UI, showing the code clearly with instructions to paste it into Home Assistant.
- [ ] Implement error handling on top of this proof of concept (discovery, JWKS, OIDC)
- [ ] Make id_token claim used for the group (admin/user) configurable
- [ ] Make id_token claim used for the username configurable
- [ ] Make id_token claim used for the name configurable
- [X] Implement error handling on top of this proof of concept (discovery, JWKS, OIDC)
- [X] Make id_token claim used for the group (admin/user) configurable
- [X] Make id_token claim used for the username configurable
- [X] Make id_token claim used for the name configurable
- [ ] Add instructions on how to deploy this with Authentik & Authelia
- [X] Configure Github Actions to automatically lint and build the package
- [ ] Configure Dependabot for automatic updates
Expand Down
65 changes: 38 additions & 27 deletions custom_components/auth_oidc/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,25 @@
import logging
from typing import OrderedDict

import voluptuous as vol
from homeassistant.core import HomeAssistant

# Import and re-export config schema explictly
# pylint: disable=useless-import-alias
from .config import (
CONFIG_SCHEMA as CONFIG_SCHEMA,
DOMAIN,
DEFAULT_TITLE,
CLIENT_ID,
CLIENT_SECRET,
DISCOVERY_URL,
DISPLAY_NAME,
ID_TOKEN_SIGNING_ALGORITHM,
FEATURES,
CLAIMS,
)

# pylint: enable=useless-import-alias

from .endpoints.welcome import OIDCWelcomeView
from .endpoints.redirect import OIDCRedirectView
from .endpoints.finish import OIDCFinishView
Expand All @@ -14,52 +30,47 @@
from .oidc_client import OIDCClient
from .provider import OpenIDAuthProvider

DOMAIN = "auth_oidc"
_LOGGER = logging.getLogger(__name__)

CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
vol.Required("client_id"): vol.Coerce(str),
vol.Optional("client_secret"): vol.Coerce(str),
vol.Required("discovery_url"): vol.Coerce(str),
}
)
},
extra=vol.ALLOW_EXTRA,
)


async def async_setup(hass: HomeAssistant, config):
"""Add the OIDC Auth Provider to the providers in Home Assistant"""
my_config = config[DOMAIN]

providers = OrderedDict()

# Use private APIs until there is a real auth platform
# pylint: disable=protected-access
provider = OpenIDAuthProvider(
hass,
hass.auth._store,
config[DOMAIN],
)
provider = OpenIDAuthProvider(hass, hass.auth._store, my_config)

providers[(provider.type, provider.id)] = provider
providers.update(hass.auth._providers)
hass.auth._providers = providers
# pylint: enable=protected-access

_LOGGER.debug("Added OIDC provider for Home Assistant")
_LOGGER.info("Registered OIDC provider")

# Define some fields
discovery_url: str = config[DOMAIN]["discovery_url"]
client_id: str = config[DOMAIN]["client_id"]
scope: str = "openid profile email"
# We only use openid & profile, never email
scope = "openid profile"

oidc_client = oidc_client = OIDCClient(discovery_url, client_id, scope)
oidc_client = oidc_client = OIDCClient(
discovery_url=my_config.get(DISCOVERY_URL),
client_id=my_config.get(CLIENT_ID),
scope=scope,
client_secret=my_config.get(CLIENT_SECRET),
id_token_signing_alg=my_config.get(ID_TOKEN_SIGNING_ALGORITHM),
features=my_config.get(FEATURES, {}),
claims=my_config.get(CLAIMS, {}),
)

hass.http.register_view(OIDCWelcomeView())
# Register the views
name = config[DOMAIN].get(DISPLAY_NAME, DEFAULT_TITLE)

hass.http.register_view(OIDCWelcomeView(name))
hass.http.register_view(OIDCRedirectView(oidc_client))
hass.http.register_view(OIDCCallbackView(oidc_client, provider))
hass.http.register_view(OIDCFinishView())

_LOGGER.info("Registered OIDC views")

return True
72 changes: 72 additions & 0 deletions custom_components/auth_oidc/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
"""Config schema and constants."""

import voluptuous as vol

CLIENT_ID = "client_id"
CLIENT_SECRET = "client_secret"
DISCOVERY_URL = "discovery_url"
DISPLAY_NAME = "display_name"
ID_TOKEN_SIGNING_ALGORITHM = "id_token_signing_alg"
FEATURES = "features"
FEATURES_AUTOMATIC_USER_LINKING = "automatic_user_linking"
FEATURES_AUTOMATIC_PERSON_CREATION = "automatic_person_creation"
FEATURES_DISABLE_PKCE = "disable_rfc7636"
CLAIMS = "claims"
CLAIMS_DISPLAY_NAME = "display_name"
CLAIMS_USERNAME = "username"
CLAIMS_GROUPS = "groups"

DEFAULT_TITLE = "OpenID Connect (SSO)"

DOMAIN = "auth_oidc"
CONFIG_SCHEMA = vol.Schema(
{
DOMAIN: vol.Schema(
{
# Required client ID as registered with the OIDC provider
vol.Required(CLIENT_ID): vol.Coerce(str),
# Optional Client Secret to enable confidential client mode
vol.Optional(CLIENT_SECRET): vol.Coerce(str),
# Which OIDC well-known URL should we use?
vol.Required(DISCOVERY_URL): vol.Coerce(str),
# Which name should be shown on the login screens?
vol.Optional(DISPLAY_NAME): vol.Coerce(str),
# Should we enforce a specific signing algorithm on the id tokens?
# Defaults to RS256/RSA-pubkey
vol.Optional(ID_TOKEN_SIGNING_ALGORITHM): vol.Coerce(str),
# Which features should be enabled/disabled?
# Optional, defaults to sane/secure defaults
vol.Optional(FEATURES): vol.Schema(
{
# Automatically links users to the HA user based on OIDC username claim
# See provider.py for explanation
vol.Optional(FEATURES_AUTOMATIC_USER_LINKING): vol.Coerce(bool),
# Automatically creates a person entry for your new OIDC user
# See provider.py for explanation
vol.Optional(FEATURES_AUTOMATIC_PERSON_CREATION): vol.Coerce(
bool
),
# Feature flag to disable PKCE to support OIDC servers that do not
# allow additional parameters and don't support RFC 7636
vol.Optional(FEATURES_DISABLE_PKCE): vol.Coerce(bool),
}
),
# Determine which specific claims will be used from the id_token
# Optional, defaults to most common claims
vol.Optional(CLAIMS): vol.Schema(
{
# Which claim should we use to obtain the display name from OIDC?
vol.Optional(CLAIMS_DISPLAY_NAME): vol.Coerce(str),
# Which claim should we use to obtain the username from OIDC?
vol.Optional(CLAIMS_USERNAME): vol.Coerce(str),
# Which claim should we use to obtain the group(s) from OIDC?
vol.Optional(CLAIMS_GROUPS): vol.Coerce(str),
}
),
}
)
},
# Any extra fields should not go into our config right now
# You may set them for upgrading etc
extra=vol.REMOVE_EXTRA,
)
5 changes: 4 additions & 1 deletion custom_components/auth_oidc/endpoints/welcome.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ class OIDCWelcomeView(HomeAssistantView):
url = PATH
name = "auth:oidc:welcome"

def __init__(self, name: str) -> None:
self.name = name

async def get(self, _: web.Request) -> web.Response:
"""Receive response."""
view_html = await get_view("welcome")
view_html = await get_view("welcome", {"name": self.name})
return web.Response(text=view_html, content_type="text/html")
2 changes: 1 addition & 1 deletion custom_components/auth_oidc/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,5 @@
"aiofiles>=24.1.0",
"jinja2>=3.1.4"
],
"version": "0.3.0"
"version": "0.4.0"
}
Loading

0 comments on commit db4c6bc

Please sign in to comment.