authentik.api.authentication

API Authentication

  1"""API Authentication"""
  2
  3from hmac import compare_digest
  4from pathlib import Path
  5from tempfile import gettempdir
  6from typing import TYPE_CHECKING, Any
  7
  8from django.conf import settings
  9from django.contrib.auth.models import AnonymousUser
 10from drf_spectacular.extensions import OpenApiAuthenticationExtension
 11from rest_framework.authentication import BaseAuthentication, get_authorization_header
 12from rest_framework.exceptions import AuthenticationFailed
 13from rest_framework.request import Request
 14from structlog.stdlib import get_logger
 15
 16from authentik.common.oauth.constants import SCOPE_AUTHENTIK_API
 17from authentik.core.middleware import CTX_AUTH_VIA
 18from authentik.core.models import Token, TokenIntents, User, UserTypes
 19from authentik.lib.tracing import active_tracer
 20from authentik.outposts.models import Outpost
 21
 22if TYPE_CHECKING:
 23    from drf_spectacular.openapi import AutoSchema
 24
 25LOGGER = get_logger()
 26_tmp = Path(gettempdir())
 27try:
 28    with open(_tmp / "authentik-core-ipc.key") as _f:
 29        ipc_key = _f.read()
 30except OSError:
 31    ipc_key = None
 32
 33
 34def validate_auth(header: bytes, format="bearer") -> str | None:
 35    """Validate that the header is in a correct format,
 36    returns type and credentials"""
 37    auth_credentials = header.decode().strip()
 38    if auth_credentials == "" or " " not in auth_credentials:
 39        return None
 40    auth_type, _, auth_credentials = auth_credentials.partition(" ")
 41    if not compare_digest(auth_type.lower(), format):
 42        LOGGER.debug("Unsupported authentication type, denying", type=auth_type.lower())
 43        return None
 44    if auth_credentials == "":  # nosec # noqa
 45        raise AuthenticationFailed("Malformed header")
 46    return auth_credentials
 47
 48
 49class VirtualUser(AnonymousUser):
 50    is_active = True
 51
 52    @property
 53    def type(self):
 54        return UserTypes.INTERNAL_SERVICE_ACCOUNT
 55
 56    @property
 57    def is_anonymous(self):
 58        return False
 59
 60    @property
 61    def is_authenticated(self):
 62        return True
 63
 64    def all_roles(self):
 65        return []
 66
 67
 68class IPCUser(VirtualUser):
 69    """'Virtual' user for IPC communication between authentik core and the authentik router"""
 70
 71    username = "authentik:system"
 72    is_superuser = True
 73
 74    @property
 75    def type(self):
 76        return UserTypes.INTERNAL_SERVICE_ACCOUNT
 77
 78    def has_perm(self, perm, obj=None):
 79        return True
 80
 81    def has_perms(self, perm_list, obj=None):
 82        return True
 83
 84    def has_module_perms(self, module):
 85        return True
 86
 87
 88class TokenAuthentication(BaseAuthentication):
 89    """Token-based authentication using HTTP Bearer authentication"""
 90
 91    @active_tracer().instrument()
 92    def authenticate(self, request: Request) -> tuple[User, Any] | None:
 93        """Token-based authentication using HTTP Bearer authentication"""
 94        auth = get_authorization_header(request)
 95
 96        user_ctx = self.bearer_auth(auth)
 97        # None is only returned when the header isn't set.
 98        if not user_ctx:
 99            return None
100
101        return user_ctx
102
103    def bearer_auth(self, raw_header: bytes) -> tuple[User, Any] | None:
104        """raw_header in the Format of `Bearer ....`"""
105        user_ctx = self.auth_user_lookup(raw_header)
106        if not user_ctx:
107            return None
108        user, ctx = user_ctx
109        if not user.is_active:
110            raise AuthenticationFailed("Token invalid/expired")
111        return user, ctx
112
113    def auth_user_lookup(self, raw_header: bytes) -> tuple[User, Any] | None:
114        """raw_header in the Format of `Bearer ....`"""
115        from authentik.providers.oauth2.models import AccessToken
116
117        auth_credentials = validate_auth(raw_header)
118        if not auth_credentials:
119            return None
120        # first, check traditional tokens
121        key_token = Token.objects.filter(
122            key=auth_credentials, intent=TokenIntents.INTENT_API
123        ).first()
124        if key_token:
125            CTX_AUTH_VIA.set("api_token")
126            return key_token.user, key_token
127        # then try to auth via JWT
128        jwt_token = AccessToken.objects.filter(
129            token=auth_credentials, _scope__icontains=SCOPE_AUTHENTIK_API
130        ).first()
131        if jwt_token:
132            # Double-check scopes, since they are saved in a single string
133            # we want to check the parsed version too
134            if SCOPE_AUTHENTIK_API not in jwt_token.scope:
135                raise AuthenticationFailed("Token invalid/expired")
136            CTX_AUTH_VIA.set("jwt")
137            return jwt_token.user, jwt_token
138        # then try to auth via secret key (for embedded outpost/etc)
139        user_outpost = self.token_secret_key(auth_credentials)
140        if user_outpost:
141            CTX_AUTH_VIA.set("secret_key")
142            return user_outpost
143        # then try to auth via secret key (for embedded outpost/etc)
144        user = self.token_ipc(auth_credentials)
145        if user:
146            CTX_AUTH_VIA.set("ipc")
147            return user
148        raise AuthenticationFailed("Token invalid/expired")
149
150    def token_ipc(self, value: str) -> tuple[User, None] | None:
151        """Check if the token is the secret key
152        and return the service account for the managed outpost"""
153        if not ipc_key or not compare_digest(value, ipc_key):
154            return None
155        return IPCUser(), None
156
157    def token_secret_key(self, value: str) -> tuple[User, Outpost] | None:
158        """Check if the token is the secret key
159        and return the service account for the managed outpost"""
160        from authentik.outposts.apps import MANAGED_OUTPOST
161
162        if not compare_digest(value, settings.SECRET_KEY):
163            return None
164        outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
165        if not outposts:
166            return None
167        outpost = outposts.first()
168        return outpost.user, outpost
169
170
171class TokenSchema(OpenApiAuthenticationExtension):
172    """Auth schema"""
173
174    target_class = TokenAuthentication
175    name = "authentik"
176
177    def get_security_definition(self, auto_schema: AutoSchema):
178        """Auth schema"""
179        return {"type": "http", "scheme": "bearer"}
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
def validate_auth(header: bytes, format='bearer') -> str | None:
35def validate_auth(header: bytes, format="bearer") -> str | None:
36    """Validate that the header is in a correct format,
37    returns type and credentials"""
38    auth_credentials = header.decode().strip()
39    if auth_credentials == "" or " " not in auth_credentials:
40        return None
41    auth_type, _, auth_credentials = auth_credentials.partition(" ")
42    if not compare_digest(auth_type.lower(), format):
43        LOGGER.debug("Unsupported authentication type, denying", type=auth_type.lower())
44        return None
45    if auth_credentials == "":  # nosec # noqa
46        raise AuthenticationFailed("Malformed header")
47    return auth_credentials

Validate that the header is in a correct format, returns type and credentials

class VirtualUser(django.contrib.auth.models.AnonymousUser):
50class VirtualUser(AnonymousUser):
51    is_active = True
52
53    @property
54    def type(self):
55        return UserTypes.INTERNAL_SERVICE_ACCOUNT
56
57    @property
58    def is_anonymous(self):
59        return False
60
61    @property
62    def is_authenticated(self):
63        return True
64
65    def all_roles(self):
66        return []
is_active = True
type
53    @property
54    def type(self):
55        return UserTypes.INTERNAL_SERVICE_ACCOUNT
is_anonymous
57    @property
58    def is_anonymous(self):
59        return False
is_authenticated
61    @property
62    def is_authenticated(self):
63        return True
def all_roles(self):
65    def all_roles(self):
66        return []
class IPCUser(VirtualUser):
69class IPCUser(VirtualUser):
70    """'Virtual' user for IPC communication between authentik core and the authentik router"""
71
72    username = "authentik:system"
73    is_superuser = True
74
75    @property
76    def type(self):
77        return UserTypes.INTERNAL_SERVICE_ACCOUNT
78
79    def has_perm(self, perm, obj=None):
80        return True
81
82    def has_perms(self, perm_list, obj=None):
83        return True
84
85    def has_module_perms(self, module):
86        return True

'Virtual' user for IPC communication between authentik core and the authentik router

username = 'authentik:system'
is_superuser = True
type
75    @property
76    def type(self):
77        return UserTypes.INTERNAL_SERVICE_ACCOUNT
def has_perm(self, perm, obj=None):
79    def has_perm(self, perm, obj=None):
80        return True
def has_perms(self, perm_list, obj=None):
82    def has_perms(self, perm_list, obj=None):
83        return True
def has_module_perms(self, module):
85    def has_module_perms(self, module):
86        return True
class TokenAuthentication(rest_framework.authentication.BaseAuthentication):
 89class TokenAuthentication(BaseAuthentication):
 90    """Token-based authentication using HTTP Bearer authentication"""
 91
 92    @active_tracer().instrument()
 93    def authenticate(self, request: Request) -> tuple[User, Any] | None:
 94        """Token-based authentication using HTTP Bearer authentication"""
 95        auth = get_authorization_header(request)
 96
 97        user_ctx = self.bearer_auth(auth)
 98        # None is only returned when the header isn't set.
 99        if not user_ctx:
100            return None
101
102        return user_ctx
103
104    def bearer_auth(self, raw_header: bytes) -> tuple[User, Any] | None:
105        """raw_header in the Format of `Bearer ....`"""
106        user_ctx = self.auth_user_lookup(raw_header)
107        if not user_ctx:
108            return None
109        user, ctx = user_ctx
110        if not user.is_active:
111            raise AuthenticationFailed("Token invalid/expired")
112        return user, ctx
113
114    def auth_user_lookup(self, raw_header: bytes) -> tuple[User, Any] | None:
115        """raw_header in the Format of `Bearer ....`"""
116        from authentik.providers.oauth2.models import AccessToken
117
118        auth_credentials = validate_auth(raw_header)
119        if not auth_credentials:
120            return None
121        # first, check traditional tokens
122        key_token = Token.objects.filter(
123            key=auth_credentials, intent=TokenIntents.INTENT_API
124        ).first()
125        if key_token:
126            CTX_AUTH_VIA.set("api_token")
127            return key_token.user, key_token
128        # then try to auth via JWT
129        jwt_token = AccessToken.objects.filter(
130            token=auth_credentials, _scope__icontains=SCOPE_AUTHENTIK_API
131        ).first()
132        if jwt_token:
133            # Double-check scopes, since they are saved in a single string
134            # we want to check the parsed version too
135            if SCOPE_AUTHENTIK_API not in jwt_token.scope:
136                raise AuthenticationFailed("Token invalid/expired")
137            CTX_AUTH_VIA.set("jwt")
138            return jwt_token.user, jwt_token
139        # then try to auth via secret key (for embedded outpost/etc)
140        user_outpost = self.token_secret_key(auth_credentials)
141        if user_outpost:
142            CTX_AUTH_VIA.set("secret_key")
143            return user_outpost
144        # then try to auth via secret key (for embedded outpost/etc)
145        user = self.token_ipc(auth_credentials)
146        if user:
147            CTX_AUTH_VIA.set("ipc")
148            return user
149        raise AuthenticationFailed("Token invalid/expired")
150
151    def token_ipc(self, value: str) -> tuple[User, None] | None:
152        """Check if the token is the secret key
153        and return the service account for the managed outpost"""
154        if not ipc_key or not compare_digest(value, ipc_key):
155            return None
156        return IPCUser(), None
157
158    def token_secret_key(self, value: str) -> tuple[User, Outpost] | None:
159        """Check if the token is the secret key
160        and return the service account for the managed outpost"""
161        from authentik.outposts.apps import MANAGED_OUTPOST
162
163        if not compare_digest(value, settings.SECRET_KEY):
164            return None
165        outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
166        if not outposts:
167            return None
168        outpost = outposts.first()
169        return outpost.user, outpost

Token-based authentication using HTTP Bearer authentication

@active_tracer().instrument()
def authenticate( self, request: rest_framework.request.Request) -> tuple[authentik.core.models.User, Any] | None:
 92    @active_tracer().instrument()
 93    def authenticate(self, request: Request) -> tuple[User, Any] | None:
 94        """Token-based authentication using HTTP Bearer authentication"""
 95        auth = get_authorization_header(request)
 96
 97        user_ctx = self.bearer_auth(auth)
 98        # None is only returned when the header isn't set.
 99        if not user_ctx:
100            return None
101
102        return user_ctx

Token-based authentication using HTTP Bearer authentication

def bearer_auth(self, raw_header: bytes) -> tuple[authentik.core.models.User, Any] | None:
104    def bearer_auth(self, raw_header: bytes) -> tuple[User, Any] | None:
105        """raw_header in the Format of `Bearer ....`"""
106        user_ctx = self.auth_user_lookup(raw_header)
107        if not user_ctx:
108            return None
109        user, ctx = user_ctx
110        if not user.is_active:
111            raise AuthenticationFailed("Token invalid/expired")
112        return user, ctx

raw_header in the Format of Bearer ....

def auth_user_lookup(self, raw_header: bytes) -> tuple[authentik.core.models.User, Any] | None:
114    def auth_user_lookup(self, raw_header: bytes) -> tuple[User, Any] | None:
115        """raw_header in the Format of `Bearer ....`"""
116        from authentik.providers.oauth2.models import AccessToken
117
118        auth_credentials = validate_auth(raw_header)
119        if not auth_credentials:
120            return None
121        # first, check traditional tokens
122        key_token = Token.objects.filter(
123            key=auth_credentials, intent=TokenIntents.INTENT_API
124        ).first()
125        if key_token:
126            CTX_AUTH_VIA.set("api_token")
127            return key_token.user, key_token
128        # then try to auth via JWT
129        jwt_token = AccessToken.objects.filter(
130            token=auth_credentials, _scope__icontains=SCOPE_AUTHENTIK_API
131        ).first()
132        if jwt_token:
133            # Double-check scopes, since they are saved in a single string
134            # we want to check the parsed version too
135            if SCOPE_AUTHENTIK_API not in jwt_token.scope:
136                raise AuthenticationFailed("Token invalid/expired")
137            CTX_AUTH_VIA.set("jwt")
138            return jwt_token.user, jwt_token
139        # then try to auth via secret key (for embedded outpost/etc)
140        user_outpost = self.token_secret_key(auth_credentials)
141        if user_outpost:
142            CTX_AUTH_VIA.set("secret_key")
143            return user_outpost
144        # then try to auth via secret key (for embedded outpost/etc)
145        user = self.token_ipc(auth_credentials)
146        if user:
147            CTX_AUTH_VIA.set("ipc")
148            return user
149        raise AuthenticationFailed("Token invalid/expired")

raw_header in the Format of Bearer ....

def token_ipc(self, value: str) -> tuple[authentik.core.models.User, None] | None:
151    def token_ipc(self, value: str) -> tuple[User, None] | None:
152        """Check if the token is the secret key
153        and return the service account for the managed outpost"""
154        if not ipc_key or not compare_digest(value, ipc_key):
155            return None
156        return IPCUser(), None

Check if the token is the secret key and return the service account for the managed outpost

def token_secret_key( self, value: str) -> tuple[authentik.core.models.User, authentik.outposts.models.Outpost] | None:
158    def token_secret_key(self, value: str) -> tuple[User, Outpost] | None:
159        """Check if the token is the secret key
160        and return the service account for the managed outpost"""
161        from authentik.outposts.apps import MANAGED_OUTPOST
162
163        if not compare_digest(value, settings.SECRET_KEY):
164            return None
165        outposts = Outpost.objects.filter(managed=MANAGED_OUTPOST)
166        if not outposts:
167            return None
168        outpost = outposts.first()
169        return outpost.user, outpost

Check if the token is the secret key and return the service account for the managed outpost

class TokenSchema(drf_spectacular.plumbing.OpenApiGeneratorExtension[ForwardRef('OpenApiAuthenticationExtension')]):
172class TokenSchema(OpenApiAuthenticationExtension):
173    """Auth schema"""
174
175    target_class = TokenAuthentication
176    name = "authentik"
177
178    def get_security_definition(self, auto_schema: AutoSchema):
179        """Auth schema"""
180        return {"type": "http", "scheme": "bearer"}

Auth schema

target_class = <class 'TokenAuthentication'>
name = $POSTGRES_USER
def get_security_definition(unknown):
178    def get_security_definition(self, auto_schema: AutoSchema):
179        """Auth schema"""
180        return {"type": "http", "scheme": "bearer"}

Auth schema