authentik.core.auth
Authenticate with tokens
1"""Authenticate with tokens""" 2 3from typing import Any 4 5from asgiref.sync import sync_to_async 6from django.contrib.auth.backends import ModelBackend 7from django.contrib.auth.hashers import make_password 8from django.http.request import HttpRequest 9 10from authentik.core.models import Token, TokenIntents, User 11from authentik.events.utils import cleanse_dict, sanitize_dict 12from authentik.flows.planner import FlowPlan 13from authentik.flows.views.executor import SESSION_KEY_PLAN 14from authentik.stages.password.stage import PLAN_CONTEXT_METHOD, PLAN_CONTEXT_METHOD_ARGS 15 16 17class ModelBackendNoAuthz(ModelBackend): 18 def get_user_permissions(self, user_obj, obj=None): 19 return set() 20 21 def get_group_permissions(self, user_obj, obj=None): 22 return set() 23 24 def get_all_permissions(self, user_obj, obj=None): 25 return set() 26 27 def has_perm(self, user_obj, perm, obj=None): 28 return False 29 30 def has_module_perms(self, user_obj, app_label): 31 return False 32 33 def with_perm(self, perm, is_active=True, include_superusers=True, obj=None): 34 return User.objects.none() 35 36 37class InbuiltBackend(ModelBackendNoAuthz): 38 """Inbuilt backend""" 39 40 def authenticate( 41 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 42 ) -> User | None: 43 if username is None or password is None: 44 return None 45 user = User.objects.select_related("password_device").filter(username=username).first() 46 device = getattr(user, "password_device", None) 47 if device is None: 48 # Hash once, so a missing user or password takes as long as a wrong password. 49 make_password(password) 50 return None 51 if not device.check_password(password) or not self.user_can_authenticate(user): 52 return None 53 self.set_method("password", request) 54 return user 55 56 async def aauthenticate( 57 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 58 ) -> User | None: 59 return await sync_to_async(self.authenticate)( 60 request, username=username, password=password, **kwargs 61 ) 62 63 def set_method(self, method: str, request: HttpRequest | None, **kwargs): 64 """Set method data on current flow, if possbiel""" 65 if not request: 66 return 67 # Since we can't directly pass other variables to signals, and we want to log the method 68 # and the token used, we assume we're running in a flow and set a variable in the context 69 flow_plan: FlowPlan = request.session.get(SESSION_KEY_PLAN, FlowPlan("")) 70 flow_plan.context.setdefault(PLAN_CONTEXT_METHOD, method) 71 flow_plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {}) 72 flow_plan.context[PLAN_CONTEXT_METHOD_ARGS].update(cleanse_dict(sanitize_dict(kwargs))) 73 request.session[SESSION_KEY_PLAN] = flow_plan 74 75 76class TokenBackend(InbuiltBackend): 77 """Authenticate with token""" 78 79 def authenticate( 80 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 81 ) -> User | None: 82 try: 83 user = User._default_manager.get_by_natural_key(username) 84 85 except User.DoesNotExist: 86 # Run the default password hasher once to reduce the timing 87 # difference between an existing and a nonexistent user (#20760). 88 make_password(password) 89 return None 90 91 tokens = Token.objects.filter( 92 user=user, key=password, intent=TokenIntents.INTENT_APP_PASSWORD 93 ) 94 if not tokens.exists(): 95 return None 96 token = tokens.first() 97 self.set_method("token", request, token=token) 98 return token.user if self.user_can_authenticate(token.user) else None
class
ModelBackendNoAuthz(django.contrib.auth.backends.ModelBackend):
18class ModelBackendNoAuthz(ModelBackend): 19 def get_user_permissions(self, user_obj, obj=None): 20 return set() 21 22 def get_group_permissions(self, user_obj, obj=None): 23 return set() 24 25 def get_all_permissions(self, user_obj, obj=None): 26 return set() 27 28 def has_perm(self, user_obj, perm, obj=None): 29 return False 30 31 def has_module_perms(self, user_obj, app_label): 32 return False 33 34 def with_perm(self, perm, is_active=True, include_superusers=True, obj=None): 35 return User.objects.none()
Authenticates against settings.AUTH_USER_MODEL.
def
get_user_permissions(self, user_obj, obj=None):
Return a set of permission strings the user user_obj has from their
user_permissions.
def
get_group_permissions(self, user_obj, obj=None):
Return a set of permission strings the user user_obj has from the
groups they belong.
38class InbuiltBackend(ModelBackendNoAuthz): 39 """Inbuilt backend""" 40 41 def authenticate( 42 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 43 ) -> User | None: 44 if username is None or password is None: 45 return None 46 user = User.objects.select_related("password_device").filter(username=username).first() 47 device = getattr(user, "password_device", None) 48 if device is None: 49 # Hash once, so a missing user or password takes as long as a wrong password. 50 make_password(password) 51 return None 52 if not device.check_password(password) or not self.user_can_authenticate(user): 53 return None 54 self.set_method("password", request) 55 return user 56 57 async def aauthenticate( 58 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 59 ) -> User | None: 60 return await sync_to_async(self.authenticate)( 61 request, username=username, password=password, **kwargs 62 ) 63 64 def set_method(self, method: str, request: HttpRequest | None, **kwargs): 65 """Set method data on current flow, if possbiel""" 66 if not request: 67 return 68 # Since we can't directly pass other variables to signals, and we want to log the method 69 # and the token used, we assume we're running in a flow and set a variable in the context 70 flow_plan: FlowPlan = request.session.get(SESSION_KEY_PLAN, FlowPlan("")) 71 flow_plan.context.setdefault(PLAN_CONTEXT_METHOD, method) 72 flow_plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {}) 73 flow_plan.context[PLAN_CONTEXT_METHOD_ARGS].update(cleanse_dict(sanitize_dict(kwargs))) 74 request.session[SESSION_KEY_PLAN] = flow_plan
Inbuilt backend
def
authenticate( self, request: django.http.request.HttpRequest, username: str | None, password: str | None, **kwargs: Any) -> authentik.core.models.User | None:
41 def authenticate( 42 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 43 ) -> User | None: 44 if username is None or password is None: 45 return None 46 user = User.objects.select_related("password_device").filter(username=username).first() 47 device = getattr(user, "password_device", None) 48 if device is None: 49 # Hash once, so a missing user or password takes as long as a wrong password. 50 make_password(password) 51 return None 52 if not device.check_password(password) or not self.user_can_authenticate(user): 53 return None 54 self.set_method("password", request) 55 return user
async def
aauthenticate( self, request: django.http.request.HttpRequest, username: str | None, password: str | None, **kwargs: Any) -> authentik.core.models.User | None:
def
set_method( self, method: str, request: django.http.request.HttpRequest | None, **kwargs):
64 def set_method(self, method: str, request: HttpRequest | None, **kwargs): 65 """Set method data on current flow, if possbiel""" 66 if not request: 67 return 68 # Since we can't directly pass other variables to signals, and we want to log the method 69 # and the token used, we assume we're running in a flow and set a variable in the context 70 flow_plan: FlowPlan = request.session.get(SESSION_KEY_PLAN, FlowPlan("")) 71 flow_plan.context.setdefault(PLAN_CONTEXT_METHOD, method) 72 flow_plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {}) 73 flow_plan.context[PLAN_CONTEXT_METHOD_ARGS].update(cleanse_dict(sanitize_dict(kwargs))) 74 request.session[SESSION_KEY_PLAN] = flow_plan
Set method data on current flow, if possbiel
77class TokenBackend(InbuiltBackend): 78 """Authenticate with token""" 79 80 def authenticate( 81 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 82 ) -> User | None: 83 try: 84 user = User._default_manager.get_by_natural_key(username) 85 86 except User.DoesNotExist: 87 # Run the default password hasher once to reduce the timing 88 # difference between an existing and a nonexistent user (#20760). 89 make_password(password) 90 return None 91 92 tokens = Token.objects.filter( 93 user=user, key=password, intent=TokenIntents.INTENT_APP_PASSWORD 94 ) 95 if not tokens.exists(): 96 return None 97 token = tokens.first() 98 self.set_method("token", request, token=token) 99 return token.user if self.user_can_authenticate(token.user) else None
Authenticate with token
def
authenticate( self, request: django.http.request.HttpRequest, username: str | None, password: str | None, **kwargs: Any) -> authentik.core.models.User | None:
80 def authenticate( 81 self, request: HttpRequest, username: str | None, password: str | None, **kwargs: Any 82 ) -> User | None: 83 try: 84 user = User._default_manager.get_by_natural_key(username) 85 86 except User.DoesNotExist: 87 # Run the default password hasher once to reduce the timing 88 # difference between an existing and a nonexistent user (#20760). 89 make_password(password) 90 return None 91 92 tokens = Token.objects.filter( 93 user=user, key=password, intent=TokenIntents.INTENT_APP_PASSWORD 94 ) 95 if not tokens.exists(): 96 return None 97 token = tokens.first() 98 self.set_method("token", request, token=token) 99 return token.user if self.user_can_authenticate(token.user) else None