authentik.providers.oauth2.id_token
id_token utils
1"""id_token utils""" 2 3from dataclasses import asdict, dataclass, field 4from hashlib import sha256 5from typing import TYPE_CHECKING, Any 6 7from django.http import HttpRequest 8from django.utils import timezone 9 10from authentik.common.oauth.constants import ( 11 ACR_AUTHENTIK_DEFAULT, 12 AMR_MFA, 13 AMR_PASSWORD, 14 AMR_SMART_CARD, 15 AMR_WEBAUTHN, 16 SubModes, 17) 18from authentik.core.models import User, default_token_duration 19from authentik.events.signals import get_login_event 20from authentik.lib.generators import generate_id 21from authentik.lib.tracing import active_tracer 22from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS 23 24if TYPE_CHECKING: 25 from authentik.providers.oauth2.models import BaseGrantModel, OAuth2Provider 26 27 28def hash_session_key(session_key: str) -> str: 29 """Hash the session key for inclusion in JWTs as `sid`""" 30 return sha256(session_key.encode("ascii")).hexdigest() 31 32 33@dataclass(slots=True) 34class IDToken: 35 """The primary extension that OpenID Connect makes to OAuth 2.0 to enable End-Users to be 36 Authenticated is the ID Token data structure. The ID Token is a security token that contains 37 Claims about the Authentication of an End-User by an Authorization Server when using a Client, 38 and potentially other requested Claims. The ID Token is represented as a 39 JSON Web Token (JWT) [JWT]. 40 41 https://openid.net/specs/openid-connect-core-1_0.html#IDToken 42 https://www.iana.org/assignments/jwt/jwt.xhtml""" 43 44 # Issuer, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.1 45 iss: str | None = None 46 # Subject, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.2 47 sub: str | None = None 48 # Audience, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.3 49 aud: str | list[str] | None = None 50 # Expiration time, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.4 51 exp: int | None = None 52 # Issued at, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.6 53 iat: int | None = None 54 # Time when the authentication occurred, 55 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken 56 auth_time: int | None = None 57 # Authentication Context Class Reference, 58 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken 59 acr: str | None = ACR_AUTHENTIK_DEFAULT 60 # Authentication Methods References, 61 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken 62 amr: list[str] | None = None 63 # Code hash value, http://openid.net/specs/openid-connect-core-1_0.html 64 c_hash: str | None = None 65 # Value used to associate a Client session with an ID Token, 66 # http://openid.net/specs/openid-connect-core-1_0.html 67 nonce: str | None = None 68 # Access Token hash value, http://openid.net/specs/openid-connect-core-1_0.html 69 at_hash: str | None = None 70 # Session ID, https://openid.net/specs/openid-connect-frontchannel-1_0.html#ClaimsContents 71 sid: str | None = None 72 # JWT ID, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.7 73 jti: str | None = None 74 # Confirmation JWK, https://datatracker.ietf.org/doc/html/rfc7800#section-3 75 cnf: dict | None = None 76 # Authorized Actor, RFC 8693 §4.1 delegation -- present when this token was issued 77 # via token exchange with an `actor_token` (e.g. an Actor acting for `sub`). 78 # https://datatracker.ietf.org/doc/html/rfc8693#section-4.1 79 act: dict | None = None 80 81 claims: dict[str, Any] = field(default_factory=dict) 82 83 @staticmethod 84 @active_tracer().instrument() 85 def new( 86 provider: OAuth2Provider, token: BaseGrantModel, request: HttpRequest, **kwargs 87 ) -> IDToken: 88 """Create ID Token""" 89 id_token = IDToken(provider, token, **kwargs) 90 id_token.exp = int( 91 (token.expires if token.expires is not None else default_token_duration()).timestamp() 92 ) 93 id_token.iss = provider.get_issuer(request) 94 id_token.jti = generate_id() 95 id_token.aud = provider.client_id 96 id_token.claims = {} 97 98 id_token.sub = id_token._resolve_sub(provider, token.user) 99 100 # Convert datetimes into timestamps. 101 now = timezone.now() 102 id_token.iat = int(now.timestamp()) 103 id_token.auth_time = int(token.auth_time.timestamp()) 104 if token.session: 105 id_token.sid = hash_session_key(token.session.session.session_key) 106 107 # We use the timestamp of the user's last successful login (EventAction.LOGIN) for auth_time 108 auth_event = get_login_event(token.session) 109 if auth_event: 110 # Also check which method was used for authentication 111 method = auth_event.context.get(PLAN_CONTEXT_METHOD, "") 112 method_args = auth_event.context.get(PLAN_CONTEXT_METHOD_ARGS, {}) 113 amr = [] 114 if method == "password": 115 amr.append(AMR_PASSWORD) 116 if method == "auth_webauthn_pwl": 117 amr.append(AMR_WEBAUTHN) 118 if "certificate" in method_args: 119 amr.append(AMR_SMART_CARD) 120 if "mfa_devices" in method_args: 121 amr.append(AMR_MFA) 122 if amr: 123 id_token.amr = amr 124 125 # Include (or not) user standard claims in the id_token. 126 if provider.include_claims_in_id_token: 127 from authentik.providers.oauth2.views.userinfo import UserInfoView 128 129 user_info = UserInfoView() 130 user_info.request = request 131 id_token.claims = user_info.get_claims(token.provider, token) 132 133 # RFC 8693 §4.1 delegation: `sub` above stays the subject (unchanged); `act` 134 # records who is actually exercising the token (e.g. an Actor acting for a 135 # human), when the token-exchange request presented an `actor_token`. 136 # A delegation chain the subject token already carried (passed in as `act`) is 137 # nested under the new actor, or kept as-is when there is no new actor. 138 actor = getattr(token, "actor", None) 139 if actor: 140 act = {"sub": id_token._resolve_sub(provider, actor)} 141 if id_token.act: 142 act["act"] = id_token.act 143 id_token.act = act 144 return id_token 145 146 def _resolve_sub(self, provider: OAuth2Provider, user: User) -> str: 147 """Resolve a `sub`-shaped identifier for `user`, per `provider.sub_mode`.""" 148 if provider.sub_mode == SubModes.HASHED_USER_ID: 149 return user.uid 150 if provider.sub_mode == SubModes.USER_ID: 151 return str(user.pk) 152 if provider.sub_mode == SubModes.USER_UUID: 153 return str(user.uuid) 154 if provider.sub_mode == SubModes.USER_EMAIL: 155 return user.email 156 if provider.sub_mode == SubModes.USER_USERNAME: 157 return user.username 158 if provider.sub_mode == SubModes.USER_UPN: 159 return user.attributes.get("upn", user.uid) 160 raise ValueError(f"Provider {provider} has invalid sub_mode selected: {provider.sub_mode}") 161 162 def to_dict(self) -> dict[str, Any]: 163 """Convert dataclass to dict, and update with keys from `claims`""" 164 id_dict = asdict(self) 165 # All items without a value should be removed instead being set to None/null 166 # https://openid.net/specs/openid-connect-core-1_0.html#JSONSerialization 167 for key in list(id_dict.keys()): 168 if id_dict[key] is None: 169 id_dict.pop(key) 170 id_dict.pop("claims") 171 id_dict.update(self.claims) 172 return id_dict 173 174 def to_access_token(self, provider: OAuth2Provider, token: BaseGrantModel) -> str: 175 """Encode id_token for use as access token, adding fields""" 176 final = self.to_dict() 177 # Access tokens remain bearer tokens not DPoP, should not have key-binding cnf 178 final.pop("cnf", None) 179 final["azp"] = provider.client_id 180 final["uid"] = generate_id() 181 final.setdefault("scope", " ".join(token.scope)) 182 return provider.encode(final) 183 184 def to_jwt(self, provider: OAuth2Provider, jwt_type: str | None = None) -> str: 185 """Shortcut to encode id_token to jwt, signed by self.provider""" 186 return provider.encode(self.to_dict(), jwt_type=jwt_type)
def
hash_session_key(session_key: str) -> str:
29def hash_session_key(session_key: str) -> str: 30 """Hash the session key for inclusion in JWTs as `sid`""" 31 return sha256(session_key.encode("ascii")).hexdigest()
Hash the session key for inclusion in JWTs as sid
@dataclass(slots=True)
class
IDToken:
34@dataclass(slots=True) 35class IDToken: 36 """The primary extension that OpenID Connect makes to OAuth 2.0 to enable End-Users to be 37 Authenticated is the ID Token data structure. The ID Token is a security token that contains 38 Claims about the Authentication of an End-User by an Authorization Server when using a Client, 39 and potentially other requested Claims. The ID Token is represented as a 40 JSON Web Token (JWT) [JWT]. 41 42 https://openid.net/specs/openid-connect-core-1_0.html#IDToken 43 https://www.iana.org/assignments/jwt/jwt.xhtml""" 44 45 # Issuer, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.1 46 iss: str | None = None 47 # Subject, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.2 48 sub: str | None = None 49 # Audience, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.3 50 aud: str | list[str] | None = None 51 # Expiration time, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.4 52 exp: int | None = None 53 # Issued at, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.6 54 iat: int | None = None 55 # Time when the authentication occurred, 56 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken 57 auth_time: int | None = None 58 # Authentication Context Class Reference, 59 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken 60 acr: str | None = ACR_AUTHENTIK_DEFAULT 61 # Authentication Methods References, 62 # https://openid.net/specs/openid-connect-core-1_0.html#IDToken 63 amr: list[str] | None = None 64 # Code hash value, http://openid.net/specs/openid-connect-core-1_0.html 65 c_hash: str | None = None 66 # Value used to associate a Client session with an ID Token, 67 # http://openid.net/specs/openid-connect-core-1_0.html 68 nonce: str | None = None 69 # Access Token hash value, http://openid.net/specs/openid-connect-core-1_0.html 70 at_hash: str | None = None 71 # Session ID, https://openid.net/specs/openid-connect-frontchannel-1_0.html#ClaimsContents 72 sid: str | None = None 73 # JWT ID, https://www.rfc-editor.org/rfc/rfc7519.html#section-4.1.7 74 jti: str | None = None 75 # Confirmation JWK, https://datatracker.ietf.org/doc/html/rfc7800#section-3 76 cnf: dict | None = None 77 # Authorized Actor, RFC 8693 §4.1 delegation -- present when this token was issued 78 # via token exchange with an `actor_token` (e.g. an Actor acting for `sub`). 79 # https://datatracker.ietf.org/doc/html/rfc8693#section-4.1 80 act: dict | None = None 81 82 claims: dict[str, Any] = field(default_factory=dict) 83 84 @staticmethod 85 @active_tracer().instrument() 86 def new( 87 provider: OAuth2Provider, token: BaseGrantModel, request: HttpRequest, **kwargs 88 ) -> IDToken: 89 """Create ID Token""" 90 id_token = IDToken(provider, token, **kwargs) 91 id_token.exp = int( 92 (token.expires if token.expires is not None else default_token_duration()).timestamp() 93 ) 94 id_token.iss = provider.get_issuer(request) 95 id_token.jti = generate_id() 96 id_token.aud = provider.client_id 97 id_token.claims = {} 98 99 id_token.sub = id_token._resolve_sub(provider, token.user) 100 101 # Convert datetimes into timestamps. 102 now = timezone.now() 103 id_token.iat = int(now.timestamp()) 104 id_token.auth_time = int(token.auth_time.timestamp()) 105 if token.session: 106 id_token.sid = hash_session_key(token.session.session.session_key) 107 108 # We use the timestamp of the user's last successful login (EventAction.LOGIN) for auth_time 109 auth_event = get_login_event(token.session) 110 if auth_event: 111 # Also check which method was used for authentication 112 method = auth_event.context.get(PLAN_CONTEXT_METHOD, "") 113 method_args = auth_event.context.get(PLAN_CONTEXT_METHOD_ARGS, {}) 114 amr = [] 115 if method == "password": 116 amr.append(AMR_PASSWORD) 117 if method == "auth_webauthn_pwl": 118 amr.append(AMR_WEBAUTHN) 119 if "certificate" in method_args: 120 amr.append(AMR_SMART_CARD) 121 if "mfa_devices" in method_args: 122 amr.append(AMR_MFA) 123 if amr: 124 id_token.amr = amr 125 126 # Include (or not) user standard claims in the id_token. 127 if provider.include_claims_in_id_token: 128 from authentik.providers.oauth2.views.userinfo import UserInfoView 129 130 user_info = UserInfoView() 131 user_info.request = request 132 id_token.claims = user_info.get_claims(token.provider, token) 133 134 # RFC 8693 §4.1 delegation: `sub` above stays the subject (unchanged); `act` 135 # records who is actually exercising the token (e.g. an Actor acting for a 136 # human), when the token-exchange request presented an `actor_token`. 137 # A delegation chain the subject token already carried (passed in as `act`) is 138 # nested under the new actor, or kept as-is when there is no new actor. 139 actor = getattr(token, "actor", None) 140 if actor: 141 act = {"sub": id_token._resolve_sub(provider, actor)} 142 if id_token.act: 143 act["act"] = id_token.act 144 id_token.act = act 145 return id_token 146 147 def _resolve_sub(self, provider: OAuth2Provider, user: User) -> str: 148 """Resolve a `sub`-shaped identifier for `user`, per `provider.sub_mode`.""" 149 if provider.sub_mode == SubModes.HASHED_USER_ID: 150 return user.uid 151 if provider.sub_mode == SubModes.USER_ID: 152 return str(user.pk) 153 if provider.sub_mode == SubModes.USER_UUID: 154 return str(user.uuid) 155 if provider.sub_mode == SubModes.USER_EMAIL: 156 return user.email 157 if provider.sub_mode == SubModes.USER_USERNAME: 158 return user.username 159 if provider.sub_mode == SubModes.USER_UPN: 160 return user.attributes.get("upn", user.uid) 161 raise ValueError(f"Provider {provider} has invalid sub_mode selected: {provider.sub_mode}") 162 163 def to_dict(self) -> dict[str, Any]: 164 """Convert dataclass to dict, and update with keys from `claims`""" 165 id_dict = asdict(self) 166 # All items without a value should be removed instead being set to None/null 167 # https://openid.net/specs/openid-connect-core-1_0.html#JSONSerialization 168 for key in list(id_dict.keys()): 169 if id_dict[key] is None: 170 id_dict.pop(key) 171 id_dict.pop("claims") 172 id_dict.update(self.claims) 173 return id_dict 174 175 def to_access_token(self, provider: OAuth2Provider, token: BaseGrantModel) -> str: 176 """Encode id_token for use as access token, adding fields""" 177 final = self.to_dict() 178 # Access tokens remain bearer tokens not DPoP, should not have key-binding cnf 179 final.pop("cnf", None) 180 final["azp"] = provider.client_id 181 final["uid"] = generate_id() 182 final.setdefault("scope", " ".join(token.scope)) 183 return provider.encode(final) 184 185 def to_jwt(self, provider: OAuth2Provider, jwt_type: str | None = None) -> str: 186 """Shortcut to encode id_token to jwt, signed by self.provider""" 187 return provider.encode(self.to_dict(), jwt_type=jwt_type)
The primary extension that OpenID Connect makes to OAuth 2.0 to enable End-Users to be Authenticated is the ID Token data structure. The ID Token is a security token that contains Claims about the Authentication of an End-User by an Authorization Server when using a Client, and potentially other requested Claims. The ID Token is represented as a JSON Web Token (JWT) [JWT].
https://openid.net/specs/openid-connect-core-1_0.html#IDToken https://www.iana.org/assignments/jwt/jwt.xhtml
IDToken( iss: str | None = None, sub: str | None = None, aud: str | list[str] | None = None, exp: int | None = None, iat: int | None = None, auth_time: int | None = None, acr: str | None = 'goauthentik.io/providers/oauth2/default', amr: list[str] | None = None, c_hash: str | None = None, nonce: str | None = None, at_hash: str | None = None, sid: str | None = None, jti: str | None = None, cnf: dict | None = None, act: dict | None = None, claims: dict[str, typing.Any] = <factory>)
@staticmethod
@active_tracer().instrument()
def
new(unknown):
84 @staticmethod 85 @active_tracer().instrument() 86 def new( 87 provider: OAuth2Provider, token: BaseGrantModel, request: HttpRequest, **kwargs 88 ) -> IDToken: 89 """Create ID Token""" 90 id_token = IDToken(provider, token, **kwargs) 91 id_token.exp = int( 92 (token.expires if token.expires is not None else default_token_duration()).timestamp() 93 ) 94 id_token.iss = provider.get_issuer(request) 95 id_token.jti = generate_id() 96 id_token.aud = provider.client_id 97 id_token.claims = {} 98 99 id_token.sub = id_token._resolve_sub(provider, token.user) 100 101 # Convert datetimes into timestamps. 102 now = timezone.now() 103 id_token.iat = int(now.timestamp()) 104 id_token.auth_time = int(token.auth_time.timestamp()) 105 if token.session: 106 id_token.sid = hash_session_key(token.session.session.session_key) 107 108 # We use the timestamp of the user's last successful login (EventAction.LOGIN) for auth_time 109 auth_event = get_login_event(token.session) 110 if auth_event: 111 # Also check which method was used for authentication 112 method = auth_event.context.get(PLAN_CONTEXT_METHOD, "") 113 method_args = auth_event.context.get(PLAN_CONTEXT_METHOD_ARGS, {}) 114 amr = [] 115 if method == "password": 116 amr.append(AMR_PASSWORD) 117 if method == "auth_webauthn_pwl": 118 amr.append(AMR_WEBAUTHN) 119 if "certificate" in method_args: 120 amr.append(AMR_SMART_CARD) 121 if "mfa_devices" in method_args: 122 amr.append(AMR_MFA) 123 if amr: 124 id_token.amr = amr 125 126 # Include (or not) user standard claims in the id_token. 127 if provider.include_claims_in_id_token: 128 from authentik.providers.oauth2.views.userinfo import UserInfoView 129 130 user_info = UserInfoView() 131 user_info.request = request 132 id_token.claims = user_info.get_claims(token.provider, token) 133 134 # RFC 8693 §4.1 delegation: `sub` above stays the subject (unchanged); `act` 135 # records who is actually exercising the token (e.g. an Actor acting for a 136 # human), when the token-exchange request presented an `actor_token`. 137 # A delegation chain the subject token already carried (passed in as `act`) is 138 # nested under the new actor, or kept as-is when there is no new actor. 139 actor = getattr(token, "actor", None) 140 if actor: 141 act = {"sub": id_token._resolve_sub(provider, actor)} 142 if id_token.act: 143 act["act"] = id_token.act 144 id_token.act = act 145 return id_token
Create ID Token
def
to_dict(self) -> dict[str, typing.Any]:
163 def to_dict(self) -> dict[str, Any]: 164 """Convert dataclass to dict, and update with keys from `claims`""" 165 id_dict = asdict(self) 166 # All items without a value should be removed instead being set to None/null 167 # https://openid.net/specs/openid-connect-core-1_0.html#JSONSerialization 168 for key in list(id_dict.keys()): 169 if id_dict[key] is None: 170 id_dict.pop(key) 171 id_dict.pop("claims") 172 id_dict.update(self.claims) 173 return id_dict
Convert dataclass to dict, and update with keys from claims
def
to_access_token(unknown):
175 def to_access_token(self, provider: OAuth2Provider, token: BaseGrantModel) -> str: 176 """Encode id_token for use as access token, adding fields""" 177 final = self.to_dict() 178 # Access tokens remain bearer tokens not DPoP, should not have key-binding cnf 179 final.pop("cnf", None) 180 final["azp"] = provider.client_id 181 final["uid"] = generate_id() 182 final.setdefault("scope", " ".join(token.scope)) 183 return provider.encode(final)
Encode id_token for use as access token, adding fields