authentik.stages.password.stage

authentik password stage

  1"""authentik password stage"""
  2
  3from typing import Any
  4
  5from django.contrib.auth import _clean_credentials
  6from django.contrib.auth.backends import BaseBackend
  7from django.contrib.auth.hashers import make_password
  8from django.core.exceptions import PermissionDenied
  9from django.db.models import Sum
 10from django.http import HttpRequest, HttpResponse
 11from django.urls import reverse
 12from django.utils.translation import gettext as _
 13from rest_framework.exceptions import ValidationError
 14from rest_framework.fields import BooleanField, CharField
 15from structlog.stdlib import get_logger
 16
 17from authentik.core.models import SERVICE_ACCOUNT_TYPES, User
 18from authentik.core.signals import login_failed
 19from authentik.flows.challenge import (
 20    Challenge,
 21    ChallengeResponse,
 22    WithUserInfoChallenge,
 23)
 24from authentik.flows.exceptions import StageInvalidException
 25from authentik.flows.models import Flow, Stage
 26from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER
 27from authentik.flows.stage import ChallengeStageView
 28from authentik.lib.tracing import active_tracer
 29from authentik.lib.utils.reflection import path_to_class
 30from authentik.policies.reputation.models import Reputation
 31from authentik.stages.password.lockout import (
 32    PasswordLockout,
 33    PasswordLockoutResult,
 34)
 35from authentik.stages.password.models import PasswordDevice, PasswordStage
 36
 37LOGGER = get_logger()
 38PLAN_CONTEXT_AUTHENTICATION_BACKEND = "user_backend"
 39PLAN_CONTEXT_METHOD = "auth_method"
 40PLAN_CONTEXT_METHOD_ARGS = "auth_method_args"
 41PLAN_CONTEXT_INITIAL_SCORE = "goauthentik.io/stages/password/initial_score"
 42
 43
 44def authenticate(
 45    request: HttpRequest, backends: list[str], stage: Stage | None = None, **credentials: Any
 46) -> User | None:
 47    """If the given credentials are valid, return a User object.
 48
 49    Customized version of django's authenticate, which accepts a list of backends"""
 50    if (
 51        PasswordDevice.objects.filter(
 52            user__username=credentials.get("username"), locked_at__isnull=False
 53        )
 54        .exclude(user__type__in=SERVICE_ACCOUNT_TYPES)
 55        .exists()
 56    ):
 57        # Refuse before a backend can sync passwords or change authentication state.
 58        # Match the inbuilt backend's hashing work without checking the real password.
 59        make_password(credentials.get("password"))
 60        backends = []
 61    for backend_path in backends:
 62        try:
 63            backend: BaseBackend = path_to_class(backend_path)()
 64        except ImportError:
 65            LOGGER.warning("Failed to import backend", path=backend_path)
 66            continue
 67        LOGGER.debug("Attempting authentication...", backend=backend_path)
 68        with active_tracer().start_span(
 69            op="authentik.stages.password.authenticate",
 70            name=backend_path,
 71        ):
 72            user = backend.authenticate(request, **credentials)
 73        if user is None:
 74            LOGGER.debug("Backend returned nothing, continuing", backend=backend_path)
 75            continue
 76        # Annotate the user object with the path of the backend.
 77        user.backend = backend_path
 78        LOGGER.info("Successful authentication", user=user.username, backend=backend_path)
 79        return user
 80
 81    # The credentials supplied are invalid to all backends, fire signal
 82    login_failed.send(
 83        sender=__name__,
 84        credentials=_clean_credentials(credentials),
 85        request=request,
 86        stage=stage,
 87    )
 88
 89
 90class PasswordChallenge(WithUserInfoChallenge):
 91    """Password challenge UI fields"""
 92
 93    recovery_url = CharField(required=False)
 94
 95    component = CharField(default="ak-stage-password")
 96
 97    allow_show_password = BooleanField(default=False)
 98
 99
100class PasswordChallengeResponse(ChallengeResponse):
101    """Password challenge response"""
102
103    component = CharField(default="ak-stage-password")
104
105    password = CharField(trim_whitespace=False)
106
107    lockout: PasswordLockoutResult | None = None
108
109    def validate_password(self, password: str) -> str | None:
110        """Validate password and authenticate user"""
111        executor = self.stage.executor
112        if PLAN_CONTEXT_PENDING_USER not in executor.plan.context:
113            raise StageInvalidException("No pending user")
114        # Get the pending user's username, which is used as
115        # an Identifier by most authentication backends
116        pending_user: User = executor.plan.context[PLAN_CONTEXT_PENDING_USER]
117        auth_kwargs = {
118            "password": password,
119            "username": pending_user.username,
120        }
121        try:
122            with active_tracer().start_span(
123                op="authentik.stages.password.authenticate",
124                name="User authenticate call",
125            ):
126                user = authenticate(
127                    self.stage.request,
128                    executor.current_stage.backends,
129                    executor.current_stage,
130                    **auth_kwargs,
131                )
132        except PermissionDenied as exc:
133            del auth_kwargs["password"]
134            # User was found, but permission was denied (i.e. user is not active)
135            self.stage.logger.debug("Denied access", **auth_kwargs)
136            raise StageInvalidException("Denied access") from exc
137        except ValidationError as exc:
138            del auth_kwargs["password"]
139            # User was found, authentication succeeded, but another signal raised an error
140            # (most likely LDAP)
141            self.stage.logger.debug("Validation error from signal", exc=exc, **auth_kwargs)
142            raise StageInvalidException("Validation error") from exc
143        result = PasswordLockout(executor.current_stage, self.stage.request).apply(
144            pending_user, user, executor.plan.context
145        )
146        self.lockout = result
147        if not result.user:
148            # No user was found -> invalid credentials
149            self.stage.logger.info("Invalid credentials")
150            error = _("Invalid password")
151            if result.last_attempt:
152                error = executor.current_stage.last_attempt_warning_message or error
153            raise ValidationError(error, "invalid")
154        # User instance returned from authenticate() has .backend property set
155        executor.plan.context[PLAN_CONTEXT_PENDING_USER] = result.user
156        executor.plan.context[PLAN_CONTEXT_AUTHENTICATION_BACKEND] = result.user.backend
157        return password
158
159
160class PasswordStageView(ChallengeStageView):
161    """Authentication stage which authenticates against django's AuthBackend"""
162
163    response_class = PasswordChallengeResponse
164
165    def get_challenge(self) -> Challenge:
166        challenge = PasswordChallenge(
167            data={
168                "allow_show_password": self.executor.current_stage.allow_show_password,
169            }
170        )
171        recovery_flow: Flow | None = self.request.brand.flow_recovery
172        if recovery_flow:
173            recover_url = reverse(
174                "authentik_core:if-flow",
175                kwargs={"flow_slug": recovery_flow.slug},
176            )
177            challenge.initial_data["recovery_url"] = self.request.build_absolute_uri(recover_url)
178        if PLAN_CONTEXT_INITIAL_SCORE not in self.executor.plan.context:
179            self.executor.plan.context[PLAN_CONTEXT_INITIAL_SCORE] = self.get_reputation_score()
180        return challenge
181
182    def get_reputation_score(self) -> int:
183        return (
184            Reputation.objects.filter(identifier=self.get_pending_user().username).aggregate(
185                total_score=Sum("score")
186            )["total_score"]
187            or 0
188        )
189
190    def challenge_invalid(self, response: PasswordChallengeResponse) -> HttpResponse:
191        current_stage: PasswordStage = self.executor.current_stage
192        error = _("Invalid password")
193        if response.lockout:
194            if response.lockout.lockout_reached:
195                return self.executor.stage_invalid(current_stage.lockout_message or error)
196            if response.lockout.last_attempt:
197                error = current_stage.last_attempt_warning_message or error
198        initial_score = self.executor.plan.context.get(PLAN_CONTEXT_INITIAL_SCORE)
199        if initial_score is None:
200            initial_score = self.get_reputation_score()
201            self.executor.plan.context[PLAN_CONTEXT_INITIAL_SCORE] = initial_score
202        new_score = self.get_reputation_score()
203        if (initial_score - new_score) >= current_stage.failed_attempts_before_cancel:
204            self.logger.debug("User has exceeded maximum tries")
205            return self.executor.stage_invalid(error)
206        return super().challenge_invalid(response)
207
208    def challenge_valid(self, response: PasswordChallengeResponse) -> HttpResponse:
209        """Authenticate against django's authentication backend"""
210        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
211            return self.executor.stage_invalid()
212        return self.executor.stage_ok()
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
PLAN_CONTEXT_AUTHENTICATION_BACKEND = 'user_backend'
PLAN_CONTEXT_METHOD = 'auth_method'
PLAN_CONTEXT_METHOD_ARGS = 'auth_method_args'
PLAN_CONTEXT_INITIAL_SCORE = 'goauthentik.io/stages/password/initial_score'
def authenticate( request: django.http.request.HttpRequest, backends: list[str], stage: authentik.flows.models.Stage | None = None, **credentials: Any) -> authentik.core.models.User | None:
45def authenticate(
46    request: HttpRequest, backends: list[str], stage: Stage | None = None, **credentials: Any
47) -> User | None:
48    """If the given credentials are valid, return a User object.
49
50    Customized version of django's authenticate, which accepts a list of backends"""
51    if (
52        PasswordDevice.objects.filter(
53            user__username=credentials.get("username"), locked_at__isnull=False
54        )
55        .exclude(user__type__in=SERVICE_ACCOUNT_TYPES)
56        .exists()
57    ):
58        # Refuse before a backend can sync passwords or change authentication state.
59        # Match the inbuilt backend's hashing work without checking the real password.
60        make_password(credentials.get("password"))
61        backends = []
62    for backend_path in backends:
63        try:
64            backend: BaseBackend = path_to_class(backend_path)()
65        except ImportError:
66            LOGGER.warning("Failed to import backend", path=backend_path)
67            continue
68        LOGGER.debug("Attempting authentication...", backend=backend_path)
69        with active_tracer().start_span(
70            op="authentik.stages.password.authenticate",
71            name=backend_path,
72        ):
73            user = backend.authenticate(request, **credentials)
74        if user is None:
75            LOGGER.debug("Backend returned nothing, continuing", backend=backend_path)
76            continue
77        # Annotate the user object with the path of the backend.
78        user.backend = backend_path
79        LOGGER.info("Successful authentication", user=user.username, backend=backend_path)
80        return user
81
82    # The credentials supplied are invalid to all backends, fire signal
83    login_failed.send(
84        sender=__name__,
85        credentials=_clean_credentials(credentials),
86        request=request,
87        stage=stage,
88    )

If the given credentials are valid, return a User object.

Customized version of django's authenticate, which accepts a list of backends

class PasswordChallenge(authentik.flows.challenge.WithUserInfoChallenge):
91class PasswordChallenge(WithUserInfoChallenge):
92    """Password challenge UI fields"""
93
94    recovery_url = CharField(required=False)
95
96    component = CharField(default="ak-stage-password")
97
98    allow_show_password = BooleanField(default=False)

Password challenge UI fields

recovery_url
component
allow_show_password
class PasswordChallengeResponse(authentik.flows.challenge.ChallengeResponse):
101class PasswordChallengeResponse(ChallengeResponse):
102    """Password challenge response"""
103
104    component = CharField(default="ak-stage-password")
105
106    password = CharField(trim_whitespace=False)
107
108    lockout: PasswordLockoutResult | None = None
109
110    def validate_password(self, password: str) -> str | None:
111        """Validate password and authenticate user"""
112        executor = self.stage.executor
113        if PLAN_CONTEXT_PENDING_USER not in executor.plan.context:
114            raise StageInvalidException("No pending user")
115        # Get the pending user's username, which is used as
116        # an Identifier by most authentication backends
117        pending_user: User = executor.plan.context[PLAN_CONTEXT_PENDING_USER]
118        auth_kwargs = {
119            "password": password,
120            "username": pending_user.username,
121        }
122        try:
123            with active_tracer().start_span(
124                op="authentik.stages.password.authenticate",
125                name="User authenticate call",
126            ):
127                user = authenticate(
128                    self.stage.request,
129                    executor.current_stage.backends,
130                    executor.current_stage,
131                    **auth_kwargs,
132                )
133        except PermissionDenied as exc:
134            del auth_kwargs["password"]
135            # User was found, but permission was denied (i.e. user is not active)
136            self.stage.logger.debug("Denied access", **auth_kwargs)
137            raise StageInvalidException("Denied access") from exc
138        except ValidationError as exc:
139            del auth_kwargs["password"]
140            # User was found, authentication succeeded, but another signal raised an error
141            # (most likely LDAP)
142            self.stage.logger.debug("Validation error from signal", exc=exc, **auth_kwargs)
143            raise StageInvalidException("Validation error") from exc
144        result = PasswordLockout(executor.current_stage, self.stage.request).apply(
145            pending_user, user, executor.plan.context
146        )
147        self.lockout = result
148        if not result.user:
149            # No user was found -> invalid credentials
150            self.stage.logger.info("Invalid credentials")
151            error = _("Invalid password")
152            if result.last_attempt:
153                error = executor.current_stage.last_attempt_warning_message or error
154            raise ValidationError(error, "invalid")
155        # User instance returned from authenticate() has .backend property set
156        executor.plan.context[PLAN_CONTEXT_PENDING_USER] = result.user
157        executor.plan.context[PLAN_CONTEXT_AUTHENTICATION_BACKEND] = result.user.backend
158        return password

Password challenge response

component
password
def validate_password(self, password: str) -> str | None:
110    def validate_password(self, password: str) -> str | None:
111        """Validate password and authenticate user"""
112        executor = self.stage.executor
113        if PLAN_CONTEXT_PENDING_USER not in executor.plan.context:
114            raise StageInvalidException("No pending user")
115        # Get the pending user's username, which is used as
116        # an Identifier by most authentication backends
117        pending_user: User = executor.plan.context[PLAN_CONTEXT_PENDING_USER]
118        auth_kwargs = {
119            "password": password,
120            "username": pending_user.username,
121        }
122        try:
123            with active_tracer().start_span(
124                op="authentik.stages.password.authenticate",
125                name="User authenticate call",
126            ):
127                user = authenticate(
128                    self.stage.request,
129                    executor.current_stage.backends,
130                    executor.current_stage,
131                    **auth_kwargs,
132                )
133        except PermissionDenied as exc:
134            del auth_kwargs["password"]
135            # User was found, but permission was denied (i.e. user is not active)
136            self.stage.logger.debug("Denied access", **auth_kwargs)
137            raise StageInvalidException("Denied access") from exc
138        except ValidationError as exc:
139            del auth_kwargs["password"]
140            # User was found, authentication succeeded, but another signal raised an error
141            # (most likely LDAP)
142            self.stage.logger.debug("Validation error from signal", exc=exc, **auth_kwargs)
143            raise StageInvalidException("Validation error") from exc
144        result = PasswordLockout(executor.current_stage, self.stage.request).apply(
145            pending_user, user, executor.plan.context
146        )
147        self.lockout = result
148        if not result.user:
149            # No user was found -> invalid credentials
150            self.stage.logger.info("Invalid credentials")
151            error = _("Invalid password")
152            if result.last_attempt:
153                error = executor.current_stage.last_attempt_warning_message or error
154            raise ValidationError(error, "invalid")
155        # User instance returned from authenticate() has .backend property set
156        executor.plan.context[PLAN_CONTEXT_PENDING_USER] = result.user
157        executor.plan.context[PLAN_CONTEXT_AUTHENTICATION_BACKEND] = result.user.backend
158        return password

Validate password and authenticate user

class PasswordStageView(authentik.flows.stage.ChallengeStageView):
161class PasswordStageView(ChallengeStageView):
162    """Authentication stage which authenticates against django's AuthBackend"""
163
164    response_class = PasswordChallengeResponse
165
166    def get_challenge(self) -> Challenge:
167        challenge = PasswordChallenge(
168            data={
169                "allow_show_password": self.executor.current_stage.allow_show_password,
170            }
171        )
172        recovery_flow: Flow | None = self.request.brand.flow_recovery
173        if recovery_flow:
174            recover_url = reverse(
175                "authentik_core:if-flow",
176                kwargs={"flow_slug": recovery_flow.slug},
177            )
178            challenge.initial_data["recovery_url"] = self.request.build_absolute_uri(recover_url)
179        if PLAN_CONTEXT_INITIAL_SCORE not in self.executor.plan.context:
180            self.executor.plan.context[PLAN_CONTEXT_INITIAL_SCORE] = self.get_reputation_score()
181        return challenge
182
183    def get_reputation_score(self) -> int:
184        return (
185            Reputation.objects.filter(identifier=self.get_pending_user().username).aggregate(
186                total_score=Sum("score")
187            )["total_score"]
188            or 0
189        )
190
191    def challenge_invalid(self, response: PasswordChallengeResponse) -> HttpResponse:
192        current_stage: PasswordStage = self.executor.current_stage
193        error = _("Invalid password")
194        if response.lockout:
195            if response.lockout.lockout_reached:
196                return self.executor.stage_invalid(current_stage.lockout_message or error)
197            if response.lockout.last_attempt:
198                error = current_stage.last_attempt_warning_message or error
199        initial_score = self.executor.plan.context.get(PLAN_CONTEXT_INITIAL_SCORE)
200        if initial_score is None:
201            initial_score = self.get_reputation_score()
202            self.executor.plan.context[PLAN_CONTEXT_INITIAL_SCORE] = initial_score
203        new_score = self.get_reputation_score()
204        if (initial_score - new_score) >= current_stage.failed_attempts_before_cancel:
205            self.logger.debug("User has exceeded maximum tries")
206            return self.executor.stage_invalid(error)
207        return super().challenge_invalid(response)
208
209    def challenge_valid(self, response: PasswordChallengeResponse) -> HttpResponse:
210        """Authenticate against django's authentication backend"""
211        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
212            return self.executor.stage_invalid()
213        return self.executor.stage_ok()

Authentication stage which authenticates against django's AuthBackend

response_class = <class 'PasswordChallengeResponse'>
def get_challenge(self) -> authentik.flows.challenge.Challenge:
166    def get_challenge(self) -> Challenge:
167        challenge = PasswordChallenge(
168            data={
169                "allow_show_password": self.executor.current_stage.allow_show_password,
170            }
171        )
172        recovery_flow: Flow | None = self.request.brand.flow_recovery
173        if recovery_flow:
174            recover_url = reverse(
175                "authentik_core:if-flow",
176                kwargs={"flow_slug": recovery_flow.slug},
177            )
178            challenge.initial_data["recovery_url"] = self.request.build_absolute_uri(recover_url)
179        if PLAN_CONTEXT_INITIAL_SCORE not in self.executor.plan.context:
180            self.executor.plan.context[PLAN_CONTEXT_INITIAL_SCORE] = self.get_reputation_score()
181        return challenge

Return the challenge that the client should solve

def get_reputation_score(self) -> int:
183    def get_reputation_score(self) -> int:
184        return (
185            Reputation.objects.filter(identifier=self.get_pending_user().username).aggregate(
186                total_score=Sum("score")
187            )["total_score"]
188            or 0
189        )
def challenge_invalid( self, response: PasswordChallengeResponse) -> django.http.response.HttpResponse:
191    def challenge_invalid(self, response: PasswordChallengeResponse) -> HttpResponse:
192        current_stage: PasswordStage = self.executor.current_stage
193        error = _("Invalid password")
194        if response.lockout:
195            if response.lockout.lockout_reached:
196                return self.executor.stage_invalid(current_stage.lockout_message or error)
197            if response.lockout.last_attempt:
198                error = current_stage.last_attempt_warning_message or error
199        initial_score = self.executor.plan.context.get(PLAN_CONTEXT_INITIAL_SCORE)
200        if initial_score is None:
201            initial_score = self.get_reputation_score()
202            self.executor.plan.context[PLAN_CONTEXT_INITIAL_SCORE] = initial_score
203        new_score = self.get_reputation_score()
204        if (initial_score - new_score) >= current_stage.failed_attempts_before_cancel:
205            self.logger.debug("User has exceeded maximum tries")
206            return self.executor.stage_invalid(error)
207        return super().challenge_invalid(response)

Callback when the challenge has the incorrect format

def challenge_valid( self, response: PasswordChallengeResponse) -> django.http.response.HttpResponse:
209    def challenge_valid(self, response: PasswordChallengeResponse) -> HttpResponse:
210        """Authenticate against django's authentication backend"""
211        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
212            return self.executor.stage_invalid()
213        return self.executor.stage_ok()

Authenticate against django's authentication backend