authentik.providers.proxy.api

ProxyProvider API Views

  1"""ProxyProvider API Views"""
  2
  3from typing import Any
  4
  5from django.utils.translation import gettext_lazy as _
  6from drf_spectacular.utils import extend_schema_field
  7from rest_framework.exceptions import ValidationError
  8from rest_framework.fields import CharField, ListField, ReadOnlyField, SerializerMethodField
  9from rest_framework.mixins import ListModelMixin
 10from rest_framework.viewsets import GenericViewSet, ModelViewSet
 11
 12from authentik.core.api.providers import ProviderSerializer
 13from authentik.core.api.used_by import UsedByMixin
 14from authentik.core.api.utils import ModelSerializer, PassiveSerializer
 15from authentik.crypto.validators import TLS_KEY_TYPES, KeyTypeValidator
 16from authentik.lib.utils.time import timedelta_from_string
 17from authentik.outposts.permissions import IsOutpostServiceAccount
 18from authentik.providers.oauth2.api.providers import RedirectURISerializer
 19from authentik.providers.oauth2.models import ScopeMapping
 20from authentik.providers.oauth2.views.provider import ProviderInfoView
 21from authentik.providers.proxy.models import ProxyMode, ProxyProvider
 22
 23
 24class OpenIDConnectConfigurationSerializer(PassiveSerializer):
 25    """rest_framework Serializer for OIDC Configuration"""
 26
 27    issuer = CharField()
 28    authorization_endpoint = CharField()
 29    token_endpoint = CharField()
 30    userinfo_endpoint = CharField()
 31    end_session_endpoint = CharField()
 32    introspection_endpoint = CharField()
 33    jwks_uri = CharField()
 34
 35    response_types_supported = ListField(child=CharField())
 36    id_token_signing_alg_values_supported = ListField(child=CharField())
 37    subject_types_supported = ListField(child=CharField())
 38    token_endpoint_auth_methods_supported = ListField(child=CharField())
 39
 40
 41class ProxyProviderSerializer(ProviderSerializer):
 42    """ProxyProvider Serializer"""
 43
 44    client_id = CharField(read_only=True)
 45    redirect_uris = RedirectURISerializer(many=True, read_only=True, source="_redirect_uris")
 46    outpost_set = ListField(child=CharField(), read_only=True, source="outpost_set.all")
 47
 48    def validate_basic_auth_enabled(self, value: bool) -> bool:
 49        """Ensure user and password attributes are set"""
 50        if value:
 51            if (
 52                self.initial_data.get("basic_auth_password_attribute", "") == ""
 53                or self.initial_data.get("basic_auth_user_attribute", "") == ""
 54            ):
 55                raise ValidationError(
 56                    _("User and password attributes must be set when basic auth is enabled.")
 57                )
 58        return value
 59
 60    def validate(self, attrs) -> dict[Any, str]:
 61        """Check that internal_host is set when mode is Proxy"""
 62        if (
 63            attrs.get("mode", ProxyMode.PROXY) == ProxyMode.PROXY
 64            and attrs.get("internal_host", "") == ""
 65        ):
 66            raise ValidationError(
 67                {"internal_host": _("Internal host cannot be empty when forward auth is disabled.")}
 68            )
 69        return attrs
 70
 71    def create(self, validated_data: dict):
 72        instance: ProxyProvider = super().create(validated_data)
 73        instance.set_oauth_defaults()
 74        instance.save()
 75        return instance
 76
 77    def update(self, instance: ProxyProvider, validated_data: dict):
 78        instance = super().update(instance, validated_data)
 79        instance.set_oauth_defaults()
 80        instance.save()
 81        return instance
 82
 83    class Meta:
 84        model = ProxyProvider
 85        fields = ProviderSerializer.Meta.fields + [
 86            "client_id",
 87            "internal_host",
 88            "external_host",
 89            "internal_host_ssl_validation",
 90            "certificate",
 91            "skip_path_regex",
 92            "basic_auth_enabled",
 93            "basic_auth_password_attribute",
 94            "basic_auth_user_attribute",
 95            "mode",
 96            "intercept_header_auth",
 97            "redirect_uris",
 98            "cookie_domain",
 99            "jwt_federation_sources",
100            "jwt_federation_providers",
101            "access_token_validity",
102            "refresh_token_validity",
103            "outpost_set",
104        ]
105        extra_kwargs = {
106            **ProviderSerializer.Meta.extra_write_kwargs,
107            "certificate": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
108        }
109
110
111class ProxyProviderViewSet(UsedByMixin, ModelViewSet):
112    """ProxyProvider Viewset"""
113
114    queryset = ProxyProvider.objects.all()
115    serializer_class = ProxyProviderSerializer
116    filterset_fields = {
117        "application": ["isnull"],
118        "name": ["iexact"],
119        "authorization_flow__slug": ["iexact"],
120        "property_mappings": ["iexact"],
121        "internal_host": ["iexact"],
122        "external_host": ["iexact"],
123        "internal_host_ssl_validation": ["iexact"],
124        "certificate__kp_uuid": ["iexact"],
125        "certificate__name": ["iexact"],
126        "skip_path_regex": ["iexact"],
127        "basic_auth_enabled": ["iexact"],
128        "basic_auth_password_attribute": ["iexact"],
129        "basic_auth_user_attribute": ["iexact"],
130        "mode": ["iexact"],
131        "cookie_domain": ["iexact"],
132    }
133    search_fields = ["name"]
134    ordering = ["name"]
135
136
137class ProxyOutpostConfigSerializer(ModelSerializer):
138    """Proxy provider serializer for outposts"""
139
140    assigned_application_slug = ReadOnlyField(source="application.slug")
141    assigned_application_name = ReadOnlyField(source="application.name")
142
143    oidc_configuration = SerializerMethodField()
144    access_token_validity = SerializerMethodField()
145    scopes_to_request = SerializerMethodField()
146
147    @extend_schema_field(OpenIDConnectConfigurationSerializer)
148    def get_oidc_configuration(self, obj: ProxyProvider):
149        """Embed OpenID Connect provider information"""
150        return ProviderInfoView(request=self.context["request"]._request).get_info(obj)
151
152    def get_access_token_validity(self, obj: ProxyProvider) -> float | None:
153        """Get token validity as second count"""
154        return timedelta_from_string(obj.access_token_validity).total_seconds()
155
156    def get_scopes_to_request(self, obj: ProxyProvider) -> list[str]:
157        """Get all the scope names the outpost should request,
158        including custom-defined ones"""
159        scope_names = set(
160            ScopeMapping.objects.filter(provider__in=[obj]).values_list("scope_name", flat=True)
161        )
162        return list(scope_names)
163
164    class Meta:
165        model = ProxyProvider
166        fields = [
167            "pk",
168            "name",
169            "internal_host",
170            "external_host",
171            "internal_host_ssl_validation",
172            "client_id",
173            "client_secret",
174            "oidc_configuration",
175            "cookie_secret",
176            "certificate",
177            "skip_path_regex",
178            "basic_auth_enabled",
179            "basic_auth_password_attribute",
180            "basic_auth_user_attribute",
181            "mode",
182            "cookie_domain",
183            "access_token_validity",
184            "intercept_header_auth",
185            "scopes_to_request",
186            "assigned_application_slug",
187            "assigned_application_name",
188        ]
189
190
191class ProxyOutpostConfigViewSet(ListModelMixin, GenericViewSet):
192    """ProxyProvider Viewset"""
193
194    queryset = ProxyProvider.objects.filter(application__isnull=False)
195    serializer_class = ProxyOutpostConfigSerializer
196    permission_classes = [IsOutpostServiceAccount]
197    ordering = ["name"]
198    search_fields = ["name"]
199    filterset_fields = ["name"]
class OpenIDConnectConfigurationSerializer(authentik.core.api.utils.PassiveSerializer):
25class OpenIDConnectConfigurationSerializer(PassiveSerializer):
26    """rest_framework Serializer for OIDC Configuration"""
27
28    issuer = CharField()
29    authorization_endpoint = CharField()
30    token_endpoint = CharField()
31    userinfo_endpoint = CharField()
32    end_session_endpoint = CharField()
33    introspection_endpoint = CharField()
34    jwks_uri = CharField()
35
36    response_types_supported = ListField(child=CharField())
37    id_token_signing_alg_values_supported = ListField(child=CharField())
38    subject_types_supported = ListField(child=CharField())
39    token_endpoint_auth_methods_supported = ListField(child=CharField())

rest_framework Serializer for OIDC Configuration

issuer
authorization_endpoint
token_endpoint
userinfo_endpoint
end_session_endpoint
introspection_endpoint
jwks_uri
response_types_supported
id_token_signing_alg_values_supported
subject_types_supported
token_endpoint_auth_methods_supported
class ProxyProviderSerializer(authentik.core.api.providers.ProviderSerializer):
 42class ProxyProviderSerializer(ProviderSerializer):
 43    """ProxyProvider Serializer"""
 44
 45    client_id = CharField(read_only=True)
 46    redirect_uris = RedirectURISerializer(many=True, read_only=True, source="_redirect_uris")
 47    outpost_set = ListField(child=CharField(), read_only=True, source="outpost_set.all")
 48
 49    def validate_basic_auth_enabled(self, value: bool) -> bool:
 50        """Ensure user and password attributes are set"""
 51        if value:
 52            if (
 53                self.initial_data.get("basic_auth_password_attribute", "") == ""
 54                or self.initial_data.get("basic_auth_user_attribute", "") == ""
 55            ):
 56                raise ValidationError(
 57                    _("User and password attributes must be set when basic auth is enabled.")
 58                )
 59        return value
 60
 61    def validate(self, attrs) -> dict[Any, str]:
 62        """Check that internal_host is set when mode is Proxy"""
 63        if (
 64            attrs.get("mode", ProxyMode.PROXY) == ProxyMode.PROXY
 65            and attrs.get("internal_host", "") == ""
 66        ):
 67            raise ValidationError(
 68                {"internal_host": _("Internal host cannot be empty when forward auth is disabled.")}
 69            )
 70        return attrs
 71
 72    def create(self, validated_data: dict):
 73        instance: ProxyProvider = super().create(validated_data)
 74        instance.set_oauth_defaults()
 75        instance.save()
 76        return instance
 77
 78    def update(self, instance: ProxyProvider, validated_data: dict):
 79        instance = super().update(instance, validated_data)
 80        instance.set_oauth_defaults()
 81        instance.save()
 82        return instance
 83
 84    class Meta:
 85        model = ProxyProvider
 86        fields = ProviderSerializer.Meta.fields + [
 87            "client_id",
 88            "internal_host",
 89            "external_host",
 90            "internal_host_ssl_validation",
 91            "certificate",
 92            "skip_path_regex",
 93            "basic_auth_enabled",
 94            "basic_auth_password_attribute",
 95            "basic_auth_user_attribute",
 96            "mode",
 97            "intercept_header_auth",
 98            "redirect_uris",
 99            "cookie_domain",
100            "jwt_federation_sources",
101            "jwt_federation_providers",
102            "access_token_validity",
103            "refresh_token_validity",
104            "outpost_set",
105        ]
106        extra_kwargs = {
107            **ProviderSerializer.Meta.extra_write_kwargs,
108            "certificate": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
109        }

ProxyProvider Serializer

client_id
redirect_uris
outpost_set
def validate_basic_auth_enabled(self, value: bool) -> bool:
49    def validate_basic_auth_enabled(self, value: bool) -> bool:
50        """Ensure user and password attributes are set"""
51        if value:
52            if (
53                self.initial_data.get("basic_auth_password_attribute", "") == ""
54                or self.initial_data.get("basic_auth_user_attribute", "") == ""
55            ):
56                raise ValidationError(
57                    _("User and password attributes must be set when basic auth is enabled.")
58                )
59        return value

Ensure user and password attributes are set

def validate(self, attrs) -> dict[typing.Any, str]:
61    def validate(self, attrs) -> dict[Any, str]:
62        """Check that internal_host is set when mode is Proxy"""
63        if (
64            attrs.get("mode", ProxyMode.PROXY) == ProxyMode.PROXY
65            and attrs.get("internal_host", "") == ""
66        ):
67            raise ValidationError(
68                {"internal_host": _("Internal host cannot be empty when forward auth is disabled.")}
69            )
70        return attrs

Check that internal_host is set when mode is Proxy

def create(self, validated_data: dict):
72    def create(self, validated_data: dict):
73        instance: ProxyProvider = super().create(validated_data)
74        instance.set_oauth_defaults()
75        instance.save()
76        return instance

We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just:

return ExampleModel.objects.create(**validated_data)

If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so:

example_relationship = validated_data.pop('example_relationship')
instance = ExampleModel.objects.create(**validated_data)
instance.example_relationship = example_relationship
return instance

The default implementation also does not handle nested relationships. If you want to support writable nested relationships you'll need to write an explicit .create() method.

def update( self, instance: authentik.providers.proxy.models.ProxyProvider, validated_data: dict):
78    def update(self, instance: ProxyProvider, validated_data: dict):
79        instance = super().update(instance, validated_data)
80        instance.set_oauth_defaults()
81        instance.save()
82        return instance
class ProxyProviderSerializer.Meta:
 84    class Meta:
 85        model = ProxyProvider
 86        fields = ProviderSerializer.Meta.fields + [
 87            "client_id",
 88            "internal_host",
 89            "external_host",
 90            "internal_host_ssl_validation",
 91            "certificate",
 92            "skip_path_regex",
 93            "basic_auth_enabled",
 94            "basic_auth_password_attribute",
 95            "basic_auth_user_attribute",
 96            "mode",
 97            "intercept_header_auth",
 98            "redirect_uris",
 99            "cookie_domain",
100            "jwt_federation_sources",
101            "jwt_federation_providers",
102            "access_token_validity",
103            "refresh_token_validity",
104            "outpost_set",
105        ]
106        extra_kwargs = {
107            **ProviderSerializer.Meta.extra_write_kwargs,
108            "certificate": {"validators": [KeyTypeValidator(*TLS_KEY_TYPES)]},
109        }
fields = ['pk', 'name', 'authentication_flow', 'authorization_flow', 'invalidation_flow', 'property_mappings', 'component', 'assigned_application_slug', 'assigned_application_name', 'assigned_backchannel_application_slug', 'assigned_backchannel_application_name', 'verbose_name', 'verbose_name_plural', 'meta_model_name', 'client_id', 'internal_host', 'external_host', 'internal_host_ssl_validation', 'certificate', 'skip_path_regex', 'basic_auth_enabled', 'basic_auth_password_attribute', 'basic_auth_user_attribute', 'mode', 'intercept_header_auth', 'redirect_uris', 'cookie_domain', 'jwt_federation_sources', 'jwt_federation_providers', 'access_token_validity', 'refresh_token_validity', 'outpost_set']
extra_kwargs = {'authorization_flow': {'required': True, 'allow_null': False}, 'invalidation_flow': {'required': True, 'allow_null': False}, 'certificate': {'validators': [<KeyTypeValidator(allowed=[KeyType.RSA, KeyType.EC, KeyType.ED25519, KeyType.MLDSA44, KeyType.MLDSA65, KeyType.MLDSA87])>]}}
class ProxyProviderViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
112class ProxyProviderViewSet(UsedByMixin, ModelViewSet):
113    """ProxyProvider Viewset"""
114
115    queryset = ProxyProvider.objects.all()
116    serializer_class = ProxyProviderSerializer
117    filterset_fields = {
118        "application": ["isnull"],
119        "name": ["iexact"],
120        "authorization_flow__slug": ["iexact"],
121        "property_mappings": ["iexact"],
122        "internal_host": ["iexact"],
123        "external_host": ["iexact"],
124        "internal_host_ssl_validation": ["iexact"],
125        "certificate__kp_uuid": ["iexact"],
126        "certificate__name": ["iexact"],
127        "skip_path_regex": ["iexact"],
128        "basic_auth_enabled": ["iexact"],
129        "basic_auth_password_attribute": ["iexact"],
130        "basic_auth_user_attribute": ["iexact"],
131        "mode": ["iexact"],
132        "cookie_domain": ["iexact"],
133    }
134    search_fields = ["name"]
135    ordering = ["name"]

ProxyProvider Viewset

queryset = <InheritanceQuerySet []>
serializer_class = <class 'ProxyProviderSerializer'>
filterset_fields = {'application': ['isnull'], 'name': ['iexact'], 'authorization_flow__slug': ['iexact'], 'property_mappings': ['iexact'], 'internal_host': ['iexact'], 'external_host': ['iexact'], 'internal_host_ssl_validation': ['iexact'], 'certificate__kp_uuid': ['iexact'], 'certificate__name': ['iexact'], 'skip_path_regex': ['iexact'], 'basic_auth_enabled': ['iexact'], 'basic_auth_password_attribute': ['iexact'], 'basic_auth_user_attribute': ['iexact'], 'mode': ['iexact'], 'cookie_domain': ['iexact']}
search_fields = ['name']
ordering = ['name']
name = None
description = None
suffix = None
detail = None
basename = None
class ProxyOutpostConfigSerializer(authentik.core.api.utils.ModelSerializer):
138class ProxyOutpostConfigSerializer(ModelSerializer):
139    """Proxy provider serializer for outposts"""
140
141    assigned_application_slug = ReadOnlyField(source="application.slug")
142    assigned_application_name = ReadOnlyField(source="application.name")
143
144    oidc_configuration = SerializerMethodField()
145    access_token_validity = SerializerMethodField()
146    scopes_to_request = SerializerMethodField()
147
148    @extend_schema_field(OpenIDConnectConfigurationSerializer)
149    def get_oidc_configuration(self, obj: ProxyProvider):
150        """Embed OpenID Connect provider information"""
151        return ProviderInfoView(request=self.context["request"]._request).get_info(obj)
152
153    def get_access_token_validity(self, obj: ProxyProvider) -> float | None:
154        """Get token validity as second count"""
155        return timedelta_from_string(obj.access_token_validity).total_seconds()
156
157    def get_scopes_to_request(self, obj: ProxyProvider) -> list[str]:
158        """Get all the scope names the outpost should request,
159        including custom-defined ones"""
160        scope_names = set(
161            ScopeMapping.objects.filter(provider__in=[obj]).values_list("scope_name", flat=True)
162        )
163        return list(scope_names)
164
165    class Meta:
166        model = ProxyProvider
167        fields = [
168            "pk",
169            "name",
170            "internal_host",
171            "external_host",
172            "internal_host_ssl_validation",
173            "client_id",
174            "client_secret",
175            "oidc_configuration",
176            "cookie_secret",
177            "certificate",
178            "skip_path_regex",
179            "basic_auth_enabled",
180            "basic_auth_password_attribute",
181            "basic_auth_user_attribute",
182            "mode",
183            "cookie_domain",
184            "access_token_validity",
185            "intercept_header_auth",
186            "scopes_to_request",
187            "assigned_application_slug",
188            "assigned_application_name",
189        ]

Proxy provider serializer for outposts

assigned_application_slug
assigned_application_name
oidc_configuration
access_token_validity
scopes_to_request
@extend_schema_field(OpenIDConnectConfigurationSerializer)
def get_oidc_configuration(self, obj: authentik.providers.proxy.models.ProxyProvider):
148    @extend_schema_field(OpenIDConnectConfigurationSerializer)
149    def get_oidc_configuration(self, obj: ProxyProvider):
150        """Embed OpenID Connect provider information"""
151        return ProviderInfoView(request=self.context["request"]._request).get_info(obj)

Embed OpenID Connect provider information

def get_access_token_validity( self, obj: authentik.providers.proxy.models.ProxyProvider) -> float | None:
153    def get_access_token_validity(self, obj: ProxyProvider) -> float | None:
154        """Get token validity as second count"""
155        return timedelta_from_string(obj.access_token_validity).total_seconds()

Get token validity as second count

def get_scopes_to_request(self, obj: authentik.providers.proxy.models.ProxyProvider) -> list[str]:
157    def get_scopes_to_request(self, obj: ProxyProvider) -> list[str]:
158        """Get all the scope names the outpost should request,
159        including custom-defined ones"""
160        scope_names = set(
161            ScopeMapping.objects.filter(provider__in=[obj]).values_list("scope_name", flat=True)
162        )
163        return list(scope_names)

Get all the scope names the outpost should request, including custom-defined ones

class ProxyOutpostConfigSerializer.Meta:
165    class Meta:
166        model = ProxyProvider
167        fields = [
168            "pk",
169            "name",
170            "internal_host",
171            "external_host",
172            "internal_host_ssl_validation",
173            "client_id",
174            "client_secret",
175            "oidc_configuration",
176            "cookie_secret",
177            "certificate",
178            "skip_path_regex",
179            "basic_auth_enabled",
180            "basic_auth_password_attribute",
181            "basic_auth_user_attribute",
182            "mode",
183            "cookie_domain",
184            "access_token_validity",
185            "intercept_header_auth",
186            "scopes_to_request",
187            "assigned_application_slug",
188            "assigned_application_name",
189        ]
fields = ['pk', 'name', 'internal_host', 'external_host', 'internal_host_ssl_validation', 'client_id', 'client_secret', 'oidc_configuration', 'cookie_secret', 'certificate', 'skip_path_regex', 'basic_auth_enabled', 'basic_auth_password_attribute', 'basic_auth_user_attribute', 'mode', 'cookie_domain', 'access_token_validity', 'intercept_header_auth', 'scopes_to_request', 'assigned_application_slug', 'assigned_application_name']
class ProxyOutpostConfigViewSet(rest_framework.mixins.ListModelMixin, rest_framework.viewsets.GenericViewSet):
192class ProxyOutpostConfigViewSet(ListModelMixin, GenericViewSet):
193    """ProxyProvider Viewset"""
194
195    queryset = ProxyProvider.objects.filter(application__isnull=False)
196    serializer_class = ProxyOutpostConfigSerializer
197    permission_classes = [IsOutpostServiceAccount]
198    ordering = ["name"]
199    search_fields = ["name"]
200    filterset_fields = ["name"]

ProxyProvider Viewset

queryset = <InheritanceQuerySet []>
serializer_class = <class 'ProxyOutpostConfigSerializer'>
ordering = ['name']
search_fields = ['name']
filterset_fields = ['name']
name = None
description = None
suffix = None
detail = None
basename = None