Пример #1
0
 def get_jwt_token(self, user):
     now = int(time())
     rand = ''.join([choice(string.ascii_letters) for _ in range(10)])
     rands = f'{rand}.{now}'
     jws = JsonWebSignature(algorithms=JWS_ALGORITHMS)
     headers = {'alg': 'HS256'}
     payload = json.dumps({'email': user.email})
     secret = bytes(self.app.config['SECRET_KEY'], 'utf-8')
     return jws.serialize_compact(headers, payload, secret)
Пример #2
0
def json_sign(msg: Union[dict, str], privKey: str) -> dict:
    msg: dict = json.loads(msg) if isinstance(msg, str) else msg
    if not privKey:
        raise ValueError("privKey was not passed as a param")

    header = {
        "alg": "ES256",
        "kid": msg.get("headers", {}).get("from", "ORIGIN")
    }
    sig_payload = b".".join([
        base64.b64encode(canonicaljson.encode_canonical_json(header)),
        base64.b64encode(canonicaljson.encode_canonical_json(msg))
    ])
    jws = JsonWebSignature()
    key = Path(privKey).read_bytes()
    sig = jws.serialize_compact(header, sig_payload,
                                key).decode("utf-8").split('.')
    msg["signature"] = f"{sig[0]}..{sig[2]}"
    return msg
Пример #3
0
def sign_credential(credential, key):
    """
    Sign credential with RSA key of the did, add the signature as linked data JSONLD
    @parma credential as a dict
    #param key a string PEM private RSA key
    return signed credential as a dict
    """
    payload = json.dumps(credential)
    credential_jws = JsonWebSignature(algorithms=['RS256'])
    protected = {'alg': 'RS256'}
    signature = credential_jws.serialize_compact(protected, payload,
                                                 key.encode()).decode()
    credential["proof"] = {
        "type": "RsaSignature2018",
        "created": datetime.now().strftime("%m/%d/%Y, %H:%M:%S"),
        "proofPurpose": "assertionMethod",
        "verificationMethod": "https://talao.readthedocs.io/en/latest/",
        "jws": signature
    }
    return credential
    def get_token(self):
        """Return a JWT token and expiration time for making API calls to Small World Community

        Arguments to this function will, by default, use environmental variables if they are present (noted below)

        :param community_domain: the FQDN of the community instance (SWC_AUDIENCE)
        :param app_id: the the Oauth Application ID being used to connect to the community API (SWC_APP_ID)
        :param user_id: The SWC User ID of the authorized user attached to this Oauth Application (SWC_USER_ID)
        :return: A tuple with token to use with request calls and the time (in seconds) when the token will expire
        """
        exp = int(time.time()) + TOKEN_DURATION
        payload = {
            "iss": self.app_id,
            "iat": int(time.time()),
            "aud": self.community_domain,
            "exp": exp,
            "sub": self.user_id,
            "scope": SWC_SCOPE,
        }
        jws = JsonWebSignature(["HS256"])
        auth_token = jws.serialize_compact(
            JWT_TOKEN_HEADER,
            bytearray(json.dumps(payload), "utf-8"),
            bytearray(self.app_secret, "utf-8"),
        )
        swc_token_url = f"https://{self.community_domain}/services/4.0/token"
        token_request = requests.post(
            swc_token_url,
            data={
                "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
                "assertion": auth_token.decode("utf-8"),
                "content_type": "application/x-www-form-urlencoded",
            },
        )
        token_request.raise_for_status()
        token = token_request.json().get("access_token")
        return token, exp
Пример #5
0
def test_keys():
    """Try to store/get/remove keys"""
    # JWS
    jws = JsonWebSignature(algorithms=["RS256"])
    code_payload = {
        "user_id": "user",
        "scope": "scope",
        "client_id": "client",
        "redirect_uri": "redirect_uri",
        "code_challenge": "code_challenge",
    }

    # Token metadata
    header = {"alg": "RS256"}
    payload = {
        "sub": "user",
        "iss": "issuer",
        "scope": "scope",
        "setup": "setup",
        "group": "my_group"
    }

    # Remove all keys
    result = db.removeKeys()
    assert result["OK"], result["Message"]

    # Check active keys
    result = db.getActiveKeys()
    assert result["OK"], result["Message"]
    assert result["Value"] == []

    # Create new one
    result = db.getPrivateKey()
    assert result["OK"], result["Message"]

    private_key = result["Value"]
    assert isinstance(private_key, RSAKey)

    # Sign token
    header["kid"] = private_key.thumbprint()

    # Find key by KID
    result = db.getPrivateKey(header["kid"])
    assert result["OK"], result["Message"]
    # as_dict has no arguments for authlib < 1.0.0
    # for authlib >= 1.0.0:
    assert result["Value"].as_dict(True) == private_key.as_dict(True)

    # Sign token
    token = jwt.encode(header, payload, private_key)
    # Sign auth code
    code = jws.serialize_compact(header, json_b64encode(code_payload),
                                 private_key)

    # Get public key set
    result = db.getKeySet()
    keyset = result["Value"]
    assert result["OK"], result["Message"]
    # as_dict has no arguments for authlib < 1.0.0
    # for authlib >= 1.0.0:
    assert bool([
        key for key in keyset.as_dict(True)["keys"]
        if key["kid"] == header["kid"]
    ])

    # Read token
    _payload = jwt.decode(token, JsonWebKey.import_key_set(keyset.as_dict()))
    assert _payload == payload
    # Read auth code
    data = jws.deserialize_compact(code, keyset.keys[0])
    _code_payload = json_loads(urlsafe_b64decode(data["payload"]))
    assert _code_payload == code_payload