コード例 #1
0
    def authenticate(self, request):  # noqa  (too complex)
        token_value = extract_access_token(request)
        if not token_value:
            return None
        if token_value.count('.') != 4:
            logger.debug('[DeviceJWT]: Probably not a JWE-encrypted token')
            return None

        token = jwt.JWE()
        try:
            token.deserialize(token_value)
        except (jwe.InvalidJWEData, ValueError, TypeError) as e:
            logger.info('[DeviceJWT]: %s' % e)
            raise AuthenticationFailed("Invalid JWE")

        if 'iss' not in token.jose_header:
            raise AuthenticationFailed("'iss' field not present in token header")
        user_device_id = token.jose_header['iss']
        try:
            device = UserDevice.objects.get(id=user_device_id)
        except UserDevice.DoesNotExist:
            raise AuthenticationFailed("User device %s not registered" % user_device_id)

        enc_key = jwk.JWK(**device.secret_key)
        sign_key = jwk.JWK(**device.public_key)

        try:
            token = jwt.JWT()
            token.deserialize(token_value, key=enc_key)
            token.deserialize(token.claims, key=sign_key)
            claims = json.loads(token.claims)
        except (jwe.InvalidJWEData, ValueError, TypeError) as e:
            logger.info('[DeviceJWT]: %s' % e)
            raise AuthenticationFailed("Invalid encryption key or signature")

        auth_counter = claims.get('cnt', None)
        if not isinstance(auth_counter, int) or auth_counter <= device.auth_counter:
            raise AuthenticationFailed("Invalid 'cnt' field")

        device.auth_counter = auth_counter
        device.last_used_at = datetime.datetime.now(tz=local_tz)
        device.save(update_fields=('auth_counter', 'last_used_at'))

        interface_device_id = claims.get('azp', None)
        try:
            interface_device = InterfaceDevice.objects.get(id=interface_device_id)
        except InterfaceDevice.DoesNotExist:
            logger.info("Interface device {} in 'azp' not found".format(interface_device_id))
            raise AuthenticationFailed("Interface device in 'azp' not found")

        interface_secret = request.META.get('HTTP_X_INTERFACE_DEVICE_SECRET', '')
        if interface_secret != interface_device.secret_key:
            raise AuthenticationFailed("Incorrect interface device secret in X-Interface-Device-Secret HTTP header")

        nonce = claims.get('nonce', None)
        auth = TokenAuth(set(interface_device.scopes.split()), nonce=nonce)

        return (device.user, auth)
コード例 #2
0
 def authenticate(self, request):
     access_token = extract_access_token(request)
     try:
         token = Token.objects.get(access_token=access_token)
     except Token.DoesNotExist:
         raise AuthenticationFailed("invalid_token")
     if token.has_expired():
         raise AuthenticationFailed("invalid_token")
     request.token = token  # not an ideal side-affect, but required for now.
     return token
コード例 #3
0
ファイル: middleware.py プロジェクト: pinax/pinax-identity
 def __call__(self, request):
     access_token = extract_access_token(request)
     try:
         token = Token.objects.get(access_token=access_token)
     except Token.DoesNotExist:
         self.unauthenticated(request)
     else:
         if not token.has_expired():
             self.authenticated(request, token)
         else:
             self.unauthenticated(request)
     return self.get_response(request)
コード例 #4
0
    def authenticate(self, request):
        """
        Authenticate the request and return a tuple of (user, token) or None
        if there was no authentication attempt.
        """

        # access_token = self.get_access_token(request)
        access_token = extract_access_token(request)

        if not access_token:
            return None

        try:

            try:
                token = Token.objects.get(access_token=access_token)
            except Token.DoesNotExist:
                LOGGER.debug('[UserInfo] Token does not exist: %s',
                             access_token)
                raise AuthenticationFailed('Invalid_token')

            # if the token has an associated user, return it
            # otherwise (e.g. if using client_credentials), get_or_create a default API user
            user = token.user
            if not user:
                user = User.objects.get_or_create(
                    username='******')[0]

            return user, access_token

        except HTTPError as exc:
            resp = exc.response

            # if the oidc provider returns 401, it means the token is invalid.
            # in that case, we want to return the upstream error message (which
            # we can get from the www-authentication header) in the response.
            if resp.status_code == 401 and 'www-authenticate' in resp.headers:
                data = parse_www_authenticate_header(
                    resp.headers['www-authenticate'])
                raise AuthenticationFailed(data['error_description'])

            # for all other http errors, just re-raise the exception.
            raise

        except SuspiciousOperation as exc:
            LOGGER.info('Login failed: %s', exc)
            raise AuthenticationFailed('Login failed')

        return None
コード例 #5
0
    def _extract_params(self):
        token = extract_access_token(self.request)

        self.params['refresh_token'] = token

        if settings.get('OIDC_ALLOW_PARAMS_JSON_BODY'):
            body_unicode = self.request.body.decode('utf-8')
            body = json.loads(body_unicode)
            b_dict = dict(body)
            logger.error(b_dict)
            self.params['scope'] = b_dict.get('scope', '')
            self.params['grant_type'] = b_dict.get('grant_type', '')
        else:
            self.params['scope'] = self.request.POST.get('scope', '')
            self.params['grant_type'] = self.request.POST.get('grant_type', '')
コード例 #6
0
ファイル: authentication.py プロジェクト: jacqui/squarelet
    def authenticate(self, request):
        access_token = extract_access_token(request)

        if not access_token:
            # not this kind of auth
            return None

        try:
            oauth2_token = Token.objects.get(access_token=access_token)
        except Token.DoesNotExist:
            raise exceptions.AuthenticationFailed(
                "The oauth2 token is invalid")

        if oauth2_token.has_expired():
            raise exceptions.AuthenticationFailed(
                "The oauth2 token has expired")

        return oauth2_token.user, oauth2_token
コード例 #7
0
    def authenticate(self, request):
        access_token = extract_access_token(request)

        try:
            try:
                token = Token.objects.get(access_token=access_token)
            except Token.DoesNotExist:
                logger.debug('[OidcToken] Token does not exist: %s', access_token)
                return None

            if token.has_expired():
                logger.warning('[OidcToken] Token has expired: %s', access_token)
                raise BearerTokenError('invalid_token')

        except BearerTokenError as error:
            raise AuthenticationFailed(error.description)

        auth = TokenAuth(token.scope)

        return (token.user, auth)
コード例 #8
0
    def authenticate(self, request):
        access_token = extract_access_token(request)

        try:
            try:
                token = Token.objects.get(access_token=access_token)
            except Token.DoesNotExist:
                logger.debug('[UserInfo] Token does not exist: %s',
                             access_token)
                return None

            if token.has_expired():
                logger.debug('[UserInfo] Token has expired: %s', access_token)
                return None

            if "openid" not in set(token.scope):
                logger.debug('[UserInfo] Missing openid scope.')
                return None
        except BearerTokenError as error:
            return None

        return (token.user, None)
コード例 #9
0
    def authenticate(self, request):
        access_token = extract_access_token(request)

        try:
            try:
                token = Token.objects.get(access_token=access_token)
            except Token.DoesNotExist:
                logger.debug('[OidcToken] Token does not exist: %s',
                             access_token)
                return None

            if token.has_expired():
                logger.warning('[OidcToken] Token has expired: %s',
                               access_token)
                raise BearerTokenError('invalid_token')

        except BearerTokenError as error:
            raise AuthenticationFailed(error.description)

        auth = TokenAuth(token.scope)

        return (token.user, auth)
コード例 #10
0
    def authenticate(self, request):  # noqa  (too complex)
        token_value = extract_access_token(request)
        if not token_value:
            return None
        if token_value.count('.') != 4:
            logger.debug('[DeviceJWT]: Probably not a JWE-encrypted token')
            return None

        token = jwt.JWE()
        try:
            token.deserialize(token_value)
        except (jwe.InvalidJWEData, ValueError, TypeError) as e:
            logger.info('[DeviceJWT]: %s' % e)
            raise AuthenticationFailed("Invalid JWE")

        if 'iss' not in token.jose_header:
            raise AuthenticationFailed(
                "'iss' field not present in token header")
        user_device_id = token.jose_header['iss']
        try:
            device = UserDevice.objects.get(id=user_device_id)
        except UserDevice.DoesNotExist:
            raise AuthenticationFailed("User device %s not registered" %
                                       user_device_id)

        enc_key = jwk.JWK(**device.secret_key)
        sign_key = jwk.JWK(**device.public_key)

        try:
            token = jwt.JWT()
            token.deserialize(token_value, key=enc_key)
            token.deserialize(token.claims, key=sign_key)
            claims = json.loads(token.claims)
        except (jwe.InvalidJWEData, ValueError, TypeError) as e:
            logger.info('[DeviceJWT]: %s' % e)
            raise AuthenticationFailed("Invalid encryption key or signature")

        auth_counter = claims.get('cnt', None)
        if not isinstance(auth_counter,
                          int) or auth_counter <= device.auth_counter:
            raise AuthenticationFailed("Invalid 'cnt' field")

        device.auth_counter = auth_counter
        device.last_used_at = datetime.datetime.now(tz=local_tz)
        device.save(update_fields=('auth_counter', 'last_used_at'))

        interface_device_id = claims.get('azp', None)
        try:
            interface_device = InterfaceDevice.objects.get(
                id=interface_device_id)
        except InterfaceDevice.DoesNotExist:
            raise AuthenticationFailed("Interface device in 'azp' not found")

        interface_secret = request.META.get('HTTP_X_INTERFACE_DEVICE_SECRET',
                                            '')
        if interface_secret != interface_device.secret_key:
            raise AuthenticationFailed(
                "Incorrect interface device secret in X-Interface-Device-Secret HTTP header"
            )

        nonce = claims.get('nonce', None)
        auth = TokenAuth(set(interface_device.scopes.split()), nonce=nonce)

        return (device.user, auth)