示例#1
0
def get_current_user(db: Session = Depends(get_db),
                     token: str = Security(reusable_oauth2)):

    # try:
    #     payload = jwt.decode(token, config.SECRET_KEY, algorithms=[ALGORITHM])
    #     token_data = TokenPayload(**payload)
    # except PyJWTError:
    #     raise HTTPException(
    #         status_code=HTTP_403_FORBIDDEN, detail="Could not validate credentials"
    #     )
    # user = crud.user.get(db, user_id=token_data.user_id)
    # if not user:
    #     raise HTTPException(status_code=404, detail="User not found")
    # return user

    # get the kid from the headers prior to verification
    headers = jwt.get_unverified_headers(token)
    kid = headers['kid']
    # search for the kid in the downloaded public keys
    key_index = -1
    for i in range(len(keys)):
        if kid == keys[i]['kid']:
            key_index = i
            break
    if key_index == -1:
        logger.info('Public key not found in jwks.json')
        return False
    # construct the public key
    public_key = jwk.construct(keys[key_index])
    # get the last two sections of the token,
    # message and signature (encoded in base64)
    message, encoded_signature = str(token).rsplit('.', 1)
    # decode the signature
    decoded_signature = base64url_decode(encoded_signature.encode('utf-8'))
    # verify the signature
    if not public_key.verify(message.encode("utf8"), decoded_signature):
        logger.info('Signature verification failed')
        return False
    logger.info('Signature successfully verified')
    # since we passed the verification, we can now safely
    # use the unverified claims
    claims = jwt.get_unverified_claims(token)
    # additionally we can verify the token expiration
    if time.time() > claims['exp']:
        logger.info('Token is expired')
        raise HTTPException(status_code=404, detail="Sessions has expired.")
    # and the Audience  (use claims['client_id'] if verifying an access token)
    if claims['client_id'] != app_client_id:
        logger.info('Token was not issued for this audience')
        raise HTTPException(status_code=404,
                            detail="Unauthorized access. Access denied")
    # now we can use the claims
    # print(claims)

    user = crud.user.get(db, cognito_user_id=claims["sub"])
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user
示例#2
0
 def decorated(*args, **kwargs):
     token = JWTManager.get_token_auth_header(args[0])
     unverified_claims = jwt.get_unverified_claims(token)
     token_scopes = unverified_claims["scope"].split()
     for token_scope in token_scopes:
         if token_scope == required_scope:
             return f(*args, **kwargs)
     response = JsonResponse({'message': 'You don\'t have access to this resource'})
     response.status_code = 403
     return response
示例#3
0
def requires_scope(request, required_scope):
    """Determines if the required scope is present in the Access Token
    Args:
        required_scope (str): The scope required to access the resource
    """
    token = get_token_auth_header(request)
    unverified_claims = jwt.get_unverified_claims(token)
    if unverified_claims.get("scope"):
        token_scopes = unverified_claims["scope"].split()
        for token_scope in token_scopes:
            if token_scope == required_scope:
                return True
    return False
示例#4
0
    def check_token(self, renew=True):
        """
        Checks the exp attribute of the access_token and either refreshes
        the tokens by calling the renew_access_tokens method or does nothing
        :param renew: bool indicating whether to refresh on expiration
        :return: bool indicating whether access_token has expired
        """
        if not self.access_token:
            raise AttributeError('Access Token Required to Check Token')
        now = datetime.datetime.now()
        dec_access_token = jwt.get_unverified_claims(self.access_token)

        if now > datetime.datetime.fromtimestamp(dec_access_token['exp']):
            expired = True
            if renew:
                self.renew_access_token()
        else:
            expired = False
        return expired
示例#5
0
def requires_scope(req, resp, resource, params, required_scope):
    """Determines if the required scope is present in the access token
    Args:
        required_scope (str): The scope required to access the resource
    """

    _token = Auth0Middleware.get_token_auth_header(req)
    unverified_claims = jwt.get_unverified_claims(_token)
    if unverified_claims.get("scope"):
        token_scopes = unverified_claims["scope"].split()
        for token_scope in token_scopes:
            if token_scope == required_scope:
                return True

    logger.warning("User does not have the requiered scope: %s." %
                   required_scope)
    raise http_error_factory(
        status=HTTP_401,
        title="Invalid Scope",
        description="User does not have the requiered scope.",
        href=None,
        href_text=None,
        code=None,
    )
示例#6
0
def get_client_id_from_id_token(token):
    """ Pulls the audience (client id) out of an id_token
	"""
    # header, payload, _ = get_token_segments(token)
    payload = jwt.get_unverified_claims(token)
    return payload.get('aud')