authentik.policies.views
authentik access helper classes
1"""authentik access helper classes""" 2 3from typing import Any 4 5from django.contrib import messages 6from django.contrib.auth.mixins import AccessMixin 7from django.http import Http404, HttpRequest, HttpResponse 8from django.utils.translation import gettext as _ 9from django.views.generic.base import View 10from structlog.stdlib import get_logger 11 12from authentik.core.apps import AppAccessWithoutBindings 13from authentik.core.models import Application, Provider, User 14from authentik.flows.exceptions import EmptyFlowException, FlowNonApplicableException 15from authentik.flows.models import Flow, FlowDesignation 16from authentik.flows.planner import ( 17 PLAN_CONTEXT_APPLICATION, 18 PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD, 19 PLAN_CONTEXT_POST, 20 FlowPlanner, 21) 22from authentik.flows.views.executor import ( 23 SESSION_KEY_POST, 24 ToDefaultFlow, 25) 26from authentik.lib.tracing.exceptions import TracingIgnoredException 27from authentik.policies.denied import AccessDeniedResponse 28from authentik.policies.engine import PolicyEngine 29from authentik.policies.models import PolicyBindingModel 30from authentik.policies.types import PolicyRequest, PolicyResult 31 32LOGGER = get_logger() 33 34 35class RequestValidationError(TracingIgnoredException): 36 """Error raised in pre_permission_check, when a request is invalid.""" 37 38 response: HttpResponse | None 39 40 def __init__(self, response: HttpResponse | None = None): 41 super().__init__() 42 if response: 43 self.response = response 44 45 46class PolicyAccessView(AccessMixin, View): 47 """Mixin class for usage in Authorization views. 48 Provider functions to check application access, etc""" 49 50 provider: Provider | None = None 51 application: Application | None = None 52 53 def pre_permission_check(self): 54 """Optionally hook in before permission check to check if a request is valid. 55 Can raise `RequestValidationError` to return a response.""" 56 57 def resolve_provider_application(self): 58 """Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal 59 AccessDenied view to be shown. An Http404 exception 60 is not caught, and will return directly""" 61 raise NotImplementedError 62 63 def continuous_login_hold_required(self) -> bool: 64 """Keep other tabs paused until this provider's authorization flow finishes.""" 65 return True 66 67 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 68 try: 69 self.pre_permission_check() 70 except RequestValidationError as exc: 71 if exc.response: 72 return exc.response 73 return self.handle_no_permission() 74 try: 75 self.resolve_provider_application() 76 except (Application.DoesNotExist, Provider.DoesNotExist) as exc: 77 LOGGER.warning("failed to resolve application", exc=exc) 78 return self.handle_no_permission_authenticated( 79 PolicyResult(False, _("Failed to resolve application")) 80 ) 81 # Check if user is unauthenticated, so we pass the application 82 # for the identification stage 83 if not request.user.is_authenticated: 84 return self.handle_no_permission() 85 # Check permissions 86 result = self.user_has_access() 87 if not result.passing: 88 return self.handle_no_permission_authenticated(result) 89 return super().dispatch(request, *args, **kwargs) 90 91 def handle_no_permission(self) -> HttpResponse: 92 """User has no access and is not authenticated, so we remember the application 93 they try to access and redirect to the login URL. The application is saved to show 94 a hint on the Identification Stage what the user should login for.""" 95 flow_context = {} 96 authn_flow = None 97 if self.application: 98 flow_context[PLAN_CONTEXT_APPLICATION] = self.application 99 if not self.continuous_login_hold_required(): 100 flow_context[PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD] = False 101 if self.provider and self.provider.authentication_flow: 102 authn_flow = self.provider.authentication_flow 103 # Because this view might get hit with a POST request, we need to preserve that data 104 # since later views might need it (mostly SAML) 105 if self.request.method.lower() == "post": 106 self.request.session[SESSION_KEY_POST] = self.request.POST 107 flow_context[PLAN_CONTEXT_POST] = self.request.POST 108 109 if not authn_flow: 110 authn_flow = ToDefaultFlow.get_flow(self.request, FlowDesignation.AUTHENTICATION) 111 if not authn_flow: 112 raise Http404 113 planner = FlowPlanner(authn_flow) 114 try: 115 plan = planner.plan(self.request, self.modify_flow_context(authn_flow, flow_context)) 116 except (FlowNonApplicableException, EmptyFlowException) as exc: 117 LOGGER.warning("Non-applicable authentication flow", exc=exc) 118 raise Http404 from None 119 return plan.to_redirect(self.request, authn_flow, next=self.request.get_full_path()) 120 121 def handle_no_permission_authenticated( 122 self, result: PolicyResult | None = None 123 ) -> HttpResponse: 124 """Function called when user has no permissions but is authenticated""" 125 response = AccessDeniedResponse(self.request) 126 if result: 127 response.policy_result = result 128 return response 129 130 def modify_policy_request(self, request: PolicyRequest) -> PolicyRequest: 131 """optionally modify the policy request""" 132 return request 133 134 def modify_flow_context(self, flow: Flow, context: dict[str, Any]) -> dict[str, Any]: 135 """optionally modify the flow context which is used for the authentication flow""" 136 return context 137 138 def user_has_access( 139 self, user: User | None = None, pbm: PolicyBindingModel | None = None 140 ) -> PolicyResult: 141 """Check if user has access to application.""" 142 user = user or self.request.user 143 policy_engine = PolicyEngine( 144 pbm or self.application, user or self.request.user, self.request 145 ) 146 policy_engine.empty_result = AppAccessWithoutBindings.get() 147 policy_engine.use_cache = False 148 policy_engine.request = self.modify_policy_request(policy_engine.request) 149 policy_engine.build() 150 result = policy_engine.result 151 log_kwargs = {} 152 if pbm: 153 log_kwargs["pbm"] = pbm.pk 154 else: 155 log_kwargs["app"] = self.application.slug 156 LOGGER.debug( 157 "PolicyAccessView user_has_access", user=user.username, result=result, **log_kwargs 158 ) 159 if not result.passing: 160 for message in result.messages: 161 messages.error(self.request, message) 162 return result
36class RequestValidationError(TracingIgnoredException): 37 """Error raised in pre_permission_check, when a request is invalid.""" 38 39 response: HttpResponse | None 40 41 def __init__(self, response: HttpResponse | None = None): 42 super().__init__() 43 if response: 44 self.response = response
Error raised in pre_permission_check, when a request is invalid.
47class PolicyAccessView(AccessMixin, View): 48 """Mixin class for usage in Authorization views. 49 Provider functions to check application access, etc""" 50 51 provider: Provider | None = None 52 application: Application | None = None 53 54 def pre_permission_check(self): 55 """Optionally hook in before permission check to check if a request is valid. 56 Can raise `RequestValidationError` to return a response.""" 57 58 def resolve_provider_application(self): 59 """Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal 60 AccessDenied view to be shown. An Http404 exception 61 is not caught, and will return directly""" 62 raise NotImplementedError 63 64 def continuous_login_hold_required(self) -> bool: 65 """Keep other tabs paused until this provider's authorization flow finishes.""" 66 return True 67 68 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 69 try: 70 self.pre_permission_check() 71 except RequestValidationError as exc: 72 if exc.response: 73 return exc.response 74 return self.handle_no_permission() 75 try: 76 self.resolve_provider_application() 77 except (Application.DoesNotExist, Provider.DoesNotExist) as exc: 78 LOGGER.warning("failed to resolve application", exc=exc) 79 return self.handle_no_permission_authenticated( 80 PolicyResult(False, _("Failed to resolve application")) 81 ) 82 # Check if user is unauthenticated, so we pass the application 83 # for the identification stage 84 if not request.user.is_authenticated: 85 return self.handle_no_permission() 86 # Check permissions 87 result = self.user_has_access() 88 if not result.passing: 89 return self.handle_no_permission_authenticated(result) 90 return super().dispatch(request, *args, **kwargs) 91 92 def handle_no_permission(self) -> HttpResponse: 93 """User has no access and is not authenticated, so we remember the application 94 they try to access and redirect to the login URL. The application is saved to show 95 a hint on the Identification Stage what the user should login for.""" 96 flow_context = {} 97 authn_flow = None 98 if self.application: 99 flow_context[PLAN_CONTEXT_APPLICATION] = self.application 100 if not self.continuous_login_hold_required(): 101 flow_context[PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD] = False 102 if self.provider and self.provider.authentication_flow: 103 authn_flow = self.provider.authentication_flow 104 # Because this view might get hit with a POST request, we need to preserve that data 105 # since later views might need it (mostly SAML) 106 if self.request.method.lower() == "post": 107 self.request.session[SESSION_KEY_POST] = self.request.POST 108 flow_context[PLAN_CONTEXT_POST] = self.request.POST 109 110 if not authn_flow: 111 authn_flow = ToDefaultFlow.get_flow(self.request, FlowDesignation.AUTHENTICATION) 112 if not authn_flow: 113 raise Http404 114 planner = FlowPlanner(authn_flow) 115 try: 116 plan = planner.plan(self.request, self.modify_flow_context(authn_flow, flow_context)) 117 except (FlowNonApplicableException, EmptyFlowException) as exc: 118 LOGGER.warning("Non-applicable authentication flow", exc=exc) 119 raise Http404 from None 120 return plan.to_redirect(self.request, authn_flow, next=self.request.get_full_path()) 121 122 def handle_no_permission_authenticated( 123 self, result: PolicyResult | None = None 124 ) -> HttpResponse: 125 """Function called when user has no permissions but is authenticated""" 126 response = AccessDeniedResponse(self.request) 127 if result: 128 response.policy_result = result 129 return response 130 131 def modify_policy_request(self, request: PolicyRequest) -> PolicyRequest: 132 """optionally modify the policy request""" 133 return request 134 135 def modify_flow_context(self, flow: Flow, context: dict[str, Any]) -> dict[str, Any]: 136 """optionally modify the flow context which is used for the authentication flow""" 137 return context 138 139 def user_has_access( 140 self, user: User | None = None, pbm: PolicyBindingModel | None = None 141 ) -> PolicyResult: 142 """Check if user has access to application.""" 143 user = user or self.request.user 144 policy_engine = PolicyEngine( 145 pbm or self.application, user or self.request.user, self.request 146 ) 147 policy_engine.empty_result = AppAccessWithoutBindings.get() 148 policy_engine.use_cache = False 149 policy_engine.request = self.modify_policy_request(policy_engine.request) 150 policy_engine.build() 151 result = policy_engine.result 152 log_kwargs = {} 153 if pbm: 154 log_kwargs["pbm"] = pbm.pk 155 else: 156 log_kwargs["app"] = self.application.slug 157 LOGGER.debug( 158 "PolicyAccessView user_has_access", user=user.username, result=result, **log_kwargs 159 ) 160 if not result.passing: 161 for message in result.messages: 162 messages.error(self.request, message) 163 return result
Mixin class for usage in Authorization views. Provider functions to check application access, etc
54 def pre_permission_check(self): 55 """Optionally hook in before permission check to check if a request is valid. 56 Can raise `RequestValidationError` to return a response."""
Optionally hook in before permission check to check if a request is valid.
Can raise RequestValidationError to return a response.
58 def resolve_provider_application(self): 59 """Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal 60 AccessDenied view to be shown. An Http404 exception 61 is not caught, and will return directly""" 62 raise NotImplementedError
Resolve self.provider and self.application. *.DoesNotExist Exceptions cause a normal AccessDenied view to be shown. An Http404 exception is not caught, and will return directly
64 def continuous_login_hold_required(self) -> bool: 65 """Keep other tabs paused until this provider's authorization flow finishes.""" 66 return True
Keep other tabs paused until this provider's authorization flow finishes.
68 def dispatch(self, request: HttpRequest, *args: Any, **kwargs: Any) -> HttpResponse: 69 try: 70 self.pre_permission_check() 71 except RequestValidationError as exc: 72 if exc.response: 73 return exc.response 74 return self.handle_no_permission() 75 try: 76 self.resolve_provider_application() 77 except (Application.DoesNotExist, Provider.DoesNotExist) as exc: 78 LOGGER.warning("failed to resolve application", exc=exc) 79 return self.handle_no_permission_authenticated( 80 PolicyResult(False, _("Failed to resolve application")) 81 ) 82 # Check if user is unauthenticated, so we pass the application 83 # for the identification stage 84 if not request.user.is_authenticated: 85 return self.handle_no_permission() 86 # Check permissions 87 result = self.user_has_access() 88 if not result.passing: 89 return self.handle_no_permission_authenticated(result) 90 return super().dispatch(request, *args, **kwargs)
92 def handle_no_permission(self) -> HttpResponse: 93 """User has no access and is not authenticated, so we remember the application 94 they try to access and redirect to the login URL. The application is saved to show 95 a hint on the Identification Stage what the user should login for.""" 96 flow_context = {} 97 authn_flow = None 98 if self.application: 99 flow_context[PLAN_CONTEXT_APPLICATION] = self.application 100 if not self.continuous_login_hold_required(): 101 flow_context[PLAN_CONTEXT_CONTINUOUS_LOGIN_HOLD] = False 102 if self.provider and self.provider.authentication_flow: 103 authn_flow = self.provider.authentication_flow 104 # Because this view might get hit with a POST request, we need to preserve that data 105 # since later views might need it (mostly SAML) 106 if self.request.method.lower() == "post": 107 self.request.session[SESSION_KEY_POST] = self.request.POST 108 flow_context[PLAN_CONTEXT_POST] = self.request.POST 109 110 if not authn_flow: 111 authn_flow = ToDefaultFlow.get_flow(self.request, FlowDesignation.AUTHENTICATION) 112 if not authn_flow: 113 raise Http404 114 planner = FlowPlanner(authn_flow) 115 try: 116 plan = planner.plan(self.request, self.modify_flow_context(authn_flow, flow_context)) 117 except (FlowNonApplicableException, EmptyFlowException) as exc: 118 LOGGER.warning("Non-applicable authentication flow", exc=exc) 119 raise Http404 from None 120 return plan.to_redirect(self.request, authn_flow, next=self.request.get_full_path())
User has no access and is not authenticated, so we remember the application they try to access and redirect to the login URL. The application is saved to show a hint on the Identification Stage what the user should login for.
122 def handle_no_permission_authenticated( 123 self, result: PolicyResult | None = None 124 ) -> HttpResponse: 125 """Function called when user has no permissions but is authenticated""" 126 response = AccessDeniedResponse(self.request) 127 if result: 128 response.policy_result = result 129 return response
Function called when user has no permissions but is authenticated
131 def modify_policy_request(self, request: PolicyRequest) -> PolicyRequest: 132 """optionally modify the policy request""" 133 return request
optionally modify the policy request
135 def modify_flow_context(self, flow: Flow, context: dict[str, Any]) -> dict[str, Any]: 136 """optionally modify the flow context which is used for the authentication flow""" 137 return context
optionally modify the flow context which is used for the authentication flow
139 def user_has_access( 140 self, user: User | None = None, pbm: PolicyBindingModel | None = None 141 ) -> PolicyResult: 142 """Check if user has access to application.""" 143 user = user or self.request.user 144 policy_engine = PolicyEngine( 145 pbm or self.application, user or self.request.user, self.request 146 ) 147 policy_engine.empty_result = AppAccessWithoutBindings.get() 148 policy_engine.use_cache = False 149 policy_engine.request = self.modify_policy_request(policy_engine.request) 150 policy_engine.build() 151 result = policy_engine.result 152 log_kwargs = {} 153 if pbm: 154 log_kwargs["pbm"] = pbm.pk 155 else: 156 log_kwargs["app"] = self.application.slug 157 LOGGER.debug( 158 "PolicyAccessView user_has_access", user=user.username, result=result, **log_kwargs 159 ) 160 if not result.passing: 161 for message in result.messages: 162 messages.error(self.request, message) 163 return result
Check if user has access to application.