authentik.sources.oauth.types.entra_id

EntraID OAuth2 Views

  1"""EntraID OAuth2 Views"""
  2
  3from asyncio import run
  4from dataclasses import asdict
  5from typing import TYPE_CHECKING, Any
  6from urllib.parse import urlsplit
  7
  8from structlog.stdlib import get_logger
  9
 10from authentik.events.utils import sanitize_item
 11from authentik.sources.oauth.clients.oauth2 import UserprofileHeaderAuthClient
 12from authentik.sources.oauth.models import AuthorizationCodeAuthMethod, OAuthSource
 13from authentik.sources.oauth.types.oidc import OpenIDConnectOAuth2Callback
 14from authentik.sources.oauth.types.registry import SourceType, registry
 15from authentik.sources.oauth.views.redirect import OAuthRedirect
 16
 17if TYPE_CHECKING:
 18    from msgraph.generated.models.entity import Entity
 19
 20LOGGER = get_logger()
 21
 22
 23def entity_as_dict(entity: Entity) -> dict:
 24    """Create a dictionary of a model instance, making sure to remove (known) things
 25    we can't JSON serialize"""
 26    return sanitize_item(
 27        asdict(
 28            entity,
 29            # Nested entities carry their own backing store, so filter at every level
 30            dict_factory=lambda items: {k: v for k, v in items if k != "backing_store"},
 31        )
 32    )
 33
 34
 35def get_graph_url(source: OAuthSource, path: str) -> str:
 36    """Use the configured profile's origin for Graph scopes and API requests."""
 37    profile_url = source.profile_url or EntraIDType.profile_url
 38    return urlsplit(profile_url)._replace(path=path, query="", fragment="").geturl()
 39
 40
 41class EntraIDOAuthRedirect(OAuthRedirect):
 42    """Entra ID OAuth2 Redirect"""
 43
 44    def get_additional_parameters(self, source):
 45        return {
 46            "scope": ["openid", get_graph_url(source, "/User.Read")],
 47        }
 48
 49
 50class EntraIDClient(UserprofileHeaderAuthClient):
 51    """Fetch EntraID group information"""
 52
 53    def get_profile_info(self, token):
 54        # The Graph SDK is heavy, only import it when an Entra ID source is used
 55        from httpx import HTTPError
 56        from kiota_abstractions.api_error import APIError
 57
 58        profile_data = super().get_profile_info(token)
 59        group_scope = get_graph_url(self.source, "/GroupMember.Read.All")
 60        scopes = self.source.additional_scopes.removeprefix("*").split()
 61        if profile_data is None or group_scope not in scopes:
 62            return profile_data
 63        try:
 64            profile_data["raw_groups"] = run(self.get_groups(token))
 65        except (APIError, HTTPError) as exc:
 66            LOGGER.warning("Unable to fetch user groups", exc=exc)
 67            return None
 68        return profile_data
 69
 70    async def get_groups(self, token):
 71        """Fetch all memberships and convert Graph entities for property mappings."""
 72        from kiota_abstractions.authentication.anonymous_authentication_provider import (
 73            AnonymousAuthenticationProvider,
 74        )
 75        from kiota_abstractions.base_request_configuration import RequestConfiguration
 76        from kiota_abstractions.headers_collection import HeadersCollection
 77        from kiota_http.kiota_client_factory import KiotaClientFactory
 78        from msgraph.graph_request_adapter import GraphRequestAdapter, options
 79        from msgraph.graph_service_client import GraphServiceClient
 80        from msgraph_core import GraphClientFactory
 81
 82        # RequestConfiguration shares its default headers between instances
 83        config = RequestConfiguration(headers=HeadersCollection())
 84        config.headers.add("Authorization", f"{token['token_type']} {token['access_token']}")
 85        async with GraphClientFactory.create_with_default_middleware(
 86            options=options, client=KiotaClientFactory.get_default_client()
 87        ) as http_client:
 88            adapter = GraphRequestAdapter(AnonymousAuthenticationProvider(), http_client)
 89            adapter.base_url = get_graph_url(self.source, "/v1.0")
 90            client = GraphServiceClient(request_adapter=adapter)
 91            groups = []
 92            request = client.me.member_of
 93            while request:
 94                page = await request.get(config)
 95                groups.extend(page.value or [])
 96                request = (
 97                    client.me.member_of.with_url(page.odata_next_link)
 98                    if page.odata_next_link
 99                    else None
100                )
101        return {"value": [entity_as_dict(group) for group in groups]}
102
103
104class EntraIDOAuthCallback(OpenIDConnectOAuth2Callback):
105    """EntraID OAuth2 Callback"""
106
107    client_class = EntraIDClient
108
109    def get_user_id(self, info: dict[str, str]) -> str:
110        # Default try to get `id` for the Graph API endpoint
111        # fallback to OpenID logic in case the profile URL was changed
112        return info.get("id", super().get_user_id(info))
113
114
115@registry.register()
116class EntraIDType(SourceType):
117    """Entra ID Type definition"""
118
119    callback_view = EntraIDOAuthCallback
120    redirect_view = EntraIDOAuthRedirect
121    verbose_name = "Entra ID"
122    name = "entraid"
123
124    urls_customizable = True
125
126    authorization_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
127    access_token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"  # nosec
128    profile_url = "https://graph.microsoft.com/v1.0/me"
129    oidc_jwks_url = "https://login.microsoftonline.com/common/discovery/keys"
130
131    authorization_code_auth_method = AuthorizationCodeAuthMethod.POST_BODY
132
133    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
134        mail = info.get("mail", None) or info.get("otherMails", [None])[0]
135        # Format group info
136        groups = []
137        group_id_dict = {}
138        for group in info.get("raw_groups", {}).get("value", []):
139            if group["odata_type"] != "#microsoft.graph.group":
140                continue
141            groups.append(group["id"])
142            group_id_dict[group["id"]] = group
143        info["raw_groups"] = group_id_dict
144        return {
145            "username": info.get("userPrincipalName"),
146            "email": mail,
147            "name": info.get("displayName"),
148            "groups": groups,
149        }
150
151    def get_base_group_properties(self, source, group_id, **kwargs):
152        raw_groups = kwargs["info"]["raw_groups"]
153        if group_id in raw_groups:
154            name = raw_groups[group_id]["display_name"]
155        else:
156            name = group_id
157        return {
158            "name": name,
159        }
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def entity_as_dict(unknown):
24def entity_as_dict(entity: Entity) -> dict:
25    """Create a dictionary of a model instance, making sure to remove (known) things
26    we can't JSON serialize"""
27    return sanitize_item(
28        asdict(
29            entity,
30            # Nested entities carry their own backing store, so filter at every level
31            dict_factory=lambda items: {k: v for k, v in items if k != "backing_store"},
32        )
33    )

Create a dictionary of a model instance, making sure to remove (known) things we can't JSON serialize

def get_graph_url(source: authentik.sources.oauth.models.OAuthSource, path: str) -> str:
36def get_graph_url(source: OAuthSource, path: str) -> str:
37    """Use the configured profile's origin for Graph scopes and API requests."""
38    profile_url = source.profile_url or EntraIDType.profile_url
39    return urlsplit(profile_url)._replace(path=path, query="", fragment="").geturl()

Use the configured profile's origin for Graph scopes and API requests.

class EntraIDOAuthRedirect(authentik.sources.oauth.views.redirect.OAuthRedirect):
42class EntraIDOAuthRedirect(OAuthRedirect):
43    """Entra ID OAuth2 Redirect"""
44
45    def get_additional_parameters(self, source):
46        return {
47            "scope": ["openid", get_graph_url(source, "/User.Read")],
48        }

Entra ID OAuth2 Redirect

def get_additional_parameters(self, source):
45    def get_additional_parameters(self, source):
46        return {
47            "scope": ["openid", get_graph_url(source, "/User.Read")],
48        }

Return additional redirect parameters for this source.

 51class EntraIDClient(UserprofileHeaderAuthClient):
 52    """Fetch EntraID group information"""
 53
 54    def get_profile_info(self, token):
 55        # The Graph SDK is heavy, only import it when an Entra ID source is used
 56        from httpx import HTTPError
 57        from kiota_abstractions.api_error import APIError
 58
 59        profile_data = super().get_profile_info(token)
 60        group_scope = get_graph_url(self.source, "/GroupMember.Read.All")
 61        scopes = self.source.additional_scopes.removeprefix("*").split()
 62        if profile_data is None or group_scope not in scopes:
 63            return profile_data
 64        try:
 65            profile_data["raw_groups"] = run(self.get_groups(token))
 66        except (APIError, HTTPError) as exc:
 67            LOGGER.warning("Unable to fetch user groups", exc=exc)
 68            return None
 69        return profile_data
 70
 71    async def get_groups(self, token):
 72        """Fetch all memberships and convert Graph entities for property mappings."""
 73        from kiota_abstractions.authentication.anonymous_authentication_provider import (
 74            AnonymousAuthenticationProvider,
 75        )
 76        from kiota_abstractions.base_request_configuration import RequestConfiguration
 77        from kiota_abstractions.headers_collection import HeadersCollection
 78        from kiota_http.kiota_client_factory import KiotaClientFactory
 79        from msgraph.graph_request_adapter import GraphRequestAdapter, options
 80        from msgraph.graph_service_client import GraphServiceClient
 81        from msgraph_core import GraphClientFactory
 82
 83        # RequestConfiguration shares its default headers between instances
 84        config = RequestConfiguration(headers=HeadersCollection())
 85        config.headers.add("Authorization", f"{token['token_type']} {token['access_token']}")
 86        async with GraphClientFactory.create_with_default_middleware(
 87            options=options, client=KiotaClientFactory.get_default_client()
 88        ) as http_client:
 89            adapter = GraphRequestAdapter(AnonymousAuthenticationProvider(), http_client)
 90            adapter.base_url = get_graph_url(self.source, "/v1.0")
 91            client = GraphServiceClient(request_adapter=adapter)
 92            groups = []
 93            request = client.me.member_of
 94            while request:
 95                page = await request.get(config)
 96                groups.extend(page.value or [])
 97                request = (
 98                    client.me.member_of.with_url(page.odata_next_link)
 99                    if page.odata_next_link
100                    else None
101                )
102        return {"value": [entity_as_dict(group) for group in groups]}

Fetch EntraID group information

def get_profile_info(self, token):
54    def get_profile_info(self, token):
55        # The Graph SDK is heavy, only import it when an Entra ID source is used
56        from httpx import HTTPError
57        from kiota_abstractions.api_error import APIError
58
59        profile_data = super().get_profile_info(token)
60        group_scope = get_graph_url(self.source, "/GroupMember.Read.All")
61        scopes = self.source.additional_scopes.removeprefix("*").split()
62        if profile_data is None or group_scope not in scopes:
63            return profile_data
64        try:
65            profile_data["raw_groups"] = run(self.get_groups(token))
66        except (APIError, HTTPError) as exc:
67            LOGGER.warning("Unable to fetch user groups", exc=exc)
68            return None
69        return profile_data

Fetch user profile information.

async def get_groups(self, token):
 71    async def get_groups(self, token):
 72        """Fetch all memberships and convert Graph entities for property mappings."""
 73        from kiota_abstractions.authentication.anonymous_authentication_provider import (
 74            AnonymousAuthenticationProvider,
 75        )
 76        from kiota_abstractions.base_request_configuration import RequestConfiguration
 77        from kiota_abstractions.headers_collection import HeadersCollection
 78        from kiota_http.kiota_client_factory import KiotaClientFactory
 79        from msgraph.graph_request_adapter import GraphRequestAdapter, options
 80        from msgraph.graph_service_client import GraphServiceClient
 81        from msgraph_core import GraphClientFactory
 82
 83        # RequestConfiguration shares its default headers between instances
 84        config = RequestConfiguration(headers=HeadersCollection())
 85        config.headers.add("Authorization", f"{token['token_type']} {token['access_token']}")
 86        async with GraphClientFactory.create_with_default_middleware(
 87            options=options, client=KiotaClientFactory.get_default_client()
 88        ) as http_client:
 89            adapter = GraphRequestAdapter(AnonymousAuthenticationProvider(), http_client)
 90            adapter.base_url = get_graph_url(self.source, "/v1.0")
 91            client = GraphServiceClient(request_adapter=adapter)
 92            groups = []
 93            request = client.me.member_of
 94            while request:
 95                page = await request.get(config)
 96                groups.extend(page.value or [])
 97                request = (
 98                    client.me.member_of.with_url(page.odata_next_link)
 99                    if page.odata_next_link
100                    else None
101                )
102        return {"value": [entity_as_dict(group) for group in groups]}

Fetch all memberships and convert Graph entities for property mappings.

class EntraIDOAuthCallback(authentik.sources.oauth.types.oidc.OpenIDConnectOAuth2Callback):
105class EntraIDOAuthCallback(OpenIDConnectOAuth2Callback):
106    """EntraID OAuth2 Callback"""
107
108    client_class = EntraIDClient
109
110    def get_user_id(self, info: dict[str, str]) -> str:
111        # Default try to get `id` for the Graph API endpoint
112        # fallback to OpenID logic in case the profile URL was changed
113        return info.get("id", super().get_user_id(info))

EntraID OAuth2 Callback

client_class = <class 'EntraIDClient'>
def get_user_id(self, info: dict[str, str]) -> str:
110    def get_user_id(self, info: dict[str, str]) -> str:
111        # Default try to get `id` for the Graph API endpoint
112        # fallback to OpenID logic in case the profile URL was changed
113        return info.get("id", super().get_user_id(info))

Return unique identifier from the profile info.

@registry.register()
class EntraIDType(authentik.sources.oauth.types.registry.SourceType):
116@registry.register()
117class EntraIDType(SourceType):
118    """Entra ID Type definition"""
119
120    callback_view = EntraIDOAuthCallback
121    redirect_view = EntraIDOAuthRedirect
122    verbose_name = "Entra ID"
123    name = "entraid"
124
125    urls_customizable = True
126
127    authorization_url = "https://login.microsoftonline.com/common/oauth2/v2.0/authorize"
128    access_token_url = "https://login.microsoftonline.com/common/oauth2/v2.0/token"  # nosec
129    profile_url = "https://graph.microsoft.com/v1.0/me"
130    oidc_jwks_url = "https://login.microsoftonline.com/common/discovery/keys"
131
132    authorization_code_auth_method = AuthorizationCodeAuthMethod.POST_BODY
133
134    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
135        mail = info.get("mail", None) or info.get("otherMails", [None])[0]
136        # Format group info
137        groups = []
138        group_id_dict = {}
139        for group in info.get("raw_groups", {}).get("value", []):
140            if group["odata_type"] != "#microsoft.graph.group":
141                continue
142            groups.append(group["id"])
143            group_id_dict[group["id"]] = group
144        info["raw_groups"] = group_id_dict
145        return {
146            "username": info.get("userPrincipalName"),
147            "email": mail,
148            "name": info.get("displayName"),
149            "groups": groups,
150        }
151
152    def get_base_group_properties(self, source, group_id, **kwargs):
153        raw_groups = kwargs["info"]["raw_groups"]
154        if group_id in raw_groups:
155            name = raw_groups[group_id]["display_name"]
156        else:
157            name = group_id
158        return {
159            "name": name,
160        }

Entra ID Type definition

callback_view = <class 'EntraIDOAuthCallback'>
redirect_view = <class 'EntraIDOAuthRedirect'>
verbose_name = 'Entra ID'
name = 'entraid'
urls_customizable = True
authorization_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize'
access_token_url = 'https://login.microsoftonline.com/common/oauth2/v2.0/token'
profile_url = 'https://graph.microsoft.com/v1.0/me'
oidc_jwks_url = 'https://login.microsoftonline.com/common/discovery/keys'
authorization_code_auth_method = AuthorizationCodeAuthMethod.POST_BODY
def get_base_user_properties(self, info: dict[str, typing.Any], **kwargs) -> dict[str, typing.Any]:
134    def get_base_user_properties(self, info: dict[str, Any], **kwargs) -> dict[str, Any]:
135        mail = info.get("mail", None) or info.get("otherMails", [None])[0]
136        # Format group info
137        groups = []
138        group_id_dict = {}
139        for group in info.get("raw_groups", {}).get("value", []):
140            if group["odata_type"] != "#microsoft.graph.group":
141                continue
142            groups.append(group["id"])
143            group_id_dict[group["id"]] = group
144        info["raw_groups"] = group_id_dict
145        return {
146            "username": info.get("userPrincipalName"),
147            "email": mail,
148            "name": info.get("displayName"),
149            "groups": groups,
150        }

Get base user properties for enrollment/update

def get_base_group_properties(self, source, group_id, **kwargs):
152    def get_base_group_properties(self, source, group_id, **kwargs):
153        raw_groups = kwargs["info"]["raw_groups"]
154        if group_id in raw_groups:
155            name = raw_groups[group_id]["display_name"]
156        else:
157            name = group_id
158        return {
159            "name": name,
160        }

Get base group properties for creation/update