Exemple #1
0
def deser_id_token(inst, str=""):
    if not str:
        return None

    jso = json.loads(jwt.unpack(str)[1])

    # gather all the necessary keys
    # my own first
    collection = inst.keystore.get_verify_key()

    if "iss" in jso:
        for key, val in inst.keystore.collect_keys(jso["iss"]).items():
            try:
                collection[key].extend(val)
            except KeyError:
                collection[key] = val

    if "aud" in jso:
        for key, val in inst.keystore.collect_keys(jso["aud"]).items():
            try:
                collection[key].extend(val)
            except KeyError:
                collection[key] = val

    jwt.verify(str, collection)

    return IdToken().from_dict(jso)
Exemple #2
0
    def __call__(self, environ, trace, location, response, content, features):
        _id_token = environ["response_message"]["id_token"]
        jso = json.loads(jwt.unpack(_id_token)[1])
        user_id = jso["user_id"]
        self.request_args["idtoken_claims"] = {"user_id": {"value": user_id}}

        return OpenIDRequestCode.__call__(self, environ, trace, location,
                                          response, content, features)
Exemple #3
0
def test_assertion_jwt():
    cli = Client("Foo")
    cli.client_secret = "secert"
    at = oic.assertion_jwt(cli, {}, audience="audience", algorithm="none")
    print at
    header, claim, crypto, header_b64, claim_b64 = unpack(at)
    jso = json.loads(claim)
    assert _eq(jso.keys(), ["aud", "iss", "prn", "jti", "exp", "iat"])
Exemple #4
0
    def _id_token(self, session, loa="2", keytype="rsa",
                  code=None, access_token=None, user_info=None):

        _idtoken = self.server.make_id_token(session, loa,
                                             self.name, keytype, code,
                                             access_token, user_info)

        logger.debug("id_token: %s" % unpack(_idtoken)[1])

        return _idtoken
Exemple #5
0
def test_1():
    claimset = {"iss":"joe",
                "exp":1300819380,
                "http://example.com/is_root": True}

    _jwt = jwt.pack(claimset)

    part = jwt.unpack(_jwt)
    print part
    assert part[0] == {u'alg': u'none'}
    assert part[1] == \
           '{"iss":"joe","exp":1300819380,"http://example.com/is_root":true}'
Exemple #6
0
def test_private_key_jwt():
    cli = Client("FOO")
    cli.token_endpoint = "https://example.com/token"
    cli.keystore.set_sign_key(rsapub, "rsa")
    cli.keystore.set_verify_key(rsapub, "rsa")

    cis = AccessTokenRequest()
    at = oic.private_key_jwt(cli, cis)
    assert at == {}
    cas = cis["client_assertion"]
    header, claim, crypto, header_b64, claim_b64 = unpack(cas)
    jso = json.loads(claim)
    assert _eq(jso.keys(), ["aud", "iss", "prn", "jti", "exp", "iat"])
    print header
    assert header == {"alg": "RS256"}
Exemple #7
0
def test_client_secret_jwt():
    cli = Client("Foo")
    cli.token_endpoint = "https://example.com/token"
    cli.client_secret = "foobar"

    cis = AccessTokenRequest()
    at = oic.client_secret_jwt(cli, cis)
    assert at == {}
    assert cis["client_assertion_type"] == JWT_BEARER
    assert "client_assertion" in cis
    cas = cis["client_assertion"]
    header, claim, crypto, header_b64, claim_b64 = unpack(cas)
    jso = json.loads(claim)
    assert _eq(jso.keys(), ["aud", "iss", "prn", "jti", "exp", "iat"])
    print header
    assert header == {"alg": "HS256"}
Exemple #8
0
def test_make_id_token():
    srv = Server(KEYS)
    session = {"user_id": "user0", "client_id": "http://oic.example/rp"}
    issuer = "http://oic.example/idp"
    code = "abcdefghijklmnop"
    idt_jwt = srv.make_id_token(session, loa="2", issuer=issuer, code=code, access_token="access_token")

    jwt_keys = srv.keystore.get_keys("ver", owner=None)
    idt = IdToken().from_jwt(idt_jwt, key=jwt_keys)
    print idt
    header = unpack(idt_jwt)

    lha = left_hash(code, func="HS" + header[0]["alg"][-3:])
    assert lha == idt["c_hash"]

    atr = AccessTokenResponse(id_token=idt_jwt, access_token="access_token", token_type="Bearer")
    atr["code"] = code
    assert atr.verify(key=jwt_keys)
Exemple #9
0
    def from_jwt(self, txt, key, verify=True):
        """
        Given a signed JWT, verify its correctness and then create a class
        instance from the content.

        :param txt: The JWT
        :param key: keys that might be used to verify the signature of the JWT
        :param verify: Whether the signature should be verified or not
        :return: A class instance
        """
        try:
            jso = jwt.unpack(txt)[1]
            if isinstance(jso, basestring):
                jso = json.loads(jso)
            if verify:
                if key is None:
                    key = {}

                try:
                    _keys = key['.']
                except KeyError:
                    _keys = {}

                for ent in ["iss", "aud", "client_id"]:
                    _keys = gather_keys(_keys, key, jso, ent)

                if "iss" not in jso and "aud" not in jso:
                    for owner, _spec in key.items():
                        if owner == ".":
                            continue
                        for typ, keys in _spec.items():
                            try:
                                _keys[typ].extend(keys)
                            except KeyError:
                                _keys[typ] = keys

                jwt.verify(txt, _keys)
        except Exception:
            raise

        return self.from_dict(jso)
Exemple #10
0
    def verify(self, **kwargs):
        if "aud" in self:
            if "client_id" in kwargs:
                # check that it's for me
                if self["aud"] != kwargs["client_id"]:
                    return False

        if "id_token" in self:
            # Try to decode the JWT, checks the signature
            idt = IdToken().from_jwt(str(self["id_token"]), kwargs["key"])
            if not idt.verify(**kwargs):
                return False

            hfunc = "HS"+ jwt.unpack(self["id_token"])[0]["alg"][-3:]

            if "access_token" in self:
                try:
                    assert "at_hash" in idt
                except AssertionError:
                    raise Exception("Missing at_hash property")
                try:
                    assert idt["at_hash"] == jwt.left_hash(
                        self["access_token"], hfunc )
                except AssertionError:
                    raise Exception("Failed to verify access_token hash")

            if "code" in self:
                try:
                    assert "c_hash" in idt
                except AssertionError:
                    raise Exception("Missing c_hash property")
                try:
                    assert idt["c_hash"] == jwt.left_hash(self["code"], hfunc)
                except AssertionError:
                    raise Exception("Failed to verify code hash")

            self["id_token"] = idt

        return super(self.__class__, self).verify(**kwargs)