Python rest_framework.authentication.get_authorization_header() Examples

The following are 22 code examples of rest_framework.authentication.get_authorization_header(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module rest_framework.authentication , or try the search function .
Example #1
Source File: backend.py    From django-cognito-jwt with MIT License 6 votes vote down vote up
def get_jwt_token(self, request):
        auth = get_authorization_header(request).split()
        if not auth or smart_text(auth[0].lower()) != "bearer":
            return None

        if len(auth) == 1:
            msg = _("Invalid Authorization header. No credentials provided.")
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _(
                "Invalid Authorization header. Credentials string "
                "should not contain spaces."
            )
            raise exceptions.AuthenticationFailed(msg)

        return auth[1] 
Example #2
Source File: views.py    From caluma with GNU General Public License v3.0 6 votes vote down vote up
def get_bearer_token(self, request):
        auth = get_authorization_header(request).split()
        header_prefix = "Bearer"

        if not auth:
            return None

        if smart_text(auth[0].lower()) != header_prefix.lower():
            raise HttpError(HttpResponseUnauthorized("No Bearer Authorization header"))

        if len(auth) == 1:
            msg = "Invalid Authorization header. No credentials provided"
            raise HttpError(HttpResponseUnauthorized(msg))
        elif len(auth) > 2:
            msg = (
                "Invalid Authorization header. Credentials string should "
                "not contain spaces."
            )
            raise HttpError(HttpResponseUnauthorized(msg))

        return auth[1] 
Example #3
Source File: authentication.py    From diting with GNU General Public License v2.0 6 votes vote down vote up
def authenticate(self, request):
        auth = authentication.get_authorization_header(request).split()
        if not auth or auth[0].lower() != self.keyword.lower().encode():
            return None

        if len(auth) == 1:
            msg = _('Invalid token header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid token header. Sign string '
                    'should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            token = auth[1].decode()
        except UnicodeError:
            msg = _('Invalid token header. Sign string '
                    'should not contain invalid characters.')
            raise exceptions.AuthenticationFailed(msg)
        return self.authenticate_credentials(token) 
Example #4
Source File: authentication.py    From django-rest-framework-oauth with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def authenticate(self, request):
        """
        Returns two-tuple of (user, token) if authentication succeeds,
        or None otherwise.
        """

        auth = get_authorization_header(request).split()

        if len(auth) == 1:
            msg = 'Invalid bearer header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = 'Invalid bearer header. Token string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        if auth and auth[0].lower() == b'bearer':
            access_token = auth[1]
        elif 'access_token' in request.POST:
            access_token = request.POST['access_token']
        elif 'access_token' in request.GET and self.allow_query_params_token:
            access_token = request.GET['access_token']
        else:
            return None

        return self.authenticate_credentials(request, access_token) 
Example #5
Source File: backend.py    From boss-oidc with Apache License 2.0 6 votes vote down vote up
def get_access_token(request):
    """Retrieve access token from the request

    The access token is searched first the request's session. If it is not
    found it is then searched in the request's ``Authorization`` header.

    Args:
        request (Request): Django request from the user

    Returns:
        dict: JWT payload of the bearer token
    """
    access_token = request.session.get("access_token")
    if access_token is None:  # Bearer token login
        access_token = get_authorization_header(request).split()[1]
    return JWT().unpack(access_token).payload() 
Example #6
Source File: drf.py    From mozilla-django-oidc with Mozilla Public License 2.0 6 votes vote down vote up
def get_access_token(self, request):
        """
        Get the access token based on a request.

        Returns None if no authentication details were provided. Raises
        AuthenticationFailed if the token is incorrect.
        """
        header = authentication.get_authorization_header(request)
        if not header:
            return None
        header = header.decode(authentication.HTTP_HEADER_ENCODING)

        auth = header.split()

        if auth[0].lower() != 'bearer':
            return None

        if len(auth) == 1:
            msg = 'Invalid "bearer" header: No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = 'Invalid "bearer" header: Credentials string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        return auth[1] 
Example #7
Source File: authentication.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def authenticate(self, request):
        auth_header = get_authorization_header(request).decode().split()

        if not auth_header or auth_header[0].lower() != self.keyword.lower():
            return None

        email = auth_header[1]

        return self.authenticate_credentials(email) 
Example #8
Source File: authentication.py    From GloboNetworkAPI with Apache License 2.0 5 votes vote down vote up
def authenticate(self, request):
        """
        Returns a `User` if a correct username and password have been supplied
        using HTTP Basic authentication.  Otherwise returns `None`.
        """
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'basic':
            return None

        if len(auth) == 1:
            msg = 'Invalid basic header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = 'Invalid basic header. Credentials string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            auth_parts = base64.b64decode(auth[1]).decode(
                HTTP_HEADER_ENCODING).partition(':')
        except (TypeError, UnicodeDecodeError):
            msg = 'Invalid basic header. Credentials not correctly base64 encoded'
            raise exceptions.AuthenticationFailed(msg)

        userid, password = auth_parts[0], auth_parts[2]
        return self.authenticate_credentials(userid, password) 
Example #9
Source File: views.py    From django-user-management with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def delete(self, request, *args, **kwargs):
        """Delete auth token when `delete` request was issued."""
        # Logic repeated from DRF because one cannot easily reuse it
        auth = get_authorization_header(request).split()

        if not auth or auth[0].lower() != b'token':
            return response.Response(status=status.HTTP_400_BAD_REQUEST)

        if len(auth) == 1:
            msg = 'Invalid token header. No credentials provided.'
            return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
        elif len(auth) > 2:
            msg = 'Invalid token header. Token string should not contain spaces.'
            return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)

        try:
            token = self.model.objects.get(key=auth[1])
        except self.model.DoesNotExist:
            pass
        else:
            token.delete()
            signals.user_logged_out.send(
                type(self),
                user=token.user,
                request=request,
            )
        return response.Response(status=status.HTTP_204_NO_CONTENT) 
Example #10
Source File: utils.py    From djangorestframework-auth0 with MIT License 5 votes vote down vote up
def get_auth_token(request):
    """
    Return the current request auth token.

    The token is get using HTTP_AUTHORIZATION header on each request, or
    using a cookie if AUTH_COOKIE_NAME setting is set.

    The header is validated in order to ensure request is formatted as needed.

    A valid authorization header look like(default settings):
    ```
    Authorization: Bearer <auth0_generated_token>
    ```
    """
    logger.debug(
        "Getting auth token"
    )

    auth_header = get_authorization_header(request).split()
    auth_token = None

    if validate_authorization_header(auth_header):
        logger.debug(
            "Authorization header is valid"
        )
        auth_token = force_str(auth_header[1])

    # If authorization header doesn't exists, use a cookie
    elif not auth_header and auth0_api_settings.AUTH_COOKIE_NAME:
        logger.warning(
            "Using Cookie instead of header"
        )
        auth_token = request.COOKIES.get(auth0_api_settings.AUTH_COOKIE_NAME)

    else:
        logger.debug(
            "Invalid authorization header"
        )
        auth_token = None  # Just for maker it clear

    return auth_token 
Example #11
Source File: authentication.py    From django-oidc-rp with MIT License 5 votes vote down vote up
def authenticate(self, request):
        """ Authenticates users using a provided Bearer token. """
        # First step, retrieves the Bearer token from the authorization header.
        auth = get_authorization_header(request).split()
        if not auth or smart_text(auth[0].lower()) != 'bearer':
            return

        if len(auth) == 1:
            raise AuthenticationFailed('Invalid authorization header; no bearer token provided')
        elif len(auth) > 2:
            raise AuthenticationFailed('Invalid authorization header; many bearer tokens provided')

        bearer_token = smart_text(auth[1])

        # Tries to retrieve user information from the OP.
        try:
            userinfo_response = requests.get(
                oidc_rp_settings.PROVIDER_USERINFO_ENDPOINT,
                headers={'Authorization': 'Bearer {0}'.format(bearer_token)})
            userinfo_response.raise_for_status()
        except HTTPError:
            raise AuthenticationFailed('Bearer token seems invalid or expired.')
        userinfo_response_data = userinfo_response.json()

        # Tries to retrieve a corresponding user in the local database and creates it if applicable.
        try:
            oidc_user = OIDCUser.objects.select_related('user').get(
                sub=userinfo_response_data.get('sub'))
        except OIDCUser.DoesNotExist:
            oidc_user = create_oidc_user_from_claims(userinfo_response_data)
            oidc_user_created.send(sender=self.__class__, request=request, oidc_user=oidc_user)
        else:
            update_oidc_user_from_claims(oidc_user, userinfo_response_data)

        return oidc_user.user, bearer_token 
Example #12
Source File: authentication.py    From diting with GNU General Public License v2.0 5 votes vote down vote up
def authenticate(self, request):
        auth = authentication.get_authorization_header(request).split()
        if not auth or auth[0].lower() != self.keyword.lower().encode():
            return None

        if len(auth) == 1:
            msg = _('Invalid signature header. No credentials provided.')
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid signature header. Signature '
                    'string should not contain spaces.')
            raise exceptions.AuthenticationFailed(msg)

        try:
            sign = auth[1].decode().split(':')
            if len(sign) != 2:
                msg = _('Invalid signature header. '
                        'Format like AccessKeyId:Signature')
                raise exceptions.AuthenticationFailed(msg)
        except UnicodeError:
            msg = _('Invalid signature header. '
                    'Signature string should not contain invalid characters.')
            raise exceptions.AuthenticationFailed(msg)

        access_key_id = sign[0]
        try:
            uuid.UUID(access_key_id)
        except ValueError:
            raise exceptions.AuthenticationFailed('Access key id invalid')
        request_signature = sign[1]

        return self.authenticate_credentials(
            request, access_key_id, request_signature
        ) 
Example #13
Source File: api_authentication.py    From open-humans with MIT License 5 votes vote down vote up
def authenticate(self, request):
        """
        Raises an exception for an expired token, or returns two-tuple of
        (user, project) if authentication succeeds, or None otherwise.
        """
        request.oauth2_error = getattr(request, "oauth2_error", {})
        access_token = None
        try:
            auth = get_authorization_header(request).split()
            token = auth[1].decode()
            access_token = AccessToken.objects.get(token=token)
        except Exception:
            pass

        if access_token and access_token.is_expired():
            raise exceptions.AuthenticationFailed("Expired token.")

        auth = super(CustomOAuth2Authentication, self).authenticate(request)

        if auth:
            project = OAuth2DataRequestProject.objects.get(
                application=auth[1].application
            )
            return (auth[0], project)

        return auth 
Example #14
Source File: api_authentication.py    From open-humans with MIT License 5 votes vote down vote up
def authenticate(self, request):
        request.oauth2_error = getattr(request, "oauth2_error", {})
        auth = get_authorization_header(request).split()
        if not auth or auth[0].lower() != b"bearer":
            return None

        if len(auth) == 1:
            msg = "Invalid token header. No credentials provided."

            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = "Invalid token header. " "Token string should not contain spaces."

            raise exceptions.AuthenticationFailed(msg)

        try:
            token = auth[1].decode()
        except UnicodeError:
            msg = (
                "Invalid token header. "
                "Token string should not contain invalid characters."
            )

            raise exceptions.AuthenticationFailed(msg)

        return self.authenticate_credentials(token) 
Example #15
Source File: authentication.py    From django-rest-framework-sso with MIT License 5 votes vote down vote up
def authenticate(self, request):
        auth = get_authorization_header(request).split()
        authenticate_header = self.authenticate_header(request=request)

        if not auth or smart_text(auth[0].lower()) != authenticate_header.lower():
            return None

        if len(auth) == 1:
            msg = _("Invalid token header. No credentials provided.")
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _("Invalid token header. Token string should not contain spaces.")
            raise exceptions.AuthenticationFailed(msg)

        try:
            token = auth[1].decode()
        except UnicodeError:
            msg = _("Invalid token header. Token string should not contain invalid characters.")
            raise exceptions.AuthenticationFailed(msg)

        try:
            payload = decode_jwt_token(token=token)
        except jwt.exceptions.ExpiredSignature:
            msg = _("Signature has expired.")
            raise exceptions.AuthenticationFailed(msg)
        except jwt.exceptions.DecodeError:
            msg = _("Error decoding signature.")
            raise exceptions.AuthenticationFailed(msg)
        except jwt.exceptions.InvalidKeyError:
            msg = _("Unauthorized token signing key.")
            raise exceptions.AuthenticationFailed(msg)
        except jwt.exceptions.InvalidTokenError:
            raise exceptions.AuthenticationFailed()

        return self.authenticate_credentials(payload=payload, request=request) 
Example #16
Source File: authentication.py    From normandy with Mozilla Public License 2.0 5 votes vote down vote up
def authenticate(self, request):
        auth_header = get_authorization_header(request).decode().split()

        if not auth_header or auth_header[0].lower() != self.keyword.lower():
            return None

        access_token = auth_header[1]

        return self.authenticate_credentials(access_token) 
Example #17
Source File: authentication.py    From drf-oidc-auth with MIT License 5 votes vote down vote up
def get_jwt_value(self, request):
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.JWT_AUTH_HEADER_PREFIX.lower()

        if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            msg = _('Invalid Authorization header. No credentials provided')
            raise AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid Authorization header. Credentials string should not contain spaces.')
            raise AuthenticationFailed(msg)

        return auth[1] 
Example #18
Source File: authentication.py    From drf-oidc-auth with MIT License 5 votes vote down vote up
def get_bearer_token(self, request):
        auth = get_authorization_header(request).split()
        auth_header_prefix = api_settings.BEARER_AUTH_HEADER_PREFIX.lower()

        if not auth or smart_text(auth[0].lower()) != auth_header_prefix:
            return None

        if len(auth) == 1:
            msg = _('Invalid Authorization header. No credentials provided')
            raise AuthenticationFailed(msg)
        elif len(auth) > 2:
            msg = _('Invalid Authorization header. Credentials string should not contain spaces.')
            raise AuthenticationFailed(msg)

        return auth[1] 
Example #19
Source File: backends.py    From aws-workshop with MIT License 4 votes vote down vote up
def authenticate(self, request):
        """
        The `authenticate` method is called on every request, regardless of
        whether the endpoint requires authentication. 

        `authenticate` has two possible return values:

        1) `None` - We return `None` if we do not wish to authenticate. Usually
        this means we know authentication will fail. An example of
        this is when the request does not include a token in the
        headers.

        2) `(user, token)` - We return a user/token combination when 
        authentication was successful.

        If neither of these two cases were met, that means there was an error.
        In the event of an error, we do not return anything. We simple raise
        the `AuthenticationFailed` exception and let Django REST Framework
        handle the rest.
        """
        request.user = None

        # `auth_header` should be an array with two elements: 1) the name of
        # the authentication header (in this case, "Token") and 2) the JWT 
        # that we should authenticate against.
        auth_header = authentication.get_authorization_header(request).split()
        auth_header_prefix = self.authentication_header_prefix.lower()

        if not auth_header:
            return None

        if len(auth_header) == 1:
            # Invalid token header. No credentials provided. Do not attempt to
            # authenticate.
            return None

        elif len(auth_header) > 2:
            # Invalid token header. Token string should not contain spaces. Do
            # not attempt to authenticate.
            return None

        # The JWT library we're using can't handle the `byte` type, which is
        # commonly used by standard libraries in Python 3. To get around this,
        # we simply have to decode `prefix` and `token`. This does not make for
        # clean code, but it is a good decision because we would get an error
        # if we didn't decode these values.
        prefix = auth_header[0].decode('utf-8')
        token = auth_header[1].decode('utf-8')

        if prefix.lower() != auth_header_prefix:
            # The auth header prefix is not what we expected. Do not attempt to
            # authenticate.
            return None

        # By now, we are sure there is a *chance* that authentication will
        # succeed. We delegate the actual credentials authentication to the
        # method below.
        return self._authenticate_credentials(request, token) 
Example #20
Source File: backends.py    From trace-examples with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def authenticate(self, request):
        """
        The `authenticate` method is called on every request, regardless of
        whether the endpoint requires authentication. 

        `authenticate` has two possible return values:

        1) `None` - We return `None` if we do not wish to authenticate. Usually
        this means we know authentication will fail. An example of
        this is when the request does not include a token in the
        headers.

        2) `(user, token)` - We return a user/token combination when 
        authentication was successful.

        If neither of these two cases were met, that means there was an error.
        In the event of an error, we do not return anything. We simple raise
        the `AuthenticationFailed` exception and let Django REST Framework
        handle the rest.
        """
        request.user = None

        # `auth_header` should be an array with two elements: 1) the name of
        # the authentication header (in this case, "Token") and 2) the JWT 
        # that we should authenticate against.
        auth_header = authentication.get_authorization_header(request).split()
        auth_header_prefix = self.authentication_header_prefix.lower()

        if not auth_header:
            return None

        if len(auth_header) == 1:
            # Invalid token header. No credentials provided. Do not attempt to
            # authenticate.
            return None

        elif len(auth_header) > 2:
            # Invalid token header. Token string should not contain spaces. Do
            # not attempt to authenticate.
            return None

        # The JWT library we're using can't handle the `byte` type, which is
        # commonly used by standard libraries in Python 3. To get around this,
        # we simply have to decode `prefix` and `token`. This does not make for
        # clean code, but it is a good decision because we would get an error
        # if we didn't decode these values.
        prefix = auth_header[0].decode('utf-8')
        token = auth_header[1].decode('utf-8')

        if prefix.lower() != auth_header_prefix:
            # The auth header prefix is not what we expected. Do not attempt to
            # authenticate.
            return None

        # By now, we are sure there is a *chance* that authentication will
        # succeed. We delegate the actual credentials authentication to the
        # method below.
        return self._authenticate_credentials(request, token) 
Example #21
Source File: authentication.py    From django-rest-framework-social-oauth2 with MIT License 4 votes vote down vote up
def authenticate(self, request):
        """
        Returns two-tuple of (user, token) if authentication succeeds,
        or None otherwise.
        """
        auth_header = get_authorization_header(request).decode(HTTP_HEADER_ENCODING)
        auth = auth_header.split()

        if not auth or auth[0].lower() != 'bearer':
            return None

        if len(auth) == 1:
            msg = 'Invalid token header. No backend provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) == 2:
            msg = 'Invalid token header. No credentials provided.'
            raise exceptions.AuthenticationFailed(msg)
        elif len(auth) > 3:
            msg = 'Invalid token header. Token string should not contain spaces.'
            raise exceptions.AuthenticationFailed(msg)

        token = auth[2]
        backend = auth[1]

        strategy = load_strategy(request=request)

        try:
            backend = load_backend(strategy, backend, reverse("%s:%s:complete" % (DRFSO2_URL_NAMESPACE, NAMESPACE), args=(backend,)))
        except MissingBackend:
            msg = 'Invalid token header. Invalid backend.'
            raise exceptions.AuthenticationFailed(msg)

        try:
            user = backend.do_auth(access_token=token)
        except requests.HTTPError as e:
            msg = e.response.text
            raise exceptions.AuthenticationFailed(msg)

        if not user:
            msg = 'Bad credentials.'
            raise exceptions.AuthenticationFailed(msg)
        return user, token 
Example #22
Source File: backends.py    From cruzz with MIT License 4 votes vote down vote up
def authenticate(self, request):
        """
        The `authenticate` method is called on every request regardless of
        whether the endpoint requires authentication.

        `authenticate` has two possible return values:

        1) `None` - `None` if we do not wish to authenticate due
                    to some errors or something is missing.
        2) `(user, token)` - user/token combination when
                             authentication is successful.

        If neither case is met, We simple raise the `AuthenticationFailed`
        exception.
        """
        request.user = None

        # `auth_header` should be an array with two elements:
        # 1) the name of the authentication header
        # 2) the JWT that we should authenticate against.
        auth_header = authentication.get_authorization_header(request).split()
        auth_header_prefix = self.authentication_header_prefix.lower()

        if not auth_header:
            return None

        if len(auth_header) == 1:
            # Invalid token header. No credentials provided.
            return None

        elif len(auth_header) > 2:
            # Invalid token header. The Token string should not contain spaces.
            return None

        # non unicode strings, need decoding here.
        prefix = auth_header[0].decode('utf-8')
        token = auth_header[1].decode('utf-8')

        if prefix.lower() != auth_header_prefix:
            # The auth header prefix is not what we expected.
            return None

        return self._authenticate_credentials(request, token)