authentik.providers.oauth2.errors

OAuth errors

  1"""OAuth errors"""
  2
  3from urllib.parse import quote, urlencode, urlparse, urlsplit, urlunsplit
  4
  5from django.http import HttpRequest, HttpResponse
  6from django.template.response import TemplateResponse
  7
  8from authentik.events.models import Event, EventAction
  9from authentik.lib.tracing.exceptions import TracingIgnoredException
 10from authentik.lib.views import bad_request_message
 11from authentik.providers.oauth2.models import GrantType, RedirectURI, ResponseMode
 12
 13
 14class OAuth2Error(TracingIgnoredException):
 15    """Base class for all OAuth2 Errors"""
 16
 17    error: str
 18    description: str
 19    cause: str | None = None
 20
 21    def create_dict(self, request: HttpRequest):
 22        """Return error as dict for JSON Rendering"""
 23        return {
 24            "error": self.error,
 25            "error_description": self.description,
 26            "request_id": request.request_id,
 27        }
 28
 29    def __repr__(self) -> str:
 30        return self.error
 31
 32    def to_event(self, message: str | None = None, **kwargs) -> Event:
 33        """Create configuration_error Event."""
 34        return Event.new(
 35            EventAction.CONFIGURATION_ERROR,
 36            message=message or self.description,
 37            cause=self.cause,
 38            error=self.error,
 39            **kwargs,
 40        )
 41
 42    def with_cause(self, cause: str):
 43        self.cause = cause
 44        return self
 45
 46
 47class RedirectUriError(OAuth2Error):
 48    """The request fails due to a missing, invalid, or mismatching
 49    redirection URI (redirect_uri)."""
 50
 51    error = "Redirect URI Error"
 52    description = (
 53        "The request fails due to a missing, invalid, or mismatching "
 54        "redirection URI (redirect_uri)."
 55    )
 56
 57    provided_uri: str
 58    allowed_uris: list[RedirectURI]
 59
 60    def __init__(self, provided_uri: str, allowed_uris: list[RedirectURI]) -> None:
 61        super().__init__()
 62        self.provided_uri = provided_uri
 63        self.allowed_uris = allowed_uris
 64
 65    def to_event(self, **kwargs) -> Event:
 66        return super().to_event(
 67            (
 68                f"Invalid redirect URI was used. Client used '{self.provided_uri}'. "
 69                f"Allowed redirect URIs are {','.join(self.allowed_uris)}"
 70            ),
 71            **kwargs,
 72        )
 73
 74
 75class ClientIdError(OAuth2Error):
 76    """The client identifier (client_id) is missing or invalid."""
 77
 78    error = "Client ID Error"
 79    description = "The client identifier (client_id) is missing or invalid."
 80
 81    client_id: str
 82
 83    def __init__(self, client_id: str) -> None:
 84        super().__init__()
 85        self.client_id = client_id
 86
 87    def to_event(self, **kwargs) -> Event:
 88        return super().to_event(f"Invalid client identifier: {self.client_id}.", **kwargs)
 89
 90
 91class UserAuthError(OAuth2Error):
 92    """
 93    Specific to the Resource Owner Password Credentials flow when
 94    the Resource Owners credentials are not valid.
 95    """
 96
 97    error = "access_denied"
 98    description = "The resource owner or authorization server denied the request."
 99
100
101class TokenIntrospectionError(OAuth2Error):
102    """
103    Specific to the introspection endpoint. This error will be converted
104    to an "active: false" response, as per the spec.
105    See https://datatracker.ietf.org/doc/html/rfc7662
106    """
107
108
109class AuthorizeError(OAuth2Error):
110    """General Authorization Errors"""
111
112    errors = {
113        # OAuth2 errors.
114        # https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1
115        "invalid_request": "The request is otherwise malformed",
116        "unauthorized_client": (
117            "The client is not authorized to request an authorization code using this method"
118        ),
119        "access_denied": "The resource owner or authorization server denied the request",
120        "unsupported_response_type": (
121            "The authorization server does not support obtaining an authorization code "
122            "using this method"
123        ),
124        "invalid_scope": "The requested scope is invalid, unknown, or malformed",
125        "server_error": "The authorization server encountered an error",
126        "temporarily_unavailable": (
127            "The authorization server is currently unable to handle the request due to a "
128            "temporary overloading or maintenance of the server"
129        ),
130        # OpenID errors.
131        # http://openid.net/specs/openid-connect-core-1_0.html#AuthError
132        "interaction_required": (
133            "The Authorization Server requires End-User interaction of some form to proceed"
134        ),
135        "login_required": "The Authorization Server requires End-User authentication",
136        "account_selection_required": (
137            "The End-User is required to select a session at the Authorization Server"
138        ),
139        "consent_required": "The Authorization Server requires End-User consent",
140        "invalid_request_uri": (
141            "The request_uri in the Authorization Request returns an error or contains invalid data"
142        ),
143        "invalid_request_object": "The request parameter contains an invalid Request Object",
144        "request_not_supported": "The provider does not support use of the request parameter",
145        "request_uri_not_supported": (
146            "The provider does not support use of the request_uri parameter"
147        ),
148        "registration_not_supported": (
149            "The provider does not support use of the registration parameter"
150        ),
151    }
152
153    def __init__(
154        self,
155        redirect_uri: str,
156        error: str,
157        grant_type: str,
158        state: str | None,
159        response_mode: str | None = None,
160        description: str | None = None,
161    ):
162        super().__init__()
163        self.error = error
164        if description:
165            self.description = description
166        else:
167            self.description = self.errors[error]
168        self.redirect_uri = redirect_uri
169        self.grant_type = grant_type
170        self.state = state
171        self.response_mode = response_mode
172
173    def get_response(self, request: HttpRequest) -> HttpResponse:
174        """Return a valid HTTP Response carrying the error to the client, using the response mode
175        requested by the client. Falls back to a generic error page when we don't have a valid
176        redirect URI to return the error to."""
177        # Without a valid redirect URI we can't return the error to the client
178        if urlparse(self.redirect_uri).scheme == "":
179            return bad_request_message(request, self.description, title=self.error)
180        # When the client requested the form_post response mode, errors must also be returned via
181        # an auto-submitting form POST to the redirect URI.
182        # See https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
183        if self.response_mode == ResponseMode.FORM_POST:
184            attrs = {"error": self.error, "error_description": self.description}
185            if self.state is not None:
186                attrs["state"] = self.state
187            return TemplateResponse(
188                request,
189                "if/oauth_form_post.html",
190                {"redirect_uri": self.redirect_uri, "attrs": attrs},
191            )
192        # Deferred import, utils imports BearerTokenError from this module
193        from authentik.providers.oauth2.utils import HttpResponseRedirectScheme
194
195        # Like OAuthFulfillmentStage, allow the redirect URI's own scheme so that native apps
196        # with a private-use scheme (RFC 8252) get the error instead of a bare 400.
197        # The redirect URI is already validated against the provider when this is raised.
198        return HttpResponseRedirectScheme(
199            self.create_uri(), allowed_schemes=[urlparse(self.redirect_uri).scheme]
200        )
201
202    def create_uri(self) -> str:
203        """Get a redirect URI with the error message"""
204        uri = urlsplit(self.redirect_uri)
205        response_mode = self.response_mode
206        if response_mode not in ResponseMode.values:
207            response_mode = (
208                ResponseMode.FRAGMENT
209                if self.grant_type in [GrantType.IMPLICIT, GrantType.HYBRID]
210                else ResponseMode.QUERY
211            )
212
213        params = {"error": self.error, "error_description": str(self.description)}
214        if self.state is not None:
215            params["state"] = self.state
216
217        encoded = urlencode(params, quote_via=quote)
218        if response_mode == ResponseMode.FRAGMENT:
219            return urlunsplit(uri._replace(fragment=encoded))
220        # Preserve the callback query, including its original encoding.
221        query = f"{uri.query}&{encoded}" if uri.query else encoded
222        return urlunsplit(uri._replace(query=query))
223
224
225class TokenError(OAuth2Error):
226    """
227    OAuth2 token endpoint errors.
228    https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
229    """
230
231    errors = {
232        "invalid_request": "The request is otherwise malformed",
233        "invalid_client": (
234            "Client authentication failed (e.g., unknown client, no client authentication "
235            "included, or unsupported authentication method)"
236        ),
237        "invalid_grant": (
238            "The provided authorization grant or refresh token is invalid, expired, revoked, "
239            "does not match the redirection URI used in the authorization request, "
240            "or was issued to another client"
241        ),
242        "unauthorized_client": (
243            "The authenticated client is not authorized to use this authorization grant type"
244        ),
245        "unsupported_grant_type": (
246            "The authorization grant type is not supported by the authorization server"
247        ),
248        "invalid_scope": (
249            "The requested scope is invalid, unknown, malformed, or exceeds the scope "
250            "granted by the resource owner"
251        ),
252        # https://datatracker.ietf.org/doc/html/rfc9449#section-5
253        "invalid_dpop_proof": "The DPoP proof is invalid",
254    }
255
256    def __init__(self, error: str):
257        super().__init__()
258        self.error = error
259        self.description = self.errors[error]
260
261
262class TokenExchangeError(TokenError):
263    """
264    Token exchange errors
265    See https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.2
266    Can also use codes from TokenError
267    """
268
269    errors = TokenError.errors | {
270        "invalid_target": (
271            "The authorization server is unable to issue a token for the target service "
272            "indicated by the 'resource' or 'audience' parameter"
273        ),
274    }
275
276    def __init__(self, error: str):
277        super().__init__(error)
278        self.error = error
279        self.description = self.errors[error]
280
281
282class TokenRevocationError(OAuth2Error):
283    """
284    Specific to the revocation endpoint.
285    See https://datatracker.ietf.org/doc/html/rfc7662
286    """
287
288    errors = TokenError.errors | {
289        "unsupported_token_type": (
290            "The authorization server does not support the revocation of the presented "
291            "token type.  That is, the client tried to revoke an access token on a server not"
292            "supporting this feature."
293        )
294    }
295
296    def __init__(self, error: str):
297        super().__init__()
298        self.error = error
299        self.description = self.errors[error]
300
301
302class DeviceCodeError(TokenError):
303    """
304    Device-code flow errors
305    See https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
306    Can also use codes form TokenError
307    """
308
309    errors = TokenError.errors | {
310        "authorization_pending": (
311            "The authorization request is still pending as the end user hasn't "
312            "yet completed the user-interaction steps"
313        ),
314        "access_denied": "The authorization request was denied.",
315        "expired_token": (
316            'The "device_code" has expired, and the device authorization '
317            "session has concluded.  The client MAY commence a new device "
318            "authorization request but SHOULD wait for user interaction before "
319            "restarting to avoid unnecessary polling."
320        ),
321        "slow_down": (
322            'A variant of "authorization_pending", the authorization request is'
323            "still pending and polling should continue, but the interval MUST"
324            "be increased by 5 seconds for this and all subsequent requests."
325        ),
326        "invalid_dpop_jkt": (
327            'The "dpop_jkt" parameter is not a valid base64url-encoded SHA-256 JWK thumbprint'
328        ),
329        "dpop_jkt_required": (
330            'The "dpop_jkt" parameter is required when the "bound_key" scope is requested'
331        ),
332        "dpop_jkt_not_allowed": (
333            'The "dpop_jkt" parameter must not be set unless the "bound_key" scope is requested'
334        ),
335    }
336
337    def __init__(self, error: str):
338        super().__init__(error)
339        self.error = error
340        self.description = self.errors[error]
341
342
343class BearerTokenError(OAuth2Error):
344    """
345    OAuth2 errors.
346    https://datatracker.ietf.org/doc/html/rfc6750#section-3.1
347    """
348
349    errors = {
350        "invalid_request": ("The request is otherwise malformed", 400),
351        "invalid_token": (
352            (
353                "The access token provided is expired, revoked, malformed, "
354                "or invalid for other reasons"
355            ),
356            401,
357        ),
358        "insufficient_scope": (
359            "The request requires higher privileges than provided by the access token",
360            403,
361        ),
362    }
363
364    def __init__(self, code):
365        super().__init__()
366        self.code = code
367        error_tuple = self.errors.get(code, ("", ""))
368        self.description = error_tuple[0]
369        self.status = error_tuple[1]
15class OAuth2Error(TracingIgnoredException):
16    """Base class for all OAuth2 Errors"""
17
18    error: str
19    description: str
20    cause: str | None = None
21
22    def create_dict(self, request: HttpRequest):
23        """Return error as dict for JSON Rendering"""
24        return {
25            "error": self.error,
26            "error_description": self.description,
27            "request_id": request.request_id,
28        }
29
30    def __repr__(self) -> str:
31        return self.error
32
33    def to_event(self, message: str | None = None, **kwargs) -> Event:
34        """Create configuration_error Event."""
35        return Event.new(
36            EventAction.CONFIGURATION_ERROR,
37            message=message or self.description,
38            cause=self.cause,
39            error=self.error,
40            **kwargs,
41        )
42
43    def with_cause(self, cause: str):
44        self.cause = cause
45        return self

Base class for all OAuth2 Errors

error: str
description: str
cause: str | None = None
def create_dict(self, request: django.http.request.HttpRequest):
22    def create_dict(self, request: HttpRequest):
23        """Return error as dict for JSON Rendering"""
24        return {
25            "error": self.error,
26            "error_description": self.description,
27            "request_id": request.request_id,
28        }

Return error as dict for JSON Rendering

def to_event( self, message: str | None = None, **kwargs) -> authentik.events.models.Event:
33    def to_event(self, message: str | None = None, **kwargs) -> Event:
34        """Create configuration_error Event."""
35        return Event.new(
36            EventAction.CONFIGURATION_ERROR,
37            message=message or self.description,
38            cause=self.cause,
39            error=self.error,
40            **kwargs,
41        )

Create configuration_error Event.

def with_cause(self, cause: str):
43    def with_cause(self, cause: str):
44        self.cause = cause
45        return self
class RedirectUriError(OAuth2Error):
48class RedirectUriError(OAuth2Error):
49    """The request fails due to a missing, invalid, or mismatching
50    redirection URI (redirect_uri)."""
51
52    error = "Redirect URI Error"
53    description = (
54        "The request fails due to a missing, invalid, or mismatching "
55        "redirection URI (redirect_uri)."
56    )
57
58    provided_uri: str
59    allowed_uris: list[RedirectURI]
60
61    def __init__(self, provided_uri: str, allowed_uris: list[RedirectURI]) -> None:
62        super().__init__()
63        self.provided_uri = provided_uri
64        self.allowed_uris = allowed_uris
65
66    def to_event(self, **kwargs) -> Event:
67        return super().to_event(
68            (
69                f"Invalid redirect URI was used. Client used '{self.provided_uri}'. "
70                f"Allowed redirect URIs are {','.join(self.allowed_uris)}"
71            ),
72            **kwargs,
73        )

The request fails due to a missing, invalid, or mismatching redirection URI (redirect_uri).

RedirectUriError( provided_uri: str, allowed_uris: list[authentik.providers.oauth2.models.RedirectURI])
61    def __init__(self, provided_uri: str, allowed_uris: list[RedirectURI]) -> None:
62        super().__init__()
63        self.provided_uri = provided_uri
64        self.allowed_uris = allowed_uris
error = 'Redirect URI Error'
description = 'The request fails due to a missing, invalid, or mismatching redirection URI (redirect_uri).'
provided_uri: str
def to_event(self, **kwargs) -> authentik.events.models.Event:
66    def to_event(self, **kwargs) -> Event:
67        return super().to_event(
68            (
69                f"Invalid redirect URI was used. Client used '{self.provided_uri}'. "
70                f"Allowed redirect URIs are {','.join(self.allowed_uris)}"
71            ),
72            **kwargs,
73        )

Create configuration_error Event.

class ClientIdError(OAuth2Error):
76class ClientIdError(OAuth2Error):
77    """The client identifier (client_id) is missing or invalid."""
78
79    error = "Client ID Error"
80    description = "The client identifier (client_id) is missing or invalid."
81
82    client_id: str
83
84    def __init__(self, client_id: str) -> None:
85        super().__init__()
86        self.client_id = client_id
87
88    def to_event(self, **kwargs) -> Event:
89        return super().to_event(f"Invalid client identifier: {self.client_id}.", **kwargs)

The client identifier (client_id) is missing or invalid.

ClientIdError(client_id: str)
84    def __init__(self, client_id: str) -> None:
85        super().__init__()
86        self.client_id = client_id
error = 'Client ID Error'
description = 'The client identifier (client_id) is missing or invalid.'
client_id: str
def to_event(self, **kwargs) -> authentik.events.models.Event:
88    def to_event(self, **kwargs) -> Event:
89        return super().to_event(f"Invalid client identifier: {self.client_id}.", **kwargs)

Create configuration_error Event.

class UserAuthError(OAuth2Error):
92class UserAuthError(OAuth2Error):
93    """
94    Specific to the Resource Owner Password Credentials flow when
95    the Resource Owners credentials are not valid.
96    """
97
98    error = "access_denied"
99    description = "The resource owner or authorization server denied the request."

Specific to the Resource Owner Password Credentials flow when the Resource Owners credentials are not valid.

error = 'access_denied'
description = 'The resource owner or authorization server denied the request.'
class TokenIntrospectionError(OAuth2Error):
102class TokenIntrospectionError(OAuth2Error):
103    """
104    Specific to the introspection endpoint. This error will be converted
105    to an "active: false" response, as per the spec.
106    See https://datatracker.ietf.org/doc/html/rfc7662
107    """

Specific to the introspection endpoint. This error will be converted to an "active: false" response, as per the spec. See https://datatracker.ietf.org/doc/html/rfc7662

class AuthorizeError(OAuth2Error):
110class AuthorizeError(OAuth2Error):
111    """General Authorization Errors"""
112
113    errors = {
114        # OAuth2 errors.
115        # https://datatracker.ietf.org/doc/html/rfc6749#section-4.1.2.1
116        "invalid_request": "The request is otherwise malformed",
117        "unauthorized_client": (
118            "The client is not authorized to request an authorization code using this method"
119        ),
120        "access_denied": "The resource owner or authorization server denied the request",
121        "unsupported_response_type": (
122            "The authorization server does not support obtaining an authorization code "
123            "using this method"
124        ),
125        "invalid_scope": "The requested scope is invalid, unknown, or malformed",
126        "server_error": "The authorization server encountered an error",
127        "temporarily_unavailable": (
128            "The authorization server is currently unable to handle the request due to a "
129            "temporary overloading or maintenance of the server"
130        ),
131        # OpenID errors.
132        # http://openid.net/specs/openid-connect-core-1_0.html#AuthError
133        "interaction_required": (
134            "The Authorization Server requires End-User interaction of some form to proceed"
135        ),
136        "login_required": "The Authorization Server requires End-User authentication",
137        "account_selection_required": (
138            "The End-User is required to select a session at the Authorization Server"
139        ),
140        "consent_required": "The Authorization Server requires End-User consent",
141        "invalid_request_uri": (
142            "The request_uri in the Authorization Request returns an error or contains invalid data"
143        ),
144        "invalid_request_object": "The request parameter contains an invalid Request Object",
145        "request_not_supported": "The provider does not support use of the request parameter",
146        "request_uri_not_supported": (
147            "The provider does not support use of the request_uri parameter"
148        ),
149        "registration_not_supported": (
150            "The provider does not support use of the registration parameter"
151        ),
152    }
153
154    def __init__(
155        self,
156        redirect_uri: str,
157        error: str,
158        grant_type: str,
159        state: str | None,
160        response_mode: str | None = None,
161        description: str | None = None,
162    ):
163        super().__init__()
164        self.error = error
165        if description:
166            self.description = description
167        else:
168            self.description = self.errors[error]
169        self.redirect_uri = redirect_uri
170        self.grant_type = grant_type
171        self.state = state
172        self.response_mode = response_mode
173
174    def get_response(self, request: HttpRequest) -> HttpResponse:
175        """Return a valid HTTP Response carrying the error to the client, using the response mode
176        requested by the client. Falls back to a generic error page when we don't have a valid
177        redirect URI to return the error to."""
178        # Without a valid redirect URI we can't return the error to the client
179        if urlparse(self.redirect_uri).scheme == "":
180            return bad_request_message(request, self.description, title=self.error)
181        # When the client requested the form_post response mode, errors must also be returned via
182        # an auto-submitting form POST to the redirect URI.
183        # See https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
184        if self.response_mode == ResponseMode.FORM_POST:
185            attrs = {"error": self.error, "error_description": self.description}
186            if self.state is not None:
187                attrs["state"] = self.state
188            return TemplateResponse(
189                request,
190                "if/oauth_form_post.html",
191                {"redirect_uri": self.redirect_uri, "attrs": attrs},
192            )
193        # Deferred import, utils imports BearerTokenError from this module
194        from authentik.providers.oauth2.utils import HttpResponseRedirectScheme
195
196        # Like OAuthFulfillmentStage, allow the redirect URI's own scheme so that native apps
197        # with a private-use scheme (RFC 8252) get the error instead of a bare 400.
198        # The redirect URI is already validated against the provider when this is raised.
199        return HttpResponseRedirectScheme(
200            self.create_uri(), allowed_schemes=[urlparse(self.redirect_uri).scheme]
201        )
202
203    def create_uri(self) -> str:
204        """Get a redirect URI with the error message"""
205        uri = urlsplit(self.redirect_uri)
206        response_mode = self.response_mode
207        if response_mode not in ResponseMode.values:
208            response_mode = (
209                ResponseMode.FRAGMENT
210                if self.grant_type in [GrantType.IMPLICIT, GrantType.HYBRID]
211                else ResponseMode.QUERY
212            )
213
214        params = {"error": self.error, "error_description": str(self.description)}
215        if self.state is not None:
216            params["state"] = self.state
217
218        encoded = urlencode(params, quote_via=quote)
219        if response_mode == ResponseMode.FRAGMENT:
220            return urlunsplit(uri._replace(fragment=encoded))
221        # Preserve the callback query, including its original encoding.
222        query = f"{uri.query}&{encoded}" if uri.query else encoded
223        return urlunsplit(uri._replace(query=query))

General Authorization Errors

AuthorizeError( redirect_uri: str, error: str, grant_type: str, state: str | None, response_mode: str | None = None, description: str | None = None)
154    def __init__(
155        self,
156        redirect_uri: str,
157        error: str,
158        grant_type: str,
159        state: str | None,
160        response_mode: str | None = None,
161        description: str | None = None,
162    ):
163        super().__init__()
164        self.error = error
165        if description:
166            self.description = description
167        else:
168            self.description = self.errors[error]
169        self.redirect_uri = redirect_uri
170        self.grant_type = grant_type
171        self.state = state
172        self.response_mode = response_mode
errors = {'invalid_request': 'The request is otherwise malformed', 'unauthorized_client': 'The client is not authorized to request an authorization code using this method', 'access_denied': 'The resource owner or authorization server denied the request', 'unsupported_response_type': 'The authorization server does not support obtaining an authorization code using this method', 'invalid_scope': 'The requested scope is invalid, unknown, or malformed', 'server_error': 'The authorization server encountered an error', 'temporarily_unavailable': 'The authorization server is currently unable to handle the request due to a temporary overloading or maintenance of the server', 'interaction_required': 'The Authorization Server requires End-User interaction of some form to proceed', 'login_required': 'The Authorization Server requires End-User authentication', 'account_selection_required': 'The End-User is required to select a session at the Authorization Server', 'consent_required': 'The Authorization Server requires End-User consent', 'invalid_request_uri': 'The request_uri in the Authorization Request returns an error or contains invalid data', 'invalid_request_object': 'The request parameter contains an invalid Request Object', 'request_not_supported': 'The provider does not support use of the request parameter', 'request_uri_not_supported': 'The provider does not support use of the request_uri parameter', 'registration_not_supported': 'The provider does not support use of the registration parameter'}
error
redirect_uri
grant_type
state
response_mode
def get_response( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
174    def get_response(self, request: HttpRequest) -> HttpResponse:
175        """Return a valid HTTP Response carrying the error to the client, using the response mode
176        requested by the client. Falls back to a generic error page when we don't have a valid
177        redirect URI to return the error to."""
178        # Without a valid redirect URI we can't return the error to the client
179        if urlparse(self.redirect_uri).scheme == "":
180            return bad_request_message(request, self.description, title=self.error)
181        # When the client requested the form_post response mode, errors must also be returned via
182        # an auto-submitting form POST to the redirect URI.
183        # See https://openid.net/specs/oauth-v2-form-post-response-mode-1_0.html
184        if self.response_mode == ResponseMode.FORM_POST:
185            attrs = {"error": self.error, "error_description": self.description}
186            if self.state is not None:
187                attrs["state"] = self.state
188            return TemplateResponse(
189                request,
190                "if/oauth_form_post.html",
191                {"redirect_uri": self.redirect_uri, "attrs": attrs},
192            )
193        # Deferred import, utils imports BearerTokenError from this module
194        from authentik.providers.oauth2.utils import HttpResponseRedirectScheme
195
196        # Like OAuthFulfillmentStage, allow the redirect URI's own scheme so that native apps
197        # with a private-use scheme (RFC 8252) get the error instead of a bare 400.
198        # The redirect URI is already validated against the provider when this is raised.
199        return HttpResponseRedirectScheme(
200            self.create_uri(), allowed_schemes=[urlparse(self.redirect_uri).scheme]
201        )

Return a valid HTTP Response carrying the error to the client, using the response mode requested by the client. Falls back to a generic error page when we don't have a valid redirect URI to return the error to.

def create_uri(self) -> str:
203    def create_uri(self) -> str:
204        """Get a redirect URI with the error message"""
205        uri = urlsplit(self.redirect_uri)
206        response_mode = self.response_mode
207        if response_mode not in ResponseMode.values:
208            response_mode = (
209                ResponseMode.FRAGMENT
210                if self.grant_type in [GrantType.IMPLICIT, GrantType.HYBRID]
211                else ResponseMode.QUERY
212            )
213
214        params = {"error": self.error, "error_description": str(self.description)}
215        if self.state is not None:
216            params["state"] = self.state
217
218        encoded = urlencode(params, quote_via=quote)
219        if response_mode == ResponseMode.FRAGMENT:
220            return urlunsplit(uri._replace(fragment=encoded))
221        # Preserve the callback query, including its original encoding.
222        query = f"{uri.query}&{encoded}" if uri.query else encoded
223        return urlunsplit(uri._replace(query=query))

Get a redirect URI with the error message

class TokenError(OAuth2Error):
226class TokenError(OAuth2Error):
227    """
228    OAuth2 token endpoint errors.
229    https://datatracker.ietf.org/doc/html/rfc6749#section-5.2
230    """
231
232    errors = {
233        "invalid_request": "The request is otherwise malformed",
234        "invalid_client": (
235            "Client authentication failed (e.g., unknown client, no client authentication "
236            "included, or unsupported authentication method)"
237        ),
238        "invalid_grant": (
239            "The provided authorization grant or refresh token is invalid, expired, revoked, "
240            "does not match the redirection URI used in the authorization request, "
241            "or was issued to another client"
242        ),
243        "unauthorized_client": (
244            "The authenticated client is not authorized to use this authorization grant type"
245        ),
246        "unsupported_grant_type": (
247            "The authorization grant type is not supported by the authorization server"
248        ),
249        "invalid_scope": (
250            "The requested scope is invalid, unknown, malformed, or exceeds the scope "
251            "granted by the resource owner"
252        ),
253        # https://datatracker.ietf.org/doc/html/rfc9449#section-5
254        "invalid_dpop_proof": "The DPoP proof is invalid",
255    }
256
257    def __init__(self, error: str):
258        super().__init__()
259        self.error = error
260        self.description = self.errors[error]
TokenError(error: str)
257    def __init__(self, error: str):
258        super().__init__()
259        self.error = error
260        self.description = self.errors[error]
errors = {'invalid_request': 'The request is otherwise malformed', 'invalid_client': 'Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)', 'invalid_grant': 'The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client', 'unauthorized_client': 'The authenticated client is not authorized to use this authorization grant type', 'unsupported_grant_type': 'The authorization grant type is not supported by the authorization server', 'invalid_scope': 'The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner', 'invalid_dpop_proof': 'The DPoP proof is invalid'}
error
description
class TokenExchangeError(TokenError):
263class TokenExchangeError(TokenError):
264    """
265    Token exchange errors
266    See https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.2
267    Can also use codes from TokenError
268    """
269
270    errors = TokenError.errors | {
271        "invalid_target": (
272            "The authorization server is unable to issue a token for the target service "
273            "indicated by the 'resource' or 'audience' parameter"
274        ),
275    }
276
277    def __init__(self, error: str):
278        super().__init__(error)
279        self.error = error
280        self.description = self.errors[error]

Token exchange errors See https://datatracker.ietf.org/doc/html/rfc8693#section-2.2.2 Can also use codes from TokenError

TokenExchangeError(error: str)
277    def __init__(self, error: str):
278        super().__init__(error)
279        self.error = error
280        self.description = self.errors[error]
errors = {'invalid_request': 'The request is otherwise malformed', 'invalid_client': 'Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)', 'invalid_grant': 'The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client', 'unauthorized_client': 'The authenticated client is not authorized to use this authorization grant type', 'unsupported_grant_type': 'The authorization grant type is not supported by the authorization server', 'invalid_scope': 'The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner', 'invalid_dpop_proof': 'The DPoP proof is invalid', 'invalid_target': "The authorization server is unable to issue a token for the target service indicated by the 'resource' or 'audience' parameter"}
error
description
class TokenRevocationError(OAuth2Error):
283class TokenRevocationError(OAuth2Error):
284    """
285    Specific to the revocation endpoint.
286    See https://datatracker.ietf.org/doc/html/rfc7662
287    """
288
289    errors = TokenError.errors | {
290        "unsupported_token_type": (
291            "The authorization server does not support the revocation of the presented "
292            "token type.  That is, the client tried to revoke an access token on a server not"
293            "supporting this feature."
294        )
295    }
296
297    def __init__(self, error: str):
298        super().__init__()
299        self.error = error
300        self.description = self.errors[error]

Specific to the revocation endpoint. See https://datatracker.ietf.org/doc/html/rfc7662

TokenRevocationError(error: str)
297    def __init__(self, error: str):
298        super().__init__()
299        self.error = error
300        self.description = self.errors[error]
errors = {'invalid_request': 'The request is otherwise malformed', 'invalid_client': 'Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)', 'invalid_grant': 'The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client', 'unauthorized_client': 'The authenticated client is not authorized to use this authorization grant type', 'unsupported_grant_type': 'The authorization grant type is not supported by the authorization server', 'invalid_scope': 'The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner', 'invalid_dpop_proof': 'The DPoP proof is invalid', 'unsupported_token_type': 'The authorization server does not support the revocation of the presented token type. That is, the client tried to revoke an access token on a server notsupporting this feature.'}
error
description
class DeviceCodeError(TokenError):
303class DeviceCodeError(TokenError):
304    """
305    Device-code flow errors
306    See https://datatracker.ietf.org/doc/html/rfc8628#section-3.2
307    Can also use codes form TokenError
308    """
309
310    errors = TokenError.errors | {
311        "authorization_pending": (
312            "The authorization request is still pending as the end user hasn't "
313            "yet completed the user-interaction steps"
314        ),
315        "access_denied": "The authorization request was denied.",
316        "expired_token": (
317            'The "device_code" has expired, and the device authorization '
318            "session has concluded.  The client MAY commence a new device "
319            "authorization request but SHOULD wait for user interaction before "
320            "restarting to avoid unnecessary polling."
321        ),
322        "slow_down": (
323            'A variant of "authorization_pending", the authorization request is'
324            "still pending and polling should continue, but the interval MUST"
325            "be increased by 5 seconds for this and all subsequent requests."
326        ),
327        "invalid_dpop_jkt": (
328            'The "dpop_jkt" parameter is not a valid base64url-encoded SHA-256 JWK thumbprint'
329        ),
330        "dpop_jkt_required": (
331            'The "dpop_jkt" parameter is required when the "bound_key" scope is requested'
332        ),
333        "dpop_jkt_not_allowed": (
334            'The "dpop_jkt" parameter must not be set unless the "bound_key" scope is requested'
335        ),
336    }
337
338    def __init__(self, error: str):
339        super().__init__(error)
340        self.error = error
341        self.description = self.errors[error]

Device-code flow errors See https://datatracker.ietf.org/doc/html/rfc8628#section-3.2 Can also use codes form TokenError

DeviceCodeError(error: str)
338    def __init__(self, error: str):
339        super().__init__(error)
340        self.error = error
341        self.description = self.errors[error]
errors = {'invalid_request': 'The request is otherwise malformed', 'invalid_client': 'Client authentication failed (e.g., unknown client, no client authentication included, or unsupported authentication method)', 'invalid_grant': 'The provided authorization grant or refresh token is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client', 'unauthorized_client': 'The authenticated client is not authorized to use this authorization grant type', 'unsupported_grant_type': 'The authorization grant type is not supported by the authorization server', 'invalid_scope': 'The requested scope is invalid, unknown, malformed, or exceeds the scope granted by the resource owner', 'invalid_dpop_proof': 'The DPoP proof is invalid', 'authorization_pending': "The authorization request is still pending as the end user hasn't yet completed the user-interaction steps", 'access_denied': 'The authorization request was denied.', 'expired_token': 'The "device_code" has expired, and the device authorization session has concluded. The client MAY commence a new device authorization request but SHOULD wait for user interaction before restarting to avoid unnecessary polling.', 'slow_down': 'A variant of "authorization_pending", the authorization request isstill pending and polling should continue, but the interval MUSTbe increased by 5 seconds for this and all subsequent requests.', 'invalid_dpop_jkt': 'The "dpop_jkt" parameter is not a valid base64url-encoded SHA-256 JWK thumbprint', 'dpop_jkt_required': 'The "dpop_jkt" parameter is required when the "bound_key" scope is requested', 'dpop_jkt_not_allowed': 'The "dpop_jkt" parameter must not be set unless the "bound_key" scope is requested'}
error
description
class BearerTokenError(OAuth2Error):
344class BearerTokenError(OAuth2Error):
345    """
346    OAuth2 errors.
347    https://datatracker.ietf.org/doc/html/rfc6750#section-3.1
348    """
349
350    errors = {
351        "invalid_request": ("The request is otherwise malformed", 400),
352        "invalid_token": (
353            (
354                "The access token provided is expired, revoked, malformed, "
355                "or invalid for other reasons"
356            ),
357            401,
358        ),
359        "insufficient_scope": (
360            "The request requires higher privileges than provided by the access token",
361            403,
362        ),
363    }
364
365    def __init__(self, code):
366        super().__init__()
367        self.code = code
368        error_tuple = self.errors.get(code, ("", ""))
369        self.description = error_tuple[0]
370        self.status = error_tuple[1]
BearerTokenError(code)
365    def __init__(self, code):
366        super().__init__()
367        self.code = code
368        error_tuple = self.errors.get(code, ("", ""))
369        self.description = error_tuple[0]
370        self.status = error_tuple[1]
errors = {'invalid_request': ('The request is otherwise malformed', 400), 'invalid_token': ('The access token provided is expired, revoked, malformed, or invalid for other reasons', 401), 'insufficient_scope': ('The request requires higher privileges than provided by the access token', 403)}
code
description
status