Source code for simple_openid_connect.integrations.djangorestframework.authentication
"""DRF Authentication classesSee the `DRF documentation on Setting the authentication scheme <https://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme>`_ about how to use the classes contained here."""importloggingfromtypingimportAny,Tuple,Unionfromdjango.httpimportHttpRequestfromrest_framework.authenticationimportBaseAuthenticationfromrest_framework.exceptionsimportAuthenticationFailedfromsimple_openid_connect.exceptionsimportValidationErrorfromsimple_openid_connect.integrations.django.appsimportOpenidAppConfigfromsimple_openid_connect.integrations.django.user_mappingimportFederatedUserDatalogger=logging.getLogger(__name__)
[docs]classAuthenticatedViaToken:""" A marker that is attached as ``request.auth`` on successful authentication and which holds well formatted information about that authentication. """
[docs]classAccessTokenAuthentication(BaseAuthentication):""" An authentication scheme that interprets ``Authorization: Bearer ...`` http headers as access tokens. """
[docs]defauthenticate(self,request:HttpRequest)->Union[Tuple[Any,AuthenticatedViaToken],None]:# abort if no authentication is intendedif"Authorization"notinrequest.headers.keys()ornotrequest.headers["Authorization"].startswith("Bearer "):returnNoneoidc_client=OpenidAppConfig.get_instance().get_client(request)raw_token=request.headers["Authorization"].split(" ",1)[1]# handle access token while not verifying scopes because those are verified by a permission classtry:(user,userinfo,)=OpenidAppConfig.get_instance().user_mapper.handle_federated_access_token(raw_token,oidc_client,required_scopes="")returnuser,AuthenticatedViaToken(raw_token,userinfo)exceptValidationError:raiseAuthenticationFailed()