authentik.sources.oauth.clients.oauth2

OAuth 2 Clients

  1"""OAuth 2 Clients"""
  2
  3from json import loads
  4from typing import Any
  5from urllib.parse import parse_qsl
  6
  7from django.utils.crypto import constant_time_compare, get_random_string
  8from django.utils.translation import gettext as _
  9from requests.auth import AuthBase, HTTPBasicAuth
 10from requests.exceptions import RequestException
 11from requests.models import Response
 12from structlog.stdlib import get_logger
 13
 14from authentik.lib.generators import generate_id
 15from authentik.providers.oauth2.utils import pkce_s256_challenge
 16from authentik.sources.oauth.clients.base import BaseOAuthClient
 17from authentik.sources.oauth.models import (
 18    AuthorizationCodeAuthMethod,
 19    PKCEMethod,
 20)
 21
 22LOGGER = get_logger()
 23SESSION_KEY_OAUTH_PKCE = "authentik/sources/oauth/pkce"
 24
 25
 26class OAuth2Client(BaseOAuthClient):
 27    """OAuth2 Client"""
 28
 29    _default_headers = {
 30        "Accept": "application/json",
 31    }
 32
 33    def get_request_arg(self, key: str, default: Any | None = None) -> Any:
 34        """Depending on request type, get data from post or get"""
 35        if self.request.method == "POST":
 36            return self.request.POST.get(key, default)
 37        return self.request.GET.get(key, default)
 38
 39    def check_application_state(self) -> bool:
 40        """Check optional state parameter."""
 41        stored = self.request.session.get(self.session_key, None)
 42        returned = self.get_request_arg("state", None)
 43        check = False
 44        if stored is not None:
 45            if returned is not None:
 46                check = constant_time_compare(stored, returned)
 47            else:
 48                LOGGER.warning("No state parameter returned by the source.")
 49        else:
 50            LOGGER.warning("No state stored in the session.")
 51        return check
 52
 53    def get_application_state(self) -> str:
 54        """Generate state optional parameter."""
 55        return get_random_string(32)
 56
 57    def get_client_id(self) -> str:
 58        """Get client id"""
 59        return self.source.consumer_key
 60
 61    def get_client_secret(self) -> str:
 62        """Get client secret"""
 63        return self.source.consumer_secret
 64
 65    def get_access_token_args(self, callback: str | None, code: str | None) -> dict[str, Any]:
 66        args = {
 67            "grant_type": "authorization_code",
 68        }
 69        if callback:
 70            args["redirect_uri"] = callback
 71        if code:
 72            args["code"] = code
 73        if self.request:
 74            pkce_mode = self.source.source_type.pkce
 75            if self.source.source_type.urls_customizable and self.source.pkce:
 76                pkce_mode = self.source.pkce
 77            if pkce_mode != PKCEMethod.NONE:
 78                args["code_verifier"] = self.request.session[SESSION_KEY_OAUTH_PKCE]
 79        client_id = self.get_client_id()
 80        client_secret = self.get_client_secret()
 81        if (
 82            self.source.source_type.authorization_code_auth_method
 83            == AuthorizationCodeAuthMethod.POST_BODY
 84        ):
 85            args["client_id"] = client_id
 86            if client_secret:
 87                args["client_secret"] = client_secret
 88        # For public clients (no secret, no basic auth), always include client_id
 89        if not self.get_access_token_auth():
 90            args.setdefault("client_id", client_id)
 91        return args
 92
 93    def get_access_token_auth(self) -> AuthBase | None:
 94        if (
 95            self.source.source_type.authorization_code_auth_method
 96            == AuthorizationCodeAuthMethod.BASIC_AUTH
 97            and self.get_client_secret()
 98        ):
 99            return HTTPBasicAuth(self.get_client_id(), self.get_client_secret())
100        return None
101
102    def get_access_token(self, **request_kwargs) -> dict[str, Any] | None:
103        """Fetch access token from callback request."""
104        callback = self.request.build_absolute_uri(self.callback or self.request.path)
105        if not self.check_application_state():
106            LOGGER.warning("Application state check failed.")
107            return {"error": "State check failed."}
108        code = self.get_request_arg("code", None)
109        if not code:
110            LOGGER.warning("No code returned by the source")
111            error = self.get_request_arg("error", None)
112            error_desc = self.get_request_arg("error_description", None)
113            return {"error": error_desc or error or _("No token received.")}
114        try:
115            access_token_url = self.source.source_type.access_token_url or ""
116            if self.source.source_type.urls_customizable and self.source.access_token_url:
117                access_token_url = self.source.access_token_url
118            response = self.do_request(
119                "post",
120                access_token_url,
121                auth=self.get_access_token_auth(),
122                data=self.get_access_token_args(callback, code),
123                headers=self._default_headers,
124                **request_kwargs,
125            )
126            response.raise_for_status()
127        except RequestException as exc:
128            LOGGER.warning(
129                "Unable to fetch access token",
130                exc=exc,
131                response=exc.response.text if exc.response is not None else str(exc),
132            )
133            return None
134        return response.json()
135
136    def get_redirect_args(self) -> dict[str, str]:
137        """Get request parameters for redirect url."""
138        callback = self.request.build_absolute_uri(self.callback)
139        client_id: str = self.get_client_id()
140        args: dict[str, str] = {
141            "client_id": client_id,
142            "redirect_uri": callback,
143            "response_type": "code",
144        }
145        state = self.get_application_state()
146        if state is not None:
147            args["state"] = state
148            self.request.session[self.session_key] = state
149        pkce_mode = self.source.source_type.pkce
150        if self.source.source_type.urls_customizable and self.source.pkce:
151            pkce_mode = self.source.pkce
152        if pkce_mode != PKCEMethod.NONE:
153            verifier = generate_id(length=128)
154            self.request.session[SESSION_KEY_OAUTH_PKCE] = verifier
155            # https://datatracker.ietf.org/doc/html/rfc7636#section-4.2
156            if pkce_mode == PKCEMethod.PLAIN:
157                args["code_challenge"] = verifier
158            elif pkce_mode == PKCEMethod.S256:
159                args["code_challenge"] = pkce_s256_challenge(verifier)
160            args["code_challenge_method"] = str(pkce_mode)
161        return args
162
163    def parse_raw_token(self, raw_token: str) -> dict[str, Any]:
164        """Parse token and secret from raw token response."""
165        # Load as json first then parse as query string
166        try:
167            token_data = loads(raw_token)
168        except ValueError:
169            return dict(parse_qsl(raw_token))
170        return token_data
171
172    def do_request(self, method: str, url: str, **kwargs) -> Response:
173        """Build remote url request. Constructs necessary auth."""
174        if "token" in kwargs:
175            token = kwargs.pop("token")
176
177            params = kwargs.get("params", {})
178            params["access_token"] = token["access_token"]
179            kwargs["params"] = params
180
181            headers = kwargs.get("headers", {})
182            headers["Authorization"] = f"{token['token_type']} {token['access_token']}"
183            kwargs["headers"] = headers
184        return super().do_request(method, url, **kwargs)
185
186    @property
187    def session_key(self):
188        return f"oauth-client-{self.source.name}-request-state"
189
190
191class UserprofileHeaderAuthClient(OAuth2Client):
192    """OAuth client which only sends authentication via header, not querystring"""
193
194    def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
195        "Fetch user profile information."
196        profile_url = self.source.source_type.profile_url or ""
197        if self.source.source_type.urls_customizable and self.source.profile_url:
198            profile_url = self.source.profile_url
199        if profile_url == "":
200            return None
201        response = self.session.request(
202            "get",
203            profile_url,
204            headers={"Authorization": f"{token['token_type']} {token['access_token']}"},
205        )
206        try:
207            response.raise_for_status()
208        except RequestException as exc:
209            LOGGER.warning(
210                "Unable to fetch user profile from profile_url",
211                exc=exc,
212                response=exc.response.text if exc.response is not None else str(exc),
213            )
214            return None
215        return response.json()
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
SESSION_KEY_OAUTH_PKCE = 'authentik/sources/oauth/pkce'
class OAuth2Client(authentik.sources.oauth.clients.base.BaseOAuthClient):
 27class OAuth2Client(BaseOAuthClient):
 28    """OAuth2 Client"""
 29
 30    _default_headers = {
 31        "Accept": "application/json",
 32    }
 33
 34    def get_request_arg(self, key: str, default: Any | None = None) -> Any:
 35        """Depending on request type, get data from post or get"""
 36        if self.request.method == "POST":
 37            return self.request.POST.get(key, default)
 38        return self.request.GET.get(key, default)
 39
 40    def check_application_state(self) -> bool:
 41        """Check optional state parameter."""
 42        stored = self.request.session.get(self.session_key, None)
 43        returned = self.get_request_arg("state", None)
 44        check = False
 45        if stored is not None:
 46            if returned is not None:
 47                check = constant_time_compare(stored, returned)
 48            else:
 49                LOGGER.warning("No state parameter returned by the source.")
 50        else:
 51            LOGGER.warning("No state stored in the session.")
 52        return check
 53
 54    def get_application_state(self) -> str:
 55        """Generate state optional parameter."""
 56        return get_random_string(32)
 57
 58    def get_client_id(self) -> str:
 59        """Get client id"""
 60        return self.source.consumer_key
 61
 62    def get_client_secret(self) -> str:
 63        """Get client secret"""
 64        return self.source.consumer_secret
 65
 66    def get_access_token_args(self, callback: str | None, code: str | None) -> dict[str, Any]:
 67        args = {
 68            "grant_type": "authorization_code",
 69        }
 70        if callback:
 71            args["redirect_uri"] = callback
 72        if code:
 73            args["code"] = code
 74        if self.request:
 75            pkce_mode = self.source.source_type.pkce
 76            if self.source.source_type.urls_customizable and self.source.pkce:
 77                pkce_mode = self.source.pkce
 78            if pkce_mode != PKCEMethod.NONE:
 79                args["code_verifier"] = self.request.session[SESSION_KEY_OAUTH_PKCE]
 80        client_id = self.get_client_id()
 81        client_secret = self.get_client_secret()
 82        if (
 83            self.source.source_type.authorization_code_auth_method
 84            == AuthorizationCodeAuthMethod.POST_BODY
 85        ):
 86            args["client_id"] = client_id
 87            if client_secret:
 88                args["client_secret"] = client_secret
 89        # For public clients (no secret, no basic auth), always include client_id
 90        if not self.get_access_token_auth():
 91            args.setdefault("client_id", client_id)
 92        return args
 93
 94    def get_access_token_auth(self) -> AuthBase | None:
 95        if (
 96            self.source.source_type.authorization_code_auth_method
 97            == AuthorizationCodeAuthMethod.BASIC_AUTH
 98            and self.get_client_secret()
 99        ):
100            return HTTPBasicAuth(self.get_client_id(), self.get_client_secret())
101        return None
102
103    def get_access_token(self, **request_kwargs) -> dict[str, Any] | None:
104        """Fetch access token from callback request."""
105        callback = self.request.build_absolute_uri(self.callback or self.request.path)
106        if not self.check_application_state():
107            LOGGER.warning("Application state check failed.")
108            return {"error": "State check failed."}
109        code = self.get_request_arg("code", None)
110        if not code:
111            LOGGER.warning("No code returned by the source")
112            error = self.get_request_arg("error", None)
113            error_desc = self.get_request_arg("error_description", None)
114            return {"error": error_desc or error or _("No token received.")}
115        try:
116            access_token_url = self.source.source_type.access_token_url or ""
117            if self.source.source_type.urls_customizable and self.source.access_token_url:
118                access_token_url = self.source.access_token_url
119            response = self.do_request(
120                "post",
121                access_token_url,
122                auth=self.get_access_token_auth(),
123                data=self.get_access_token_args(callback, code),
124                headers=self._default_headers,
125                **request_kwargs,
126            )
127            response.raise_for_status()
128        except RequestException as exc:
129            LOGGER.warning(
130                "Unable to fetch access token",
131                exc=exc,
132                response=exc.response.text if exc.response is not None else str(exc),
133            )
134            return None
135        return response.json()
136
137    def get_redirect_args(self) -> dict[str, str]:
138        """Get request parameters for redirect url."""
139        callback = self.request.build_absolute_uri(self.callback)
140        client_id: str = self.get_client_id()
141        args: dict[str, str] = {
142            "client_id": client_id,
143            "redirect_uri": callback,
144            "response_type": "code",
145        }
146        state = self.get_application_state()
147        if state is not None:
148            args["state"] = state
149            self.request.session[self.session_key] = state
150        pkce_mode = self.source.source_type.pkce
151        if self.source.source_type.urls_customizable and self.source.pkce:
152            pkce_mode = self.source.pkce
153        if pkce_mode != PKCEMethod.NONE:
154            verifier = generate_id(length=128)
155            self.request.session[SESSION_KEY_OAUTH_PKCE] = verifier
156            # https://datatracker.ietf.org/doc/html/rfc7636#section-4.2
157            if pkce_mode == PKCEMethod.PLAIN:
158                args["code_challenge"] = verifier
159            elif pkce_mode == PKCEMethod.S256:
160                args["code_challenge"] = pkce_s256_challenge(verifier)
161            args["code_challenge_method"] = str(pkce_mode)
162        return args
163
164    def parse_raw_token(self, raw_token: str) -> dict[str, Any]:
165        """Parse token and secret from raw token response."""
166        # Load as json first then parse as query string
167        try:
168            token_data = loads(raw_token)
169        except ValueError:
170            return dict(parse_qsl(raw_token))
171        return token_data
172
173    def do_request(self, method: str, url: str, **kwargs) -> Response:
174        """Build remote url request. Constructs necessary auth."""
175        if "token" in kwargs:
176            token = kwargs.pop("token")
177
178            params = kwargs.get("params", {})
179            params["access_token"] = token["access_token"]
180            kwargs["params"] = params
181
182            headers = kwargs.get("headers", {})
183            headers["Authorization"] = f"{token['token_type']} {token['access_token']}"
184            kwargs["headers"] = headers
185        return super().do_request(method, url, **kwargs)
186
187    @property
188    def session_key(self):
189        return f"oauth-client-{self.source.name}-request-state"

OAuth2 Client

def get_request_arg(self, key: str, default: Any | None = None) -> Any:
34    def get_request_arg(self, key: str, default: Any | None = None) -> Any:
35        """Depending on request type, get data from post or get"""
36        if self.request.method == "POST":
37            return self.request.POST.get(key, default)
38        return self.request.GET.get(key, default)

Depending on request type, get data from post or get

def check_application_state(self) -> bool:
40    def check_application_state(self) -> bool:
41        """Check optional state parameter."""
42        stored = self.request.session.get(self.session_key, None)
43        returned = self.get_request_arg("state", None)
44        check = False
45        if stored is not None:
46            if returned is not None:
47                check = constant_time_compare(stored, returned)
48            else:
49                LOGGER.warning("No state parameter returned by the source.")
50        else:
51            LOGGER.warning("No state stored in the session.")
52        return check

Check optional state parameter.

def get_application_state(self) -> str:
54    def get_application_state(self) -> str:
55        """Generate state optional parameter."""
56        return get_random_string(32)

Generate state optional parameter.

def get_client_id(self) -> str:
58    def get_client_id(self) -> str:
59        """Get client id"""
60        return self.source.consumer_key

Get client id

def get_client_secret(self) -> str:
62    def get_client_secret(self) -> str:
63        """Get client secret"""
64        return self.source.consumer_secret

Get client secret

def get_access_token_args(self, callback: str | None, code: str | None) -> dict[str, typing.Any]:
66    def get_access_token_args(self, callback: str | None, code: str | None) -> dict[str, Any]:
67        args = {
68            "grant_type": "authorization_code",
69        }
70        if callback:
71            args["redirect_uri"] = callback
72        if code:
73            args["code"] = code
74        if self.request:
75            pkce_mode = self.source.source_type.pkce
76            if self.source.source_type.urls_customizable and self.source.pkce:
77                pkce_mode = self.source.pkce
78            if pkce_mode != PKCEMethod.NONE:
79                args["code_verifier"] = self.request.session[SESSION_KEY_OAUTH_PKCE]
80        client_id = self.get_client_id()
81        client_secret = self.get_client_secret()
82        if (
83            self.source.source_type.authorization_code_auth_method
84            == AuthorizationCodeAuthMethod.POST_BODY
85        ):
86            args["client_id"] = client_id
87            if client_secret:
88                args["client_secret"] = client_secret
89        # For public clients (no secret, no basic auth), always include client_id
90        if not self.get_access_token_auth():
91            args.setdefault("client_id", client_id)
92        return args
def get_access_token_auth(self) -> requests.auth.AuthBase | None:
 94    def get_access_token_auth(self) -> AuthBase | None:
 95        if (
 96            self.source.source_type.authorization_code_auth_method
 97            == AuthorizationCodeAuthMethod.BASIC_AUTH
 98            and self.get_client_secret()
 99        ):
100            return HTTPBasicAuth(self.get_client_id(), self.get_client_secret())
101        return None
def get_access_token(self, **request_kwargs) -> dict[str, Any] | None:
103    def get_access_token(self, **request_kwargs) -> dict[str, Any] | None:
104        """Fetch access token from callback request."""
105        callback = self.request.build_absolute_uri(self.callback or self.request.path)
106        if not self.check_application_state():
107            LOGGER.warning("Application state check failed.")
108            return {"error": "State check failed."}
109        code = self.get_request_arg("code", None)
110        if not code:
111            LOGGER.warning("No code returned by the source")
112            error = self.get_request_arg("error", None)
113            error_desc = self.get_request_arg("error_description", None)
114            return {"error": error_desc or error or _("No token received.")}
115        try:
116            access_token_url = self.source.source_type.access_token_url or ""
117            if self.source.source_type.urls_customizable and self.source.access_token_url:
118                access_token_url = self.source.access_token_url
119            response = self.do_request(
120                "post",
121                access_token_url,
122                auth=self.get_access_token_auth(),
123                data=self.get_access_token_args(callback, code),
124                headers=self._default_headers,
125                **request_kwargs,
126            )
127            response.raise_for_status()
128        except RequestException as exc:
129            LOGGER.warning(
130                "Unable to fetch access token",
131                exc=exc,
132                response=exc.response.text if exc.response is not None else str(exc),
133            )
134            return None
135        return response.json()

Fetch access token from callback request.

def get_redirect_args(self) -> dict[str, str]:
137    def get_redirect_args(self) -> dict[str, str]:
138        """Get request parameters for redirect url."""
139        callback = self.request.build_absolute_uri(self.callback)
140        client_id: str = self.get_client_id()
141        args: dict[str, str] = {
142            "client_id": client_id,
143            "redirect_uri": callback,
144            "response_type": "code",
145        }
146        state = self.get_application_state()
147        if state is not None:
148            args["state"] = state
149            self.request.session[self.session_key] = state
150        pkce_mode = self.source.source_type.pkce
151        if self.source.source_type.urls_customizable and self.source.pkce:
152            pkce_mode = self.source.pkce
153        if pkce_mode != PKCEMethod.NONE:
154            verifier = generate_id(length=128)
155            self.request.session[SESSION_KEY_OAUTH_PKCE] = verifier
156            # https://datatracker.ietf.org/doc/html/rfc7636#section-4.2
157            if pkce_mode == PKCEMethod.PLAIN:
158                args["code_challenge"] = verifier
159            elif pkce_mode == PKCEMethod.S256:
160                args["code_challenge"] = pkce_s256_challenge(verifier)
161            args["code_challenge_method"] = str(pkce_mode)
162        return args

Get request parameters for redirect url.

def parse_raw_token(self, raw_token: str) -> dict[str, typing.Any]:
164    def parse_raw_token(self, raw_token: str) -> dict[str, Any]:
165        """Parse token and secret from raw token response."""
166        # Load as json first then parse as query string
167        try:
168            token_data = loads(raw_token)
169        except ValueError:
170            return dict(parse_qsl(raw_token))
171        return token_data

Parse token and secret from raw token response.

def do_request(self, method: str, url: str, **kwargs) -> requests.models.Response:
173    def do_request(self, method: str, url: str, **kwargs) -> Response:
174        """Build remote url request. Constructs necessary auth."""
175        if "token" in kwargs:
176            token = kwargs.pop("token")
177
178            params = kwargs.get("params", {})
179            params["access_token"] = token["access_token"]
180            kwargs["params"] = params
181
182            headers = kwargs.get("headers", {})
183            headers["Authorization"] = f"{token['token_type']} {token['access_token']}"
184            kwargs["headers"] = headers
185        return super().do_request(method, url, **kwargs)

Build remote url request. Constructs necessary auth.

session_key
187    @property
188    def session_key(self):
189        return f"oauth-client-{self.source.name}-request-state"

Return Session Key

class UserprofileHeaderAuthClient(OAuth2Client):
192class UserprofileHeaderAuthClient(OAuth2Client):
193    """OAuth client which only sends authentication via header, not querystring"""
194
195    def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
196        "Fetch user profile information."
197        profile_url = self.source.source_type.profile_url or ""
198        if self.source.source_type.urls_customizable and self.source.profile_url:
199            profile_url = self.source.profile_url
200        if profile_url == "":
201            return None
202        response = self.session.request(
203            "get",
204            profile_url,
205            headers={"Authorization": f"{token['token_type']} {token['access_token']}"},
206        )
207        try:
208            response.raise_for_status()
209        except RequestException as exc:
210            LOGGER.warning(
211                "Unable to fetch user profile from profile_url",
212                exc=exc,
213                response=exc.response.text if exc.response is not None else str(exc),
214            )
215            return None
216        return response.json()

OAuth client which only sends authentication via header, not querystring

def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
195    def get_profile_info(self, token: dict[str, str]) -> dict[str, Any] | None:
196        "Fetch user profile information."
197        profile_url = self.source.source_type.profile_url or ""
198        if self.source.source_type.urls_customizable and self.source.profile_url:
199            profile_url = self.source.profile_url
200        if profile_url == "":
201            return None
202        response = self.session.request(
203            "get",
204            profile_url,
205            headers={"Authorization": f"{token['token_type']} {token['access_token']}"},
206        )
207        try:
208            response.raise_for_status()
209        except RequestException as exc:
210            LOGGER.warning(
211                "Unable to fetch user profile from profile_url",
212                exc=exc,
213                response=exc.response.text if exc.response is not None else str(exc),
214            )
215            return None
216        return response.json()

Fetch user profile information.