def authenticate(self, **credentials): """Attempt to authenticate a request. Args: **credentials (dict): The credentials for authentication. Returns: django.contrib.auth.models.User: If authentication succeeds, the user that authenticated, otherwise ``None``. """ request = credentials.get('request') if request is None: return None try: from oauth2_provider.oauth2_backends import get_oauthlib_core except ImportError: raise ImproperlyConfigured( 'WebAPIOAuth2TokenAuthBackend requires django-oauth-toolkit' '>=0.9,<0.9.999.' ) oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid and self.verify_request(request, r.access_token, r.user): request._oauth2_token = r.access_token request.session['oauth2_token_id'] = r.access_token.pk return r.user return None
def auth_check(request): oauthlib_core = get_oauthlib_core() # as of now, this is only used in our APIs, so explictly check that particular scope valid, r = oauthlib_core.verify_request(request, scopes=['access_apis']) if valid: request.user = r.user return True
def authenticate(self, **credentials): """Attempt to authenticate a request. Args: **credentials (dict): The credentials for authentication. Returns: django.contrib.auth.models.User: If authentication succeeds, the user that authenticated, otherwise ``None``. """ request = credentials.get('request') if request is None: return None try: from oauth2_provider.oauth2_backends import get_oauthlib_core except ImportError: raise ImproperlyConfigured( 'WebAPIOAuth2TokenAuthBackend requires django-oauth-toolkit' '>=0.9,<0.9.999.') oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid and self.verify_request(request, r.access_token, r.user): request._oauth2_token = r.access_token request.session['oauth2_token_id'] = r.access_token.pk return r.user return None
def authenticate(cls, request): from oauth2_provider.oauth2_backends import get_oauthlib_core oauthlib_core = get_oauthlib_core() valid, oauthlib_req = oauthlib_core.verify_request(request, scopes=[]) if valid: return oauthlib_req.user else: return None
def authenticate(self, request): oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) print(valid) if valid: return r.user, r.access_token request.oauth2_error = getattr(r, "oauth2_error", {}) return None
def authenticate(self, request=None, **credentials): if request is not None: valid, r = get_oauthlib_core().verify_request(request, scopes=[]) if valid and r.user is not None: if r.user.needs_update: data = self.download_user(r) return self.update_external_user(data, r.user) #else: test_token() return None
def userinfo(request): """ Check whether the user is an admin or not. """ # from django-oauth-toolkit source code oauthlib_core = get_oauthlib_core() # oauthli_core.verify_request return valid/not valid and the processed request valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: serializer = UserSerializer(r.user) return Response(serializer.data) return Response({})
def create_token_response(self, request): """ A wrapper method that calls create_token_response on `server_class` instance. :param request: The current django.http.HttpRequest object """ uri, http_method, body, headers = self._extract_params(request) headers, body, status = get_oauthlib_core().server.create_token_response(uri, http_method, body, headers) uri = headers.get("Location", None) return uri, headers, body, status
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: return r.user, r.access_token request.oauth2_error = getattr(r, "oauth2_error", {}) return None
def authenticate(request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: return r.user, r.access_token else: return None, None
def oauth_profile(request): from account.rest.serializers import Serializers user = request.user oauth = get_oauthlib_core() oauth_email, _ = oauth.verify_request(request, scopes=["email"]) oauth_api_keys, _ = oauth.verify_request(request, scopes=["api_keys"]) oauth_provider_passthru = [] for social_auth in user.social_auth.all(): key = f"provider:{social_auth.provider}" verify, _ = oauth.verify_request(request, scopes=[key]) if verify: oauth_provider_passthru.append(social_auth) json_params = {} if "pretty" in request.GET: json_params.update(indent=2) data = dict( id=user.id, user_name=user.username, given_name=user.first_name, family_name=user.last_name, is_superuser=user.is_superuser, is_staff=user.is_staff, name=f"{user.first_name} {user.last_name}", # TODO: dont assume oauth implies verification verified_user=True, organizations=[ Serializers.org(instance=org.org, context={ "user": user }).data for org in user.orguser_set.all() ], ) if oauth_email: data.update(dict(email=user.email)) for social_auth in oauth_provider_passthru: provider = social_auth.provider data[provider] = social_auth.extra_data if "access_token" in data[provider]: del data[provider]["access_token"] if "token_type" in data[provider]: del data[provider]["token_type"] return JsonResponse(data, json_dumps_params=json_params)
def authenticate(request): """ Authenticate the request. Returns a tuple containing the user and their access token. If it's not valid then None is returned. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: return r.user, r.access_token return None, None
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: if r.client.authorization_grant_type == Application.GRANT_CLIENT_CREDENTIALS: return r.client.user, r.access_token else: return r.access_token.user, r.access_token else: return None
def process_request(self, request): # cowardly refuse to handle the v3 API endpoints if "api" in request.path and "v3" in request.path: return # do something only if request contains a Bearer token if request.META.get("HTTP_AUTHORIZATION", "").startswith("Bearer"): if not hasattr(request, "user") or request.user.is_anonymous: # borrowed from the oauth2_provider backend from oauth2_provider.oauth2_backends import get_oauthlib_core OAuthLibCore = get_oauthlib_core() valid, r = OAuthLibCore.verify_request(request, scopes=[]) if valid: request.user = request._cached_user = r.user request.tatl_oauth = True
def test_oidc_endpoint_generation_ssl(oauth2_settings, rf, settings): oauth2_settings.OIDC_ISS_ENDPOINT = "" django_request = rf.get("/", secure=True) # Calling the settings method with a django https request should generate a https url oidc_issuer_endpoint = oauth2_settings.oidc_issuer(django_request) assert oidc_issuer_endpoint == "https://testserver/o" # Should also work with an oauthlib request (via validator) core = get_oauthlib_core() uri, http_method, body, headers = core._extract_params(django_request) request = Request(uri=uri, http_method=http_method, body=body, headers=headers) validator = OAuth2Validator() oidc_issuer_endpoint = validator.get_oidc_issuer_endpoint(request) assert oidc_issuer_endpoint == "https://testserver/o"
def authenticate(self, request): access_token = get_header_oauth(request).split() if len(access_token) <= 1: msg = _('Invalid token header. No access token provided.') raise exceptions.AuthenticationFailed(msg) elif len(access_token) > 2: msg = _( 'Invalid access token header. Token string should not contain spaces.' ) raise exceptions.AuthenticationFailed(msg) oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if not valid: raise exceptions.AuthenticationFailed( _('Invalid token (or) token has expired')) return None
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: token_session_timeout = getattr(settings, 'OAUTH2_TOKEN_SESSION_TIMEOUT_SECONDS', None) if token_session_timeout is not None: half_expiration_ahead = timezone.now() + datetime.timedelta(seconds=token_session_timeout/2) if r.access_token.expires < half_expiration_ahead: r.access_token.expires = timezone.now() + datetime.timedelta(seconds=token_session_timeout) r.access_token.save() if r.client.authorization_grant_type == Application.GRANT_CLIENT_CREDENTIALS: return r.client.user, r.access_token else: return r.access_token.user, r.access_token else: return None
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if valid: token_session_timeout = getattr(settings, 'OAUTH2_TOKEN_SESSION_TIMEOUT_SECONDS', None) if token_session_timeout is not None: new_expiration = timezone.now() + datetime.timedelta(seconds=token_session_timeout) if r.access_token.expires < new_expiration: r.access_token.expires = new_expiration r.access_token.save() if r.client.authorization_grant_type == Application.GRANT_CLIENT_CREDENTIALS: return r.client.user, r.access_token else: return r.access_token.user, r.access_token else: return None
def authenticate(self, request): """ Returns two-tuple of (user, token) if authentication succeeds, or None otherwise. """ oauthlib_core = get_oauthlib_core() valid, r = oauthlib_core.verify_request(request, scopes=[]) if r and r.access_token: expiry_time = r.access_token.expires min_sec = get_time_diff(expiry_time) minutes = min_sec[0] if minutes < REFRESH_TIME_IN_MINUTES and valid: create_new_access_token(r) if valid: return r.user, r.access_token else: return None
""" Provides various authentication policies. """ from __future__ import unicode_literals from django.middleware.csrf import CsrfViewMiddleware from django.utils.translation import ugettext_lazy as _ from rest_framework import exceptions, HTTP_HEADER_ENCODING from rest_framework.authtoken.models import Token from oauth2_provider.oauth2_backends import get_oauthlib_core OAuthLibCore = get_oauthlib_core() def get_authorization_header(request): """ Return request's 'Authorization:' header, as a bytestring. Hide some test client ickyness where the header can be unicode. """ auth = request.META.get('HTTP_TOKEN', b'') if isinstance(auth, type('')): # Work around django test client oddness auth = auth.encode(HTTP_HEADER_ENCODING) return auth class CSRFCheck(CsrfViewMiddleware): def _reject(self, request, reason): # Return the failure reason instead of an HttpResponse