Esempio n. 1
0
    def test_access_token_storage_with_custom_response_class(self):
        _state = "state"

        # AccessTokenResponse custom class
        class AccessTokenResponseWrapper(AccessTokenResponse):
            """Response wrapper to get "expires_in" in hours."""

            c_param = AccessTokenResponse.c_param.copy()
            c_param.update({"expires_in_hours": SINGLE_OPTIONAL_INT})

            def __init__(self, **kwargs):
                super(AccessTokenResponseWrapper, self).__init__(**kwargs)
                if "expires_in" in self and self["expires_in"]:
                    self["expires_in_hours"] = self["expires_in"] // 3600

        resp = AccessTokenResponseWrapper(
            access_token="2YotnFZFEjr1zCsiAB",
            token_type="Bearer",
            expires_in=3600,
            state=_state,
        )
        self.consumer.parse_response(AccessTokenResponseWrapper,
                                     resp.to_urlencoded(), "urlencoded")

        grant = self.consumer.grant[_state]
        assert len(grant.tokens) == 1
        assert grant.tokens[0].access_token == "2YotnFZFEjr1zCsiAB"
        assert grant.tokens[
            0].token_expiration_time > time_util.time_sans_frac()
        assert grant.tokens[0].expires_in_hours == 1  # type: ignore
Esempio n. 2
0
    def test_do_user_info_request_with_access_token_refresh(self):
        self.client.userinfo_endpoint = "http://oic.example.org/userinfo"

        token = self.client.get_token(state=self.client.state, scope="openid")
        token.token_expiration_time = time_sans_frac() - 86400

        resp = self.client.do_user_info_request(state=self.client.state)
        assert resp.type() == "OpenIDSchema"
        assert _eq(resp.keys(), ["name", "email", "verified", "nickname"])
        assert resp["name"] == "Melody Gardot"
Esempio n. 3
0
    def device_endpoint(self, request, authn=None):

        _req = AuthorizationRequest(**request)
        device_code = rndstr(10)
        user_code = rndstr(6)

        self.device2user[device_code] = user_code
        self.user_auth[user_code] = False
        self.client_id2device[_req['client_id']] = device_code
        self.device_code_expire_at[device_code] = time_sans_frac(
        ) + self.device_code_life_time
Esempio n. 4
0
    def token_endpoint(self, request, authn=None):
        _req = TokenRequest(**request)
        _dc = _req['device_code']

        if time_sans_frac() > self.device_code_expire_at[_dc]:
            return self.host.error_code(error='expired_token')

        _uc = self.device2user[_dc]

        if self.user_auth[_uc]:  # User is authenticated
            pass
        else:
            return self.host.error_code(error='authorization_pending')
Esempio n. 5
0
    def test_get_access_token_request_override(self):
        self.client.reset()
        self.client.redirect_uris = ["http://client.example.com/authz"]
        grant = Grant()
        grant.code = "AbCdEf"
        grant.grant_expiration_time = time_util.time_sans_frac() + 30
        self.client.grant = {"xyz": grant}

        atr = self.client.construct_AccessTokenRequest(state="xyz")

        assert atr["grant_type"] == "authorization_code"
        assert atr["code"] == "AbCdEf"
        assert atr["redirect_uri"] == "http://client.example.com/authz"
Esempio n. 6
0
    def __init__(self, uid, salt, valid=3600, authn_info=None, time_stamp=0):
        """
        Creates a representation of an authentication event.

        :param uid: The local user identifier
        :param salt: Salt to be used in creating a sub
        :param valid: How long the authentication is expected to be valid
        :param authn_info: Info about the authentication event
        :return:
        """
        self.uid = uid
        self.salt = salt
        self.authn_time = int(time_stamp) or time_sans_frac()
        self.valid_until = self.authn_time + int(valid)
        self.authn_info = authn_info
Esempio n. 7
0
    def __init__(self, uid, salt, valid=3600, authn_info=None, time_stamp=0):
        """
        Creates a representation of an authentication event.

        :param uid: The local user identifier
        :param salt: Salt to be used in creating a sub
        :param valid: How long the authentication is expected to be valid
        :param authn_info: Info about the authentication event
        :return:
        """
        self.uid = uid
        self.salt = salt
        self.authn_time = int(time_stamp) or time_sans_frac()
        self.valid_until = self.authn_time + int(valid)
        self.authn_info = authn_info
Esempio n. 8
0
    def test_parse_access_token_resp(self):
        atr = AccessTokenResponse(
            access_token="2YotnFZFEjr1zCsicMWpAA",
            token_type="example",
            expires_in=3600,
            refresh_token="tGzv3JOkF0XG5Qx2TlKWIA",
            example_parameter="example_value",
        )

        self.client.parse_response(AccessTokenResponse, info=json.dumps(atr.to_dict()))

        _grant = self.client.grant[""]
        assert len(_grant.tokens) == 1
        token = _grant.tokens[0]
        assert token.access_token == "2YotnFZFEjr1zCsicMWpAA"
        assert token.token_type == "example"
        assert token.token_expiration_time > time_util.time_sans_frac()
        assert token.refresh_token == "tGzv3JOkF0XG5Qx2TlKWIA"
Esempio n. 9
0
def create_idtoken_hint_other_issuer(oper, arg):
    """
    Context:
        EndSession
    Action:
        Sets the 'id_token_hint' argument in a end_session request.
        The value of the argument is a correct signed JWT but not the one
        that should have been used.
    Example:
        "create_idtoken_hint_other_issuer": null
    """
    iss = oper.conv.entity.client_id
    op = oper.conv.entity.provider_info['issuer']
    iat = time_sans_frac()
    exp = iat + 3600
    idt = IdToken(iss=iss, aud=[op], iat=iat, exp=exp, **arg)
    keys = oper.conv.entity.keyjar.get_signing_key('rsa')
    _jwt = idt.to_jwt(keys, 'RS256')
    oper.req_args["id_token_hint"] = _jwt
Esempio n. 10
0
    def issuer(self, query):
        request = self.parse_issuer_request(query)
        if request["principal"] == "*****@*****.**":
            resp = IssuerResponse(locations="http://example.com/")
        elif request["principal"] == "*****@*****.**":
            swd = SWDServiceRedirect(location="https://example.net/swd_server")
            resp = IssuerResponse(SWD_service_redirect=swd,
                                  expires=time_sans_frac() + 600)
        else:
            resp = None

        if resp is None:
            response = Response()
            response.status = 401
            return response, ""
        else:
            response = Response()
            response.headers = {"content-type":"application/json"}
            response.text = resp.to_json()
            return response
Esempio n. 11
0
                    _cinfo[key] = val

                response = RegistrationResponseCU(client_id=client_id)

            self.keystore.load_keys(request, client_id, replace=True)

        else:
            resp = BadRequest("Unknown request type: %s" % request.type)
            return resp(environ, start_response)

        # Add the key to the keystore
        if client_secret:
            _keystore.set_sign_key(client_secret, owner=client_id)
            _keystore.set_verify_key(client_secret, owner=client_id)

            _cinfo["registration_expires"] = time_util.time_sans_frac()+3600

            response["client_secret"] = client_secret
            response["expires_at"] = _cinfo["registration_expires"]

        if self.test_mode:
            logger.info("registration_response: %s" % response.to_dict())

        resp = Response(response.to_json(), content="application/json",
                        headers=[("Cache-Control", "no-store")])
        return resp(environ, start_response)

    #noinspection PyUnusedLocal
    def providerinfo_endpoint(self, environ, start_response, **kwargs):
        logger.info("@providerinfo_endpoint")
        try:
Esempio n. 12
0
CLIENT_SECRET = "abcdefghijklmnop"
CLIENT_ID = "client_1"

rsapub = rsa_load("../oc3/certs/mycert.key")

KEYS = [
    ["abcdefghijklmnop", "hmac", "ver", "client_1"],
    ["abcdefghijklmnop", "hmac", "sig", "client_1"],
    [rsapub, "rsa", "sig", "."],
    [rsapub, "rsa", "ver", "."],
]

SIGN_KEY = {"hmac": ["abcdefghijklmnop"]}
IDTOKEN = IdToken(
    iss="http://oic.example.org/", user_id="user_id", aud=CLIENT_ID, exp=time_sans_frac() + 86400, nonce="N0nce"
)

# ----------------- CLIENT --------------------


class TestOICClient:
    def setup_class(self):
        self.client = Client(CLIENT_ID)
        self.client.redirect_uris = ["http://example.com/redirect"]
        self.client.client_secret = CLIENT_SECRET
        self.client.keystore.set_sign_key(rsapub, "rsa")
        self.client.keystore.set_verify_key(rsapub, "rsa")

    def test_areq_1(self):
        ar = self.client.construct_AuthorizationRequest(request_args={"response_type": ["code"]})