示例#1
0
def fetch_token_header_payload(token):
    """
    Fetch the header and payload out of the JWT token.
    :param token:
    :return: :raise jwt.DecodeError:
    """
    token = token.encode('utf-8')
    try:
        signing_input, crypto_segment = token.rsplit(b'.', 1)
        header_segment, payload_segment = signing_input.split(b'.', 1)
    except ValueError:
        raise jwt.DecodeError('Not enough segments')

    try:
        header = json.loads(
            jwt.utils.base64url_decode(header_segment).decode('utf-8'))
    except TypeError as e:
        current_app.logger.exception(e)
        raise jwt.DecodeError('Invalid header padding')

    try:
        payload = json.loads(
            jwt.utils.base64url_decode(payload_segment).decode('utf-8'))
    except TypeError as e:
        current_app.logger.exception(e)
        raise jwt.DecodeError('Invalid payload padding')

    return (header, payload)
示例#2
0
def jwt_decode_handler(token, get_api_key=APIKey.get_jwt_key):
    token_data = jwt.decode(token, verify=False)
    if 'iss' not in token_data:
        log.info('No issuer in JWT auth token: {}'.format(token_data))
        raise jwt.DecodeError('invalid JWT')

    try:
        api_key = get_api_key(key=token_data['iss'])
    except ObjectDoesNotExist, exc:
        log.info('No API key for JWT issuer: {}'.format(token_data['iss']))
        raise jwt.DecodeError('unknown JWT issuer')
def _unpack_authorization_header(header):
    """
    valid input: "JWT abcdef..."
    """
    if not header:
        raise jwt.DecodeError()

    try:
        auth_type, token = header.split()
        return auth_type, token
    except:
        raise jwt.DecodeError()
示例#4
0
def worker_from_jwt(encoded: str) -> WorkerJWT:
    if not _keys:
        _load(WORKER_JWTS_DIR)

    kid = jwt.get_unverified_header(encoded).get("kid")
    if not kid:
        raise jwt.DecodeError("Token is missing required `kid` header")
    cert = _keys.get(kid)
    if not cert:
        raise jwt.InvalidKeyError("No certificate found with id " + kid)

    decoded = jwt.decode(encoded, cert.public_key(), algorithms=["ES256"])
    try:
        decoded.pop("exp")
    except KeyError:
        raise jwt.MissingRequiredClaimError("exp")

    try:
        name = decoded.pop("name")
    except KeyError:
        raise jwt.MissingRequiredClaimError("name")

    allowed = []
    ous = cert.subject.get_attributes_for_oid(NameOID.ORGANIZATIONAL_UNIT_NAME)
    if ous:
        allowed = [x.value for x in ous]
    return WorkerJWT(name, allowed)
示例#5
0
    def authenticate(self, auth_token):
        try:
            token_payload = jwt.decode(auth_token,
                                       secret,
                                       algorithms=["HS256"])
            user_id = token_payload.get('user_id', None)
            if not user_id:
                raise jwt.DecodeError("No user_id field found")

            self.user_id = user_id
            self.authenticated = True
            self.auth_failures = 0
            self.send_json(actionType='AUTH OK')

            # If we are the first websocket connecting on behalf of
            # a given user, subscribe to the feed for that user
            if len(WebSocket.sockets[user_id]) == 0:
                WebSocket.subscribe(user_id)

            WebSocket.sockets[user_id].add(self)

        except jwt.DecodeError:
            self.send_json(actionType='AUTH FAILED')
        except jwt.ExpiredSignatureError:
            self.send_json(actionType='AUTH FAILED')
示例#6
0
def get_jwt_key():
    key = settings.BADGEKIT_JWT_KEY
    if not key:
        logger.error(
            'Got a webhook request, but no BADGEKIT_JWT_KEY configured! Rejecting.'
        )
        raise jwt.DecodeError('No JWT Key')
    return key
示例#7
0
def fetch_token_header(token):
    """
    Fetch the header out of the JWT token.

    :param token:
    :return: :raise jwt.DecodeError:
    """
    token = token.encode("utf-8")
    try:
        signing_input, crypto_segment = token.rsplit(b".", 1)
        header_segment, payload_segment = signing_input.split(b".", 1)
    except ValueError:
        raise jwt.DecodeError("Not enough segments")

    try:
        return json.loads(jwt.utils.base64url_decode(header_segment).decode("utf-8"))
    except TypeError as e:
        current_app.logger.exception(e)
        raise jwt.DecodeError("Invalid header padding")
示例#8
0
    def test_decode_token_fails(self, mock_decode):
        mock_decode.side_effect = jwt.DecodeError("fail")
        resp = self.client.post(
            path=webhook_url,
            data=EXAMPLE_MEMBER_ADDED,
            format="json",
            HTTP_AUTHORIZATION=u"Bearer %s" % TOKEN,
        )

        assert resp.data["detail"] == "Could not decode JWT token"
        assert resp.status_code == 403
示例#9
0
 def get_user(self, token):
     """Gets the user from credentials object. None if no credentials.
     Can raise jwt.ExpiredSignature and jwt.DecodeError"""
     profile = self.get_profile(token)
     if not profile:
         return None
     username = profile.get("user", None)
     user = self.server_store.read_user(username)
     # Timestamp must match with the stored in user, if not,
     # this token is not valid (password has been changed)
     password_timestamp = profile["password_timestamp"]
     if password_timestamp != user.password_timestamp:
         logger.debug("Timestamp doesn't match!")
         raise jwt.DecodeError("Timestamp doesn't match!")
     return username
示例#10
0
    def wrapper(*args, **kwargs):
        if not settings.IS_AUTH_REQUIRED:
            return func(*args, **kwargs)

        if 'Authorization' not in request.headers:
            raise_unauthorized()

        try:
            auth_type, token = _unpack_authorization_header(request.headers['Authorization'])

            if auth_type != 'JWT':
                raise jwt.DecodeError()
            
            jwt.decode(token, settings.SECRET_KEY)
        except (jwt.DecodeError, jwt.ExpiredSignatureError):
            raise_unauthorized()

        return func(*args, **kwargs)
示例#11
0
def myDecode(token, secret):
    payloadValided = False
    try:
        payloadValided = jwt.decode(token,
                                    secret,
                                    algorithms=['HS256', 'HS512'],
                                    verify=False)
    except jwt.ExpiredSignatureError:
        raise jwt.ExpiredSignatureError(
            'You take too much time for getting your token.',
            'You need to login again')
    except jwt.InvalidTokenError:
        raise jwt.InvalidTokenError('Exception when decode()')
    except jwt.DecodeError:
        raise jwt.DecodeError('We canno\'t decode your token')
    except jwt.InvalidSignatureError:
        raise jwt.InvalidSignatureError(
            'Your token’s signature doesn’t match'
            ' the one provided as part of the token')
    return payloadValided
示例#12
0
def basicAccess(request, response, level="basic", context=None, **kwargs):
    """Token verification"""
    token = request.get_header('Authorization')
    if token:
        if token.split("Bearer ", 1)[1]:
            token = token.split("Bearer ", 1)[1]

            secret_key = getSecret()
            try:
                content = jwt.decode(token.encode('utf8'),
                                     secret_key,
                                     algorithm='HS256')
                if content["level"] == level or level == "basic":
                    response.append_header('locals', content)
                    return True
                raise jwt.DecodeError()
            except jwt.DecodeError:
                response.status = HTTP_403
                return {"error": "access_denied"}
        response.status = HTTP_403
        return {"error": "access_denied"}
    response.status = HTTP_403
    return {"error": "access_denied"}
 def resolve(self, event):
     
     is_authenticated = self.validate_authorization_header(event)
     if not is_authenticated:
         raise jwt.DecodeError("Unauthorized")
     return event
示例#14
0
 def patched_sys_stdin_read():
     raise jwt.DecodeError()
示例#15
0
        async def wrapped_f(me, req: Request, resp: Response, *args, **kwargs):
            # pylint: disable=too-many-branches
            resp.status_code = 401
            if req.state.api.secret_key is None:
                logger.critical(
                    "No secret key configured for this application. Check your configuration."
                )
                resp.text = "No secret key configured"
            else:
                try:
                    # Check the header.
                    bearer = req.headers["Authorization"]
                    scheme, token = bearer.split(" ")
                    logger.debug("We have a scheme (%s) and a token (%s)", scheme, token)
                    # We could and we should do more test if
                    # the provided token is correct formatted.
                    if scheme == "Bearer":
                        # Currently only the Bearer scheme
                        try:
                            payload = decode_bearer_token(token, req.state.api.secret_key)
                            logger.debug("Payload: %s", payload)
                            user_id = payload.get("user_id", None)
                            logger.debug("Token %s", token)
                            logger.debug(
                                "We have a valid bearer token and the id is %d",
                                user_id,
                            )
                            if user_id is None:
                                raise jwt.DecodeError()

                            # Now we need the user
                            # user = await UserPool.get_user(user_id)
                            user = await models.User.get(id=user_id)
                            logger.debug("We have a user. The login is %s", user.login)

                            # Let's see, if we have to check some rights
                            logger.debug(
                                "Now see, if the user has one of the rights: %s",
                                self.rights,
                            )
                            if self.rights is not None:
                                # Yes, we have to
                                needed_rights = await check_rights(user, self.rights)
                                logger.debug("Matching rights: %s", needed_rights)
                                if not needed_rights:
                                    # None of the requierements are fullfilled
                                    raise InsufficientRights(
                                        f"User has non of the following rights {self.rights}"
                                    )
                                # If the calling instance has a user_right attribute,
                                # subset of requested rights, the user has are stored
                                # in that attribute
                                if hasattr(me, "user_rights"):
                                    setattr(me, "user_rights", needed_rights)

                                # Also save the rights to the request state
                                req.state.user_rights = needed_rights

                            # The current user is stored in the calling instance, if the
                            # instance has a current_user attribute, which is true for all
                            # Classes derived from BaseRessource
                            if hasattr(me, "current_user"):
                                setattr(me, "current_user", user)

                            # Saving the current user in the request state
                            req.state.current_user = user

                            # newkwargs.update(kwargs)
                            # Everythings fine
                            resp.status_code = 200
                            logger.debug("Caller class: %r", me)
                            return await f(me, req, resp, *args, **kwargs)

                        except jwt.ExpiredSignatureError:
                            logger.exception("Token expired")
                            resp.text = "Token expired"
                        except jwt.DecodeError:
                            logger.exception("Bad bearer token")
                            resp.text = "Bad bearer token"
                        except DoesNotExist:
                            logger.exception("User does not exist")
                            resp.text = "No such user"
                        except InsufficientRights as error:
                            logger.exception("InsuffitienRights")
                            resp.text = str(error)
                        except Exception:
                            logger.critical("Unknown error", exc_info=True)
                    else:
                        resp.text = f"Unknown ot unsupported authorization scheme. {scheme}"
                except KeyError:
                    resp.text = "No authorization header provided"
                except ValueError:  # pylint: disable=broad-except
                    logger.exception("Something went wrong")
                    resp.status_code = 400
                    resp.text = "Bad Request"
示例#16
0
    options = {
        'verify_signature': True,
        'verify_exp': True,
        'verify_nbf': False,
        'verify_iat': True,
        'verify_aud': False,
        'require_exp': True,
        'require_iat': True,
        'require_nbf': False,
    }
    try:
        payload = jwt.decode(
            token,
            api_key.secret,
            verify=True,
            options=options,
            leeway=api_settings.JWT_LEEWAY,
            algorithms=[api_settings.JWT_ALGORITHM]
        )
    except Exception, exc:
        log.info(u'Exception during JWT authentication: '
                 u'{e.__class__.__name__}: {e}'.format(e=exc))
        raise

    if payload['exp'] - payload['iat'] > settings.MAX_JWT_AUTH_TOKEN_LIFETIME:
        log.info('JWT auth: expiration is too long; '
                 'iss={iss}, iat={iat}, exp={exp}'.format(**payload))
        raise jwt.DecodeError('Declared expiration was too long')

    return payload