Example #1
0
    def test_token_endpoint(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz"
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')
        with LogCapture(level=logging.DEBUG) as logcap:
            resp = self.provider.token_endpoint(request=areq.to_urlencoded())

        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token'])

        expected = (
        'body: code=<REDACTED>&client_secret=<REDACTED>&grant_type'
        '=authorization_code'
        '   &client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz')
        assert _eq(parse_qs(logcap.records[1].msg[6:]), parse_qs(expected[6:]))
        expected = {u'code': '<REDACTED>', u'client_secret': '<REDACTED>',
                    u'redirect_uri': u'http://example.com/authz',
                    u'client_id': 'client1',
                    u'grant_type': 'authorization_code'}
        # Don't try this at home, kids!
        # We have to eval() to a dict here because otherwise the arbitrary
        # ordering of the string causes the test to fail intermittently.
        assert _eq(eval(logcap.records[2].msg[4:]), expected)
        assert _eq(logcap.records[3].msg, 'Verified Client ID: client1')
        expected = {'redirect_uri': u'http://example.com/authz',
                    'client_secret': '<REDACTED>',
                    'code': u'<REDACTED>', 'client_id': 'client1',
                    'grant_type': 'authorization_code'}
        assert eval(logcap.records[4].msg[20:]) == expected
        expected = {'code': '<REDACTED>', 'authzreq': '', 'sub': 'sub',
                    'access_token': '<REDACTED>',
                    'token_type': 'Bearer',
                    'redirect_uri': 'http://example.com/authz',
                    'code_used': True, 'client_id': 'client1',
                    'oauth_state': 'token',
                    'refresh_token': '<REDACTED>', 'access_token_scope': '?'}
        assert _eq(eval(logcap.records[5].msg[7:]), expected)
        expected = {'access_token': u'<REDACTED>', 'token_type': 'Bearer',
                    'refresh_token': '<REDACTED>'}
        assert _eq(eval(logcap.records[6].msg[21:]), expected)
Example #2
0
def test_token_endpoint_unauth():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, AUTHN_BROKER, AUTHZ,
                        verify_client, symkey=rndstr(16))

    authreq = AuthorizationRequest(state="state",
                                   redirect_uri="http://example.com/authz",
                                   client_id="client1")

    _sdb = provider.sdb
    sid = _sdb.token.key(user="******", areq=authreq)
    access_grant = _sdb.token(sid=sid)
    _sdb[sid] = {
        "oauth_state": "authz",
        "user_id": "user_id",
        "authzreq": "",
        "client_id": "client1",
        "code": access_grant,
        "code_used": False,
        "redirect_uri": "http://example.com/authz"
    }

    # Construct Access token request
    areq = AccessTokenRequest(code=access_grant,
                              redirect_uri="http://example.com/authz",
                              client_id="client2", client_secret="hemlighet",)

    print areq.to_dict()
    resp = provider.token_endpoint(request=areq.to_urlencoded())
    print resp.message
    atr = TokenErrorResponse().deserialize(resp.message, "json")
    print atr.keys()
    assert _eq(atr.keys(), ['error_description', 'error'])
Example #3
0
    def test_token_introspection(self):
        authreq = AuthorizationRequest(state="state", redirect_uri="http://example.com/authz", client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        req = TokenIntrospectionRequest(
            token=atr["access_token"], client_id="client1", client_secret="hemlighet", token_type_hint="access_token"
        )
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["active"] is True
Example #4
0
    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz"
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id='<REDACTED>',
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['error_description', 'error'])
Example #5
0
    def test_token_endpoint_unauth(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz"
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client2",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['error_description', 'error'])
Example #6
0
    def test_token_endpoint_bad_state(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id='client1',
                                       response_type="code",
                                       scope=["openid"])

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "authn_event": '',
            "authzreq": '',
            "client_id": 'client1',
            "code": access_grant,
            'state': 'state',
            "code_used": False,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz",
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  client_id='client1',
                                  redirect_uri="http://example.com/authz",
                                  client_secret='hemlighet',
                                  grant_type='authorization_code',
                                  state='other_state')

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr['error'] == "unauthorized_client"
Example #7
0
    def test_token_endpoint(self):
        authreq = AuthorizationRequest(
            state="state", redirect_uri="http://example.com/authz", client_id="client1"
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ["access_token", "token_type"])
Example #8
0
    def test_token_endpoint_no_cache(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        assert resp.headers == [('Pragma', 'no-cache'), ('Cache-Control', 'no-store'),
                                ('Content-type', 'application/json')]
Example #9
0
    def test_token_endpoint_no_cache(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz"
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')
        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        assert resp.headers == [('Pragma', 'no-cache'), ('Cache-Control', 'no-store'),
                                ('Content-type', 'application/json')]
Example #10
0
    def test_token_endpoint(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz"
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')
        with LogCapture(level=logging.DEBUG) as logcap:
            resp = self.provider.token_endpoint(request=areq.to_urlencoded())

        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ['access_token', 'token_type', 'refresh_token'])

        expected = (
            'token_request: code=<REDACTED>&client_secret=<REDACTED>&grant_type=authorization_code'
            '&client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz')
        assert _eq(parse_qs(logcap.records[1].msg[15:]), parse_qs(expected[15:]))
        expected = {u'code': '<REDACTED>', u'client_secret': '<REDACTED>',
                    u'redirect_uri': u'http://example.com/authz',
                    u'client_id': 'client1',
                    u'grant_type': 'authorization_code'}
        # Don't try this at home, kids!
        # We have to eval() to a dict here because otherwise the arbitrary
        # ordering of the string causes the test to fail intermittently.
        assert _eq(eval(logcap.records[2].msg[4:]), expected)
        assert _eq(logcap.records[3].msg, 'Verified Client ID: client1')
        expected = {'redirect_uri': u'http://example.com/authz',
                    'client_secret': '<REDACTED>',
                    'code': u'<REDACTED>', 'client_id': 'client1',
                    'grant_type': 'authorization_code'}
        assert eval(logcap.records[4].msg[20:]) == expected
        expected = {'code': '<REDACTED>', 'authzreq': '', 'sub': 'sub',
                    'access_token': '<REDACTED>',
                    'token_type': 'Bearer',
                    'redirect_uri': 'http://example.com/authz',
                    'code_used': True, 'client_id': 'client1',
                    'oauth_state': 'token',
                    'refresh_token': '<REDACTED>', 'access_token_scope': '?'}
        assert _eq(eval(logcap.records[5].msg[7:]), expected)
        expected = {'access_token': u'<REDACTED>', 'token_type': 'Bearer',
                    'refresh_token': '<REDACTED>'}
        assert _eq(eval(logcap.records[6].msg[21:]), expected)
Example #11
0
    def test_extra(self):
        atr = AccessTokenRequest(grant_type="authorization_code",
                                 code="SplxlOBeZQQYbYS6WxSbIA",
                                 redirect_uri="https://client.example.com/cb",
                                 extra="foo")

        query = atr.to_urlencoded()
        assert query_string_compare(query,
                                    "code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb&grant_type=authorization_code&extra=foo")

        atr2 = AccessTokenRequest().deserialize(query, "urlencoded")
        assert atr == atr2
Example #12
0
    def test_extra(self):
        atr = AccessTokenRequest(grant_type="authorization_code",
                                 code="SplxlOBeZQQYbYS6WxSbIA",
                                 redirect_uri="https://client.example.com/cb",
                                 extra="foo")

        query = atr.to_urlencoded()
        assert query_string_compare(query,
                                    "code=SplxlOBeZQQYbYS6WxSbIA&redirect_uri=https%3A%2F%2Fclient.example.com%2Fcb&grant_type=authorization_code&extra=foo")

        atr2 = AccessTokenRequest().deserialize(query, "urlencoded")
        assert atr == atr2
Example #13
0
    def test_token_introspection_missing(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client2")

        _sdb = self.provider.sdb
        self.provider.cdb["client2"] = {
            "client_secret": "hemlighet",
            "redirect_uris": [("http://localhost:8087/authz", None)],
            "token_endpoint_auth_method": "client_secret_post",
            "response_types": ["code", "token"],
        }
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client2",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"],
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client2",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        # Delete the client
        del self.provider.cdb["client2"]
        req = TokenIntrospectionRequest(
            token=atr["access_token"],
            client_id="client2",
            client_secret="hemlighet",
            token_type_hint="access_token",
        )
        resp = self.provider.introspection_endpoint(
            request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(
            resp.message, "json")
        assert ti_resp["error"] == "unauthorized_client"
Example #14
0
    def test_construct(self, client):
        cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com")
        csp = ClientSecretPost(client)
        http_args = csp.construct(cis)

        assert cis["client_id"] == "A"
        assert cis["client_secret"] == "boarding pass"
        assert http_args is None

        cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com")
        http_args = csp.construct(cis, {},
                                  http_args={"client_secret": "another"})
        assert cis["client_id"] == "A"
        assert cis["client_secret"] == "another"
        assert http_args == {}
Example #15
0
    def test_does_not_remove_padding(self):
        cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com")

        csb = ClientSecretBasic(None)
        http_args = csb.construct(cis, user="******", password="******")

        assert http_args["headers"]["Authorization"].endswith("==")
Example #16
0
    def token_endpoint(self, request="", authn=None, **kwargs):

        try:
            req = AccessTokenRequest().deserialize(request, 'urlencoded')
            client_id = self.client_authn(self, req, authn)
        except Exception as err:
            self.events.store(EV_FAULT, err)
            return self._error(error="incorrect_behavior",
                               descr="Failed to verify client")

        if self.events:
            self.events.store(EV_PROTOCOL_REQUEST, req)

        try:
            self._update_client_keys(client_id)
        except TestError:
            return self._error(error="incorrect_behavior",
                               descr="No change in client keys")

        _response = provider.Provider.token_endpoint(self,
                                                     authn=authn,
                                                     request=request,
                                                     **kwargs)

        return _response
Example #17
0
    def test_client_secret_jwt(self, client):
        client.token_endpoint = "https://example.com/token"
        client.provider_info = {
            'issuer': 'https://example.com/',
            'token_endpoint': "https://example.com/token"
        }

        csj = ClientSecretJWT(client)
        cis = AccessTokenRequest()

        csj.construct(cis, algorithm="HS256", authn_endpoint='userinfo')
        assert cis["client_assertion_type"] == JWT_BEARER
        assert "client_assertion" in cis
        cas = cis["client_assertion"]
        _jwt = JWT().unpack(cas)
        jso = _jwt.payload()
        assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
        assert _jwt.headers == {'alg': 'HS256'}

        _rj = JWS()
        info = _rj.verify_compact(
            cas, [SYMKey(k=b64e(as_bytes(client.client_secret)))])

        assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
        assert info['aud'] == [client.provider_info['issuer']]
Example #18
0
 def test_construct(self, client):
     _key = rsa_load(os.path.join(BASE_PATH, "data/keys/rsa.key"))
     kc_rsa = KeyBundle([{
         "key": _key,
         "kty": "RSA",
         "use": "ver"
     }, {
         "key": _key,
         "kty": "RSA",
         "use": "sig"
     }])
     client.keyjar[""] = kc_rsa
     client.token_endpoint = "https://example.com/token"
     client.provider_info = {
         'issuer': 'https://example.com/',
         'token_endpoint': "https://example.com/token"
     }
     cis = AccessTokenRequest()
     pkj = PrivateKeyJWT(client)
     http_args = pkj.construct(cis,
                               algorithm="RS256",
                               authn_endpoint='token')
     assert http_args == {}
     cas = cis["client_assertion"]
     _jwt = JWT().unpack(cas)
     jso = _jwt.payload()
     assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
     assert _jwt.headers == {'alg': 'RS256'}
     assert jso['aud'] == [client.provider_info['token_endpoint']]
Example #19
0
    def token_endpoint(self, authn="", **kwargs):
        """
        This is where clients come to get their access tokens
        """

        _sdb = self.sdb

        logger.debug("- token -")
        body = kwargs["request"]
        logger.debug("body: %s" % sanitize(body))

        areq = AccessTokenRequest().deserialize(body, "urlencoded")

        try:
            self.client_authn(self, areq, authn)
        except FailedAuthentication as err:
            logger.error(err)
            err = TokenErrorResponse(error="unauthorized_client",
                                     error_description="%s" % err)
            return Response(err.to_json(), content="application/json",
                            status="401 Unauthorized")

        logger.debug("AccessTokenRequest: %s" % sanitize(areq))

        try:
            assert areq["grant_type"] == "authorization_code"
        except AssertionError:
            err = TokenErrorResponse(error="invalid_request",
                                     error_description="Wrong grant type")
            return Response(err.to_json(), content="application/json",
                            status="401 Unauthorized")

        # assert that the code is valid
        _info = _sdb[areq["code"]]

        resp = self.token_scope_check(areq, _info)
        if resp:
            return resp

        # If redirect_uri was in the initial authorization request
        # verify that the one given here is the correct one.
        if "redirect_uri" in _info:
            assert areq["redirect_uri"] == _info["redirect_uri"]

        try:
            _tinfo = _sdb.upgrade_to_token(areq["code"], issue_refresh=True)
        except AccessCodeUsed:
            err = TokenErrorResponse(error="invalid_grant",
                                     error_description="Access grant used")
            return Response(err.to_json(), content="application/json",
                            status="401 Unauthorized")

        logger.debug("_tinfo: %s" % sanitize(_tinfo))

        atr = AccessTokenResponse(**by_schema(AccessTokenResponse, **_tinfo))

        logger.debug("AccessTokenResponse: %s" % sanitize(atr))

        return Response(atr.to_json(), content="application/json")
Example #20
0
    def test_construct(self, client):
        cis = AccessTokenRequest(code="foo", redirect_uri="http://example.com")

        csb = ClientSecretBasic(client)
        http_args = csb.construct(cis)
        cred = '{}:{}'.format(quote_plus("A"), quote_plus("boarding pass"))
        assert http_args == {"headers": {"Authorization": "Basic {}".format(
            base64.b64encode(cred.encode("utf-8")).decode("utf-8"))}}
Example #21
0
    def test_token_revocation_and_introspection(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory['code'](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            'response_type': ['code']
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client1",
                                  client_secret="hemlighet",
                                  grant_type='authorization_code')

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")

        req = TokenRevocationRequest(token=atr['access_token'],
                                     client_id="client1",
                                     client_secret="hemlighet",
                                     token_type_hint='access_token')
        resp = self.provider.revocation_endpoint(request=req.to_urlencoded())
        assert resp.status_code == 200

        req = TokenIntrospectionRequest(token=atr['access_token'],
                                        client_id="client1",
                                        client_secret="hemlighet",
                                        token_type_hint='access_token')
        resp = self.provider.introspection_endpoint(
            request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(
            resp.message, 'json')
        assert ti_resp['active'] is False
Example #22
0
    def test_token_introspection_missing(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client2")

        _sdb = self.provider.sdb
        self.provider.cdb["client2"] = {
            "client_secret": "hemlighet",
            "redirect_uris": [("http://localhost:8087/authz", None)],
            "token_endpoint_auth_method": "client_secret_post",
            "response_types": ["code", "token"]
        }
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.token_factory["code"](sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": authreq.to_json(),
            "client_id": "client2",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
            "response_type": ["code"]
        }

        # Construct Access token request
        areq = AccessTokenRequest(code=access_grant,
                                  redirect_uri="http://example.com/authz",
                                  client_id="client2",
                                  client_secret="hemlighet",
                                  grant_type="authorization_code")

        resp = self.provider.token_endpoint(request=areq.to_urlencoded())
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        # Delete the client
        del self.provider.cdb["client2"]
        req = TokenIntrospectionRequest(token=atr["access_token"],
                                        client_id="client2",
                                        client_secret="hemlighet",
                                        token_type_hint="access_token")
        resp = self.provider.introspection_endpoint(request=req.to_urlencoded())
        assert resp
        ti_resp = TokenIntrospectionResponse().deserialize(resp.message, "json")
        assert ti_resp["error"] == "unauthorized_client"
Example #23
0
def test_token_endpoint():
    provider = Provider("pyoicserv",
                        sdb.SessionDB(),
                        CDB,
                        AUTHN_BROKER,
                        AUTHZ,
                        verify_client,
                        symkey=rndstr(16))

    authreq = AuthorizationRequest(state="state",
                                   redirect_uri="http://example.com/authz",
                                   client_id="client1")

    _sdb = provider.sdb
    sid = _sdb.token.key(user="******", areq=authreq)
    access_grant = _sdb.token(sid=sid)
    _sdb[sid] = {
        "oauth_state": "authz",
        "sub": "sub",
        "authzreq": "",
        "client_id": "client1",
        "code": access_grant,
        "code_used": False,
        "redirect_uri": "http://example.com/authz"
    }

    # Construct Access token request
    areq = AccessTokenRequest(
        code=access_grant,
        redirect_uri="http://example.com/authz",
        client_id="client1",
        client_secret="hemlighet",
    )

    print areq.to_dict()
    resp = provider.token_endpoint(request=areq.to_urlencoded())
    print resp.message
    atr = AccessTokenResponse().deserialize(resp.message, "json")

    print atr.keys()
    assert _eq(atr.keys(),
               ['access_token', 'expires_in', 'token_type', 'refresh_token'])
Example #24
0
    def test_server_parse_token_request(self):
        atr = AccessTokenRequest(
            grant_type="authorization_code", code="SplxlOBeZQQYbYS6WxSbIA",
            redirect_uri="https://client.example.com/cb", extra="foo")
        uenc = atr.to_urlencoded()

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(), ['code', 'redirect_uri', 'grant_type', 'extra'])

        assert tr["grant_type"] == "authorization_code"
        assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(), ['code', 'grant_type', 'redirect_uri', 'extra'])

        assert tr["extra"] == "foo"
Example #25
0
    def test_token_endpoint_ok_state(self):
        authreq = AuthorizationRequest(
            state="state",
            redirect_uri="http://example.com/authz",
            client_id="client1",
            response_type="code",
            scope=["openid"],
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        ae = AuthnEvent("user", "salt")
        _sdb[sid] = {
            "oauth_state": "authz",
            "authn_event": ae.to_json(),
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "state": "state",
            "code_used": False,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz",
        }
        _sdb.do_sub(sid, "client_salt")

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            client_id="client1",
            redirect_uri="http://example.com/authz",
            client_secret="hemlighet",
            grant_type="authorization_code",
            state="state",
        )

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert atr["token_type"] == "Bearer"
Example #26
0
    def test_server_parse_token_request(self):
        atr = AccessTokenRequest(grant_type="authorization_code",
                                 code="SplxlOBeZQQYbYS6WxSbIA",
                                 redirect_uri="https://client.example.com/cb",
                                 extra="foo")
        uenc = atr.to_urlencoded()

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(), ['code', 'redirect_uri', 'grant_type', 'extra'])

        assert tr["grant_type"] == "authorization_code"
        assert tr["code"] == "SplxlOBeZQQYbYS6WxSbIA"

        tr = self.srv.parse_token_request(body=uenc)

        assert isinstance(tr, AccessTokenRequest)
        assert _eq(tr.keys(), ['code', 'grant_type', 'redirect_uri', 'extra'])

        assert tr["extra"] == "foo"
Example #27
0
def test_token_endpoint():
    provider = Provider("pyoicserv", sdb.SessionDB(), CDB, FUNCTIONS)

    authreq = AuthorizationRequest(state="state",
                                   redirect_uri="http://example.com/authz",
                                   client_id="client1")

    _sdb = provider.sdb
    sid = _sdb.token.key(user="******", areq=authreq)
    access_grant = _sdb.token(sid=sid)
    _sdb[sid] = {
        "oauth_state": "authz",
        "user_id": "user_id",
        "authzreq": "",
        "client_id": "client1",
        "code": access_grant,
        "code_used": False,
        "redirect_uri":"http://example.com/authz"
    }

    # Construct Access token request
    areq = AccessTokenRequest(code=access_grant,
                              redirect_uri="http://example.com/authz")


    str = areq.to_urlencoded()
    fil = StringIO.StringIO(buf=str)
    environ = BASE_ENVIRON.copy()
    environ["CONTENT_LENGTH"] = len(str)
    environ["wsgi.input"] = fil
    environ["REMOTE_USER"] = "******"

    resp = provider.token_endpoint(environ, start_response)
    print resp
    atr = AccessTokenResponse().deserialize(resp[0], "json")

    print atr.keys()
    assert _eq(atr.keys(), ['access_token', 'expires_in', 'token_type',
                            'refresh_token'])
Example #28
0
    def test_code_grant_type_used(self):
        authreq = AuthorizationRequest(
            state="state",
            redirect_uri="http://example.com/authz",
            client_id="client1",
            response_type="code",
            scope=["openid"],
        )

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": True,
            "scope": ["openid"],
            "redirect_uri": "http://example.com/authz",
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            client_id="client1",
            redirect_uri="http://example.com/authz",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )

        txt = areq.to_urlencoded()

        resp = self.provider.token_endpoint(request=txt)
        atr = TokenErrorResponse().deserialize(resp.message, "json")
        assert atr["error"] == "invalid_grant"
Example #29
0
    def test_client_secret_jwt(self, client):
        client.token_endpoint = "https://example.com/token"

        csj = ClientSecretJWT(client)
        cis = AccessTokenRequest()

        http_args = csj.construct(cis, algorithm="HS256")
        assert cis["client_assertion_type"] == JWT_BEARER
        assert "client_assertion" in cis
        cas = cis["client_assertion"]
        _jwt = JWT().unpack(cas)
        jso = _jwt.payload()
        assert _eq(jso.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
        assert _jwt.headers == {'alg': 'HS256'}

        _rj = JWS()
        info = _rj.verify_compact(cas, [SYMKey(key=client.client_secret)])

        assert _eq(info.keys(), ["aud", "iss", "sub", "jti", "exp", "iat"])
Example #30
0
    def token_endpoint(self, authn="", **kwargs):
        """
        This is where clients come to get their access tokens
        """

        _sdb = self.sdb

        LOG_DEBUG("- token -")
        body = kwargs["request"]
        LOG_DEBUG("body: %s" % body)

        areq = AccessTokenRequest().deserialize(body, "urlencoded")

        try:
            client = self.client_authn(self, areq, authn)
        except FailedAuthentication, err:
            err = TokenErrorResponse(error="unathorized_client",
                                     error_description="%s" % err)
            return Response(err.to_json(), content="application/json",
                            status="401 Unauthorized")
Example #31
0
import pytest

from oic.oauth2.message import AccessTokenRequest
from oic.utils.sanitize import sanitize


@pytest.mark.parametrize("raw,expected", [
    ('code=%5B999%5D&bing=baz&password=foo&param1=bar',
     'code=<REDACTED>&bing=baz&password=<REDACTED>&param1=bar'),
    (AccessTokenRequest(
        grant_type='authorization_code',
        redirect_uri=u'http://example.com/authz',
        client_id='client1',
        client_secret='hemlighet',
        code=u'0x+QZlw/S2O9NJKVqB/LDzzhod4v/FVh6ULK/0OnFsfOFRQcux5ow=='), {
            'grant_type': 'authorization_code',
            'redirect_uri': u'http://example.com/authz',
            'client_id': 'client1',
            'client_secret': '<REDACTED>',
            'code': u'<REDACTED>'
        }),
    (("{'grant_type': 'authorization_code', 'redirect_uri': u'http://example.com/authz', "
      "'client_id': 'client1', 'client_secret': 'hemlighet', "
      "'code': u'0x+QZlw/S2O9NJKVqB/LDzzhod4v/FVh6ULK/0OnFsfOFRQcux5ow=='}"),
     ("{'grant_type': 'authorization_code', 'redirect_uri': u'http://example.com/authz', "
      "'client_id': 'client1', 'client_secret': '<REDACTED>', 'code': u'<REDACTED>'}"
      )),
    ({
        'Password': '******',
        'param1': 'bar',
        'CODE': [999],
Example #32
0
from oic.oauth2.message import AccessTokenRequest
from oic.utils.sanitize import sanitize


@pytest.mark.parametrize(
    "raw,expected",
    [
        (
            "code=%5B999%5D&bing=baz&password=foo&param1=bar",
            "code=<REDACTED>&bing=baz&password=<REDACTED>&param1=bar",
        ),
        (
            AccessTokenRequest(
                grant_type="authorization_code",
                redirect_uri="http://example.com/authz",
                client_id="client1",
                client_secret="hemlighet",
                code="0x+QZlw/S2O9NJKVqB/LDzzhod4v/FVh6ULK/0OnFsfOFRQcux5ow==",
            ),
            {
                "grant_type": "authorization_code",
                "redirect_uri": "http://example.com/authz",
                "client_id": "client1",
                "client_secret": "<REDACTED>",
                "code": "<REDACTED>",
            },
        ),
        (
            (
                "{'grant_type': 'authorization_code', 'redirect_uri': u'http://example.com/authz', "
                "'client_id': 'client1', 'client_secret': 'hemlighet', "
Example #33
0
    def test_token_endpoint(self):
        authreq = AuthorizationRequest(state="state",
                                       redirect_uri="http://example.com/authz",
                                       client_id="client1")

        _sdb = self.provider.sdb
        sid = _sdb.access_token.key(user="******", areq=authreq)
        access_grant = _sdb.access_token(sid=sid)
        _sdb[sid] = {
            "oauth_state": "authz",
            "sub": "sub",
            "authzreq": "",
            "client_id": "client1",
            "code": access_grant,
            "code_used": False,
            "redirect_uri": "http://example.com/authz",
        }

        # Construct Access token request
        areq = AccessTokenRequest(
            code=access_grant,
            redirect_uri="http://example.com/authz",
            client_id="client1",
            client_secret="hemlighet",
            grant_type="authorization_code",
        )
        with LogCapture(level=logging.DEBUG) as logcap:
            resp = self.provider.token_endpoint(request=areq.to_urlencoded())

        atr = AccessTokenResponse().deserialize(resp.message, "json")
        assert _eq(atr.keys(), ["access_token", "token_type", "refresh_token"])

        expected = (
            "token_request: code=<REDACTED>&client_secret=<REDACTED>&grant_type=authorization_code"
            "&client_id=client1&redirect_uri=http%3A%2F%2Fexample.com%2Fauthz")
        assert _eq(parse_qs(logcap.records[1].msg[15:]),
                   parse_qs(expected[15:]))
        expected2 = {
            "code": "<REDACTED>",
            "client_secret": "<REDACTED>",
            "redirect_uri": "http://example.com/authz",
            "client_id": "client1",
            "grant_type": "authorization_code",
        }
        # Don't try this at home, kids!
        # We have to eval() to a dict here because otherwise the arbitrary
        # ordering of the string causes the test to fail intermittently.
        assert _eq(eval(logcap.records[2].msg[4:]), expected2)
        assert _eq(logcap.records[3].msg, "Verified Client ID: client1")
        expected3 = {
            "redirect_uri": "http://example.com/authz",
            "client_secret": "<REDACTED>",
            "code": "<REDACTED>",
            "client_id": "client1",
            "grant_type": "authorization_code",
        }
        assert eval(logcap.records[4].msg[20:]) == expected3
        expected4 = {
            "code": "<REDACTED>",
            "authzreq": "",
            "sub": "sub",
            "access_token": "<REDACTED>",
            "token_type": "Bearer",
            "redirect_uri": "http://example.com/authz",
            "code_used": True,
            "client_id": "client1",
            "oauth_state": "token",
            "refresh_token": "<REDACTED>",
            "access_token_scope": "?",
        }
        assert _eq(eval(logcap.records[5].msg[7:]), expected4)
        expected5 = {
            "access_token": "<REDACTED>",
            "token_type": "Bearer",
            "refresh_token": "<REDACTED>",
        }
        assert _eq(eval(logcap.records[6].msg[21:]), expected5)