Example #1
0
def web_flow(ctx):
    client = Client(client_authn_method=CLIENT_AUTHN_METHOD)
    issuer = f"{settings.AUTH_DEFAULT_HOST}/auth/realms/unikube"
    client.provider_config(issuer)

    state = rndstr()
    nonce = rndstr()

    # 1. run callback server
    from unikube.authentication.web import run_callback_server

    port = run_callback_server(state, nonce, client, ctx)

    # 2. send to login with redirect url.
    args = {
        "client_id": "cli",
        "response_type": ["token"],
        "response_mode": "form_post",
        "scope": ["openid"],
        "nonce": nonce,
        "state": state,
        "redirect_uri": f"http://localhost:{port}",
    }

    auth_req = client.construct_AuthorizationRequest(request_args=args)
    login_url = auth_req.request(client.authorization_endpoint)
    console.info("If your Browser does not open automatically, go to the following URL and login:")
    console.link(login_url)
    click.launch(login_url)
    return True
Example #2
0
def get_proxy_token(refresh_token_data, *,
                    user_agent=constants.USER_AGENT,
                    scope=constants.FXA_PROXY_SCOPE,
                    resource=constants.DEFAULT_PROXY_URL,
                    ttl=constants.FXA_EXP_TOKEN_TIME,
                    timeout=10.):
    client = Client(client_authn_method=None)
    provider_info = client.provider_config(constants.FXA_PROVIDER_URL)
    token_endpoint = client.token_endpoint
    #return resp.to_dict()

    http_req = urllib.request.Request(
        token_endpoint,
        data=json.dumps({
            "client_id": constants.CLIENT_ID,
            "grant_type": "refresh_token",
            "refresh_token": refresh_token_data["refresh_token"],
            "scope": scope,
            "ttl": ttl,
            "ppid_seed": random.randrange(1024),
            "resource": resource,
        }).encode('ascii'),
        headers={
            "User-Agent": user_agent,
            "Content-Type": "application/json",
        }
    )
    with urllib.request.urlopen(http_req, None, timeout) as resp:
        coding = resp.headers.get_content_charset()
        coding = coding if coding is not None else 'utf-8-sig'
        decoder = codecs.getreader(coding)(resp)
        res = json.load(decoder)
    res["received_at"] = int(time.time())
    return res
Example #3
0
    def test_sign_enc_request(self):
        cli = Client()
        cli.redirect_uris = ["http://www.example.org/authz"]
        cli.client_id = "client_1"

        for kb in self.server.keyjar.issuer_keys[""]:
            _jwks = kb.jwks()
            _keys = [k for k in json.loads(_jwks)["keys"]
                     if k["use"] in ["ver"]]
            _kb = KeyBundle(_keys)
            cli.keyjar.add_kb(self.server.name, _kb)
    
        _kb = keybundle_from_local_file("%s/rsa.pub" % BASE_PATH, "RSA", ["enc"])
        cli.keyjar.add_kb(self.server.name, _kb)
    
        request_args = {"redirect_uri": cli.redirect_uris[0],
                        "client_id": cli.client_id,
                        "scope": "openid",
                        "response_type": "code"}
    
        kwargs = {"request_object_signing_alg": "none",
                  "request_object_encryption_alg": "RSA1_5",
                  "request_object_encryption_enc": "A128CBC-HS256",
                  "request_method": "parameter",
                  "target": self.server.name}
    
        areq = cli.construct_AuthorizationRequest(request_args=request_args,
                                                  **kwargs)
    
        assert areq
        assert areq["request"]
Example #4
0
def access_token_request(request):
    client = Client(client_id=CLIENT__OAUTH2KEY, client_authn_method={"client_secret_post": ClientSecretPost})
    raw_response = json.dumps(dict(request.GET))
    aresp = client.parse_response(AuthorizationResponse, info=raw_response)  # , sformat="urlencoded")
    arespdata_state = aresp["state"]
    sessiondata_state = request.session["state"]
    logger.debug(" auth (2) %s" % (arespdata_state))

    if arespdata_state == sessiondata_state:
        code = aresp["code"]
        params = {
            "token_endpoint": WSO2IS__TOKENENDPOINT,
            "code": code,
            "client_id": CLIENT__OAUTH2KEY,
            "client_secret": CLIENT__OAUTH2SECRET,
            "redirect_uri": CLIENT__REDIRECTURL,
        }
        result = client.do_access_token_request(
            scope=["openid"], state=arespdata_state, request_args=params, authn_method="client_secret_post"
        )

        user_data = result["id_token"]["sub"]
        document_id = user_data[: user_data.find("@")]

        logger.debug(" auth (3) %s [doc=%s]" % (arespdata_state, document_id))

        return HttpResponse("User authenticated {}".format(document_id))
    else:
        return HttpResponse("Error: invalid parameters sent to authorization endpoint.")
Example #5
0
def test_construct_UserInfoRequest():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"

    uir = cli.construct_UserInfoRequest(request_args={"access_token": "access_token"})
    print uir
    assert ("%s" % uir) == "access_token=access_token"
Example #6
0
def pedir_token(request):
	cliente = Client(
		client_id=llave,
		client_authn_method={"client_secret_post": ClientSecretPost}
	)
	respuesta_cruda = json.dumps(dict(request.GET))
	respuesta = cliente.parse_response(AuthorizationResponse, info=respuesta_cruda)
	estado_recibido = respuesta['state']
	estado_almacenado = request.session['estado']
	if estado_recibido == estado_almacenado:
		codigo = respuesta['code']
		parametros = {
			"token_endpoint": endpoint_token,
			"code": codigo,
			"client_id": llave,
			"client_secret": secreto,
			"redirect_uri": callback
		}
		resultado = cliente.do_access_token_request(
			scope = ["openid"],
			state = estado_recibido,
			request_args = parametros,
			authn_method = "client_secret_post"
		)
		usuario = resultado['id_token']['sub']
		cedula = usuario[:usuario.find('@')]
		return HttpResponse("Bienvenido, usuario {}".format(cedula))
	else:
		return HttpResponse("Error: el estado enviado al endpoint de autorizacion no corresponde con el recibido.")
Example #7
0
def test_construct_CheckSessionRequest():
    cli = Client()
    cli.check_session_endpoint = "https://example.org/oauth2/check_session"

    csr = cli.construct_CheckSessionRequest(request_args={"id_token": "id_token"})
    print csr
    assert ("%s" % csr) == "id_token=id_token"
Example #8
0
    def _configure_client(self):
        config_file_path = JwtAuthenticationMethod.openid_client_config_path()

        if not os.path.exists(config_file_path):
            logger.info(
                'OpenID Connect configuration ({}) not found, JWT'
                ' authentication is disabled'.format(config_file_path)
            )

            return

        with open(config_file_path) as fp:
            config = json.loads(fp.read())

            self._client = Client(
                client_authn_method=CLIENT_AUTHN_METHOD,
                verify_ssl='/etc/pki/tls/certs/ca-bundle.crt'
            )

            self._client.provider_config(config['issuer'])

            client_registration = RegistrationResponse(
                client_id=config['client_id'],
                client_secret=config['client_secret']
            )

            self._client.store_registration_info(client_registration)
Example #9
0
    def __init__(self, provider_configuration, redirect_uri):
        """
        Args:
            provider_configuration (flask_pyoidc.provider_configuration.ProviderConfiguration)
        """
        self._provider_configuration = provider_configuration
        self._client = Client(client_authn_method=CLIENT_AUTHN_METHOD,
                              settings=provider_configuration.client_settings)
        # Token Introspection is implemented under extension sub-package of
        # the client in pyoidc.
        self._client_extension = ClientExtension(
            client_authn_method=CLIENT_AUTHN_METHOD,
            settings=provider_configuration.client_settings)
        # Client Credentials Flow is implemented under oauth2 sub-package of
        # the client in pyoidc.
        self._oauth2_client = Oauth2Client(
            client_authn_method=CLIENT_AUTHN_METHOD,
            message_factory=CCMessageFactory,
            settings=self._provider_configuration.client_settings)

        provider_metadata = provider_configuration.ensure_provider_metadata(
            self._client)
        self._client.handle_provider_config(
            ProviderConfigurationResponse(**provider_metadata.to_dict()),
            provider_metadata['issuer'])

        if self._provider_configuration.registered_client_metadata:
            client_metadata = self._provider_configuration.registered_client_metadata.to_dict(
            )
            client_metadata.update(redirect_uris=list(redirect_uri))
            self._store_registration_info(client_metadata)

        self._redirect_uri = redirect_uri
    def init_app(self, app):
        try:
            self.client_id = app.config["NHS_OIDC_CLIENT_ID"]
            self.authorization_callback_url = app.config[
                "NHS_OIDC_LOGIN_CALLBACK_URL"]
            self.registration_callback_url = app.config[
                "NHS_OIDC_REGISTRATION_CALLBACK_URL"]
            self.scopes = [
                "openid", "profile", "email", "phone", "profile_extended"
            ]
            self.vtr = '["P5.Cp.Cd", "P5.Cp.Ck", "P5.Cm"]'
            self.authority_url = app.config["NHS_OIDC_AUTHORITY_URL"]
        except ValueError as e:
            raise ValueError(f"Missing NHS OIDC configuration: {e!r}")

        self.client = Client(client_id=self.client_id,
                             client_authn_method=CLIENT_AUTHN_METHOD)
        self.client.provider_config(self.authority_url)

        self.private_key = app.config["NHS_OIDC_LOGIN_PRIVATE_KEY"]
        if not self.private_key:
            private_key_path = app.config["NHS_OIDC_LOGIN_PRIVATE_KEY_PATH"]
            if not os.stat(private_key_path):
                raise ValueError(
                    f"Missing private key file. Expected private key file at {self.private_key_path!r}"
                )

            with open(private_key_path) as key_file:
                self.private_key = key_file.read()
Example #11
0
def pedir_token(request):
    cliente = Client(
        client_id=llave,
        client_authn_method={"client_secret_post": ClientSecretPost})
    respuesta_cruda = json.dumps(dict(request.GET))
    respuesta = cliente.parse_response(AuthorizationResponse,
                                       info=respuesta_cruda)
    estado_recibido = respuesta['state']
    estado_almacenado = request.session['estado']
    if estado_recibido == estado_almacenado:
        codigo = respuesta['code']
        parametros = {
            "token_endpoint": endpoint_token,
            "code": codigo,
            "client_id": llave,
            "client_secret": secreto,
            "redirect_uri": callback
        }
        resultado = cliente.do_access_token_request(
            scope=["openid"],
            state=estado_recibido,
            request_args=parametros,
            authn_method="client_secret_post")
        usuario = resultado['id_token']['sub']
        cedula = usuario[:usuario.find('@')]
        return HttpResponse("Bienvenido, usuario {}".format(cedula))
    else:
        return HttpResponse(
            "Error: el estado enviado al endpoint de autorizacion no corresponde con el recibido."
        )
Example #12
0
def test_userinfo_request():
    cli = Client()
    cli.userinfo_endpoint = "http://example.com/userinfo"

    info = ARESP.to_urlencoded()
    cli.parse_response(AuthorizationResponse, info,
                       sformat="urlencoded", state="state0")

    cli.parse_response(AccessTokenResponse, TRESP.to_json(), state="state0")

    path, body, method, h_args = cli.user_info_request(state="state0")

    assert path == "http://example.com/userinfo?access_token=access_token"
    assert method == "GET"
    assert body is None
    assert h_args == {}

    path, body, method, h_args = cli.user_info_request(method="POST",
                                                       state="state0")

    assert path == "http://example.com/userinfo"
    assert method == "POST"
    assert body == "access_token=access_token"
    assert h_args == {'headers': {
        'Content-type': 'application/x-www-form-urlencoded'}}

    path, body, method, h_args = cli.user_info_request(method="POST",
                                                       state="state0")

    assert path == "http://example.com/userinfo"
    assert method == "POST"
    assert body == "access_token=access_token"
    assert h_args == {'headers': {
        'Content-type': 'application/x-www-form-urlencoded'}}
Example #13
0
def make_authentication_request():
    print ('create authentication request')
    # consider storing a hash in state
    # what to hash in state might include cookie data, time, salt, etc...

    # force login in order to work around the Azure AD issue where a user may be logged in to the wrong domain.
    # Set prompt=login in the implicit flow request to force a new login
    state = rndstr()
    nounce = rndstr()
    request_args = {
        "response_type": "id_token code",
        "response_mode": "form_post",
        "state": state,
        "nonce": nounce,
        "prompt": "login",
        "redirect_uri": Settings.auth_redirect_url,
        "scope":"openid profile"
    }

    print (Settings.auth_client_id)

    client = Client(Settings.auth_client_id)

    auth_req = client.construct_AuthorizationRequest(request_args = request_args)

    provider_url = Settings.auth_provider_url
    if Settings.auth_tenant is not None:
        provider_url = provider_url.replace("{{tenant}}", Settings.auth_tenant)

    login_url = auth_req.request(provider_url)

    print(login_url)

    return redirect(login_url)
Example #14
0
def get_client():
    """Method that prepare the oidc client.

    This method use lru_cache in order call the OIDC provider once
    per thread

    Today we only support OIDC providers (ISSUER) that expose a
    /.well-known/openid-configuration route

    At the moment to authenticate the RP to the OIDC provider we only
    support through client_id/secret_ID/rp_callback attributes.

    You must configure OIDC in AnyBlok configuration:

    * **oidc-provider-issuer**: The OIDC Provider urls
        (ie: https://gitlab.com)
    * **oidc-relying-party-callback**: The Relaying Party callback, once
        the user is authenticate against the OIDC provider he will be redirect
        to that uri to the RP service (ie: http://localhost:8080/callback).
        In general this value is also configured in your OIDC provider to
        avoid redirection issues.
    * **oidc-relying-party-client-id**: The client id provide by your OIDC
        provider
    * **oidc-relying-party-secret-id**: The secret id provide by your OIDC
        provider

    And optionally:

    * **oidc-scope**: Specify what access privileges are being requested for
        Access Tokens. `cf Requesting claims using scope values
        <https://openid.net/specs/openid-connect-core-1_0.html#ScopeClaims`_.
        a list of claims using coma separator. (default value: `openid,email`)
    * **oidc-userinfo-field**: Specify which field to use from the response
        of the OIDC provider `userinfo endpoint <https://openid.net/specs/
        openid-connect-core-1_0.html#UserInfoResponse>`_. To make sure
        it's a known user. (default value: `email`).
    """

    client = Client(client_authn_method=CLIENT_AUTHN_METHOD)
    for config in [
            "oidc_provider_issuer",
            "oidc_relying_party_client_id",
            "oidc_relying_party_secret_id",
            "oidc_relying_party_callback",
    ]:
        if Configuration.get(config, None) is None:
            raise ValueError("You must provide {} parameter".format(config))
    provider_info = client.provider_config(
        Configuration.get("oidc_provider_issuer"))
    info = {
        "client_id": Configuration.get("oidc_relying_party_client_id"),
        "client_secret": Configuration.get("oidc_relying_party_secret_id"),
        "redirect_uris": [Configuration.get("oidc_relying_party_callback")],
    }
    info.update(provider_info._dict)
    client_reg = RegistrationResponse(**info)

    client.store_registration_info(client_reg)
    return client
Example #15
0
    def __init__(self, client_id=None, ca_certs=""):

        Client.__init__(self, client_id, ca_certs)

        self.request2endpoint = REQUEST2ENDPOINT.copy()
        self.request2endpoint["UserClaimsRequest"] = "userclaims_endpoint"
        self.response2error = RESPONSE2ERROR.copy()
        self.response2error["UserClaimsResponse"] = ["ErrorResponse"]
Example #16
0
    def __init__(self, client_id=None, ca_certs=""):

        Client.__init__(self, client_id, ca_certs)

        self.request2endpoint = REQUEST2ENDPOINT.copy()
        self.request2endpoint["UserClaimsRequest"] = "userclaims_endpoint"
        self.response2error = RESPONSE2ERROR.copy()
        self.response2error["UserClaimsResponse"] = ["ErrorResponse"]
Example #17
0
    def __init__(self, client_id=None, verify_ssl=True):

        Client.__init__(self, client_id, verify_ssl=verify_ssl)

        self.request2endpoint = REQUEST2ENDPOINT.copy()
        self.request2endpoint["UserClaimsRequest"] = "userclaims_endpoint"
        self.response2error = RESPONSE2ERROR.copy()
        self.response2error["UserClaimsResponse"] = ["ErrorResponse"]
Example #18
0
def test_construct_CheckSessionRequest():
    cli = Client()
    cli.check_session_endpoint = "https://example.org/oauth2/check_session"

    csr = cli.construct_CheckSessionRequest(
        request_args={"id_token": "id_token"})
    print csr
    assert ("%s" % csr) == 'id_token=id_token'
Example #19
0
def test_construct_UserInfoRequest():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"

    uir = cli.construct_UserInfoRequest(
        request_args={"access_token": "access_token"})
    print uir
    assert ("%s" % uir) == "access_token=access_token"
Example #20
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"])
Example #21
0
    def __init__(self, client_id=None, verify_ssl=True):

        Client.__init__(self, client_id, verify_ssl=verify_ssl)

        self.request2endpoint = REQUEST2ENDPOINT.copy()
        self.request2endpoint["UserClaimsRequest"] = "userclaims_endpoint"
        self.response2error = RESPONSE2ERROR.copy()
        self.response2error["UserClaimsResponse"] = ["ErrorResponse"]
Example #22
0
def prepare_client():
    # http://pyoidc.readthedocs.io/en/latest/examples/rp.html


    # Instantiate a client
    client = Client(client_authn_method=CLIENT_AUTHN_METHOD)


    # Register the OP
    # endpoints are now loaded from a json file rather than defined here
    # DEV endpoints
    # issuer = "https://unity.eudat-aai.fz-juelich.de:443"
    # authorization_endpoint = "https://unity.eudat-aai.fz-juelich.de:443/oauth2-as/oauth2-authz"
    # token_endpoint = "https://unity.eudat-aai.fz-juelich.de:443/oauth2/token"
    # userinfo_endpoint = "https://unity.eudat-aai.fz-juelich.de:443/oauth2/userinfo"
    # PROD endpoints
    # issuer = "https://b2access.eudat.eu:443"
    # authorization_endpoint = "https://b2access.eudat.eu:443/oauth2-as/oauth2-authz"
    # token_endpoint = "https://b2access.eudat.eu:443/oauth2/token"
    # userinfo_endpoint = "https://b2access.eudat.eu:443/oauth2/userinfo"
    try:
        dir = os.path.dirname(__file__)
        provider_endpoints = json.load(open(dir + '/provider_endpoints.json'))
        issuer = provider_endpoints['issuer']
        authorization_endpoint = provider_endpoints['authorization_endpoint']
        token_endpoint = provider_endpoints['token_endpoint']
        userinfo_endpoint = provider_endpoints['userinfo_endpoint']
    except:
        print "Error when reading provider_endpoints.json"
        stdlogger.error("Error when reading provider_endpoints.json")
        issuer = "error"
        authorization_endpoint = "error"
        token_endpoint = "error"
        userinfo_endpoint = "error"
    op_info = ProviderConfigurationResponse(issuer=issuer, authorization_endpoint=authorization_endpoint, token_endpoint=token_endpoint, userinfo_endpoint=userinfo_endpoint)
    client.provider_info = op_info


    # Set our credentials (that we got from manually registering to B2Access), as well as the redirect URI
    try:
        dir = os.path.dirname(__file__)
        client_credentials = json.load(open(dir + '/client_credentials.json'))
        id = client_credentials['client_id']
        secret = client_credentials['client_secret']
        uri = client_credentials['client_redirect_uri']
    except:
        print "Error when reading client_credential.json"
        stdlogger.error("Error when reading client_credential.json")
        id = "error"
        secret = "error"
        uri = "error"
    # /!\ Added the redirect URI here, else it's not defined later (in args ={[...] client.registration_response["redirect_uris"][0])
    uris = [uri]
    info = {"client_id": id, "client_secret": secret, "redirect_uris": uris}
    client_reg = RegistrationResponse(**info)
    client.store_registration_info(client_reg)
    return client
Example #23
0
def test_get_access_token_request():
    resp = AuthorizationResponse(code="code", state="state")

    grant = Grant(1)
    grant.add_code(resp)

    client = Client()
    client.grant["openid"] = grant
    time.sleep(2)
    raises(GrantExpired, 'client.construct_AccessTokenRequest(state="openid")')
Example #24
0
 def setup_class(self):
     self.client = Client(CLIENT_ID,
                          client_authn_method=CLIENT_AUTHN_METHOD)
     self.client.redirect_uris = ["http://example.com/redirect"]
     self.client.client_secret = CLIENT_SECRET
     self.client.keyjar[""] = KC_RSA
     self.client.behaviour = {
         "request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]
     }
     self._state = ""
Example #25
0
def test_get_access_token_request():
    resp = AuthorizationResponse(code="code", state="state")

    grant = Grant(1)
    grant.add_code(resp)

    client = Client()
    client.grant["openid"] = grant
    time.sleep(2)
    raises(GrantExpired, 'client.construct_AccessTokenRequest(state="openid")')
Example #26
0
def test_userinfo_request():
    cli = Client()
    cli.userinfo_endpoint = "http://example.com/userinfo"

    info = ARESP.to_urlencoded()
    cli.parse_response(AuthorizationResponse, info,
                       sformat="urlencoded", state="state0")

    cli.parse_response(AccessTokenResponse, TRESP.to_json(), state="state0")

    path, body, method, h_args = cli.user_info_request(state="state0")

    assert path == "http://example.com/userinfo?access_token=access_token"
    assert method == "GET"
    assert body is None
    assert h_args == {}

    path, body, method, h_args = cli.user_info_request(method="POST",
                                                       state="state0")

    assert path == "http://example.com/userinfo"
    assert method == "POST"
    assert body == "access_token=access_token"
    assert h_args == {'headers': {
        'content-type': 'application/x-www-form-urlencoded'}}

    path, body, method, h_args = cli.user_info_request(method="POST",
                                                       state="state0")

    assert path == "http://example.com/userinfo"
    assert method == "POST"
    assert body == "access_token=access_token"
    assert h_args == {'headers': {
        'content-type': 'application/x-www-form-urlencoded'}}
Example #27
0
def init_oidc_client(app):
    oidc_client = Client(client_authn_method=CLIENT_AUTHN_METHOD)
    oidc_client.store_registration_info(RegistrationRequest(**app.config['CLIENT_REGISTRATION_INFO']))
    provider = app.config['PROVIDER_CONFIGURATION_INFO']['issuer']
    try:
        oidc_client.provider_config(provider)
    except ConnectionError as e:
        app.logger.critical('No connection to provider {!s}. Can not start without provider configuration.'.format(
            provider))
        raise e
    return oidc_client
Example #28
0
def test_client_get_grant():
    cli = Client()

    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    cli.grant["state"] = grant

    gr1 = cli.grant_from_state("state")

    assert gr1.code == "code"
Example #29
0
def test_client_get_grant():
    cli = Client()

    resp = AuthorizationResponse(code="code", state="state")
    grant = Grant()
    grant.add_code(resp)

    cli.grant["state"] = grant

    gr1 = cli.grant_from_state("state")

    assert gr1.code == "code"
Example #30
0
 def _get_client(self):
     client = Client(client_id=self.conf['client_id'],
                     client_authn_method=CLIENT_AUTHN_METHOD)
     # Set client configurations based on issuer_url
     if not OpenIDConnectAuthPlugin.provider_config:
         OpenIDConnectAuthPlugin.provider_config = client.provider_config(
             self.conf['issuer_url'])
     else:
         client.handle_provider_config(
             OpenIDConnectAuthPlugin.provider_config,
             self.conf['issuer_url'])
     return client
Example #31
0
 def create_client(self):
     self.redirect_uri = "https://example.com/redirect"
     self.client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)
     self.client.redirect_uris = [self.redirect_uri]
     self.client.authorization_endpoint = "https://example.com/authorization"
     self.client.token_endpoint = "https://example.com/token"
     self.client.userinfo_endpoint = "https://example.com/userinfo"
     self.client.check_session_endpoint = "https://example.com/check_session"
     self.client.client_secret = "abcdefghijklmnop"
     self.client.keyjar[""] = KC_RSA
     self.client.behaviour = {
         "request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]
     }
Example #32
0
def test_authz_endpoint():
    server = provider_init

    cli = Client()
    cli.redirect_uris = ["http://www.example.org/authz"]
    cli.client_id = "client0"
    cli.state = "_state_"
    args = {"response_type": ["code", "token"], "scope": ["openid"]}
    req = cli.construct_AuthorizationRequest(request_args=args)

    resp = server.authorization_endpoint(request=req.to_urlencoded())
    print resp.message
    assert "token_type=Bearer" in resp.message
    assert "code=" in resp.message
Example #33
0
def test_construct_CheckSessionRequest_2():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(id_token="id_id_id_id", access_token="access", scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    uir = cli.construct_CheckSessionRequest(state="foo", scope=["openid"])
    print uir
    assert ("%s" % uir) == "id_token=id_id_id_id"
Example #34
0
def test_private_key_jwt():
    cli = Client("FOO")
    cli.token_endpoint = "https://example.com/token"
    cli.keyjar[""] = KC_RSA

    cis = AccessTokenRequest()
    at = oic.private_key_jwt(cli, cis, algorithm="RS256")
    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", "sub", "jti", "exp", "iat"])
    print header
    assert header == {'alg': 'RS256'}
Example #35
0
def test_client_parse_args():
    cli = Client()

    args = {
        "response_type": "",
        "client_id": "client_id",
        "redirect_uri": "http://example.com/authz",
        "scope": "scope",
        "state": "state",
    }
    ar_args = cli._parse_args(AuthorizationRequest, **args)

    print ar_args.keys()
    assert _eq(ar_args.keys(), ["scope", "state", "redirect_uri", "response_type", "client_id"])
Example #36
0
def test_request_attr_mis_match():
    redirect_uri = "http://example.com/redirect"
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)
    client.redirect_uris = [redirect_uri]
    client.authorization_endpoint = "http://example.com/authorization"
    client.client_secret = "abcdefghijklmnop"
    client.keyjar[""] = KC_RSA
    client.behaviour = {
        "request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]
    }

    srv = Server()
    srv.keyjar = KEYJ

    areq = client.construct_AuthorizationRequest(
        request_args={
            "scope": "openid",
            "response_type": ["code"],
            "max_age": 86400,
            "state": "foobar",
        },
        request_param="request",
    )

    for attr in ["state", "max_age", "client_id"]:
        del areq[attr]

    areq.lax = True
    req = srv.parse_authorization_request(query=areq.to_urlencoded())

    assert req.verify()
Example #37
0
def make_client(**kw_args):
    _cli = Client(client_authn_method=CLIENT_AUTHN_METHOD,
                  keyjar=kw_args["keyjar"])
    _cli.kid = kw_args["kidd"]
    _cli.jwks_uri = kw_args["jwks_uri"]

    try:
        _cli_info = kw_args["conf"].INFO["client"]
    except KeyError:
        pass
    else:
        for arg, val in _cli_info.items():
            setattr(_cli, arg, val)

    return _cli
Example #38
0
def test_construct_CheckSessionRequest_2():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(id_token="id_id_id_id",
                               access_token="access", scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    uir = cli.construct_CheckSessionRequest(state="foo", scope=["openid"])
    print uir
    assert ("%s" % uir) == "{'id_token': 'id_id_id_id'}"
Example #39
0
def test_construct_EndSessionRequest():
    cli = Client()
    cli.redirect_uris = ["http://example.com/authz"]
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(id_token="id_id_id_id", access_token="access", scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    args = {"redirect_url": "http://example.com/end"}
    esr = cli.construct_EndSessionRequest(state="foo", request_args=args)
    print esr.keys()
    assert _eq(esr.keys(), ["id_token", "state", "redirect_url"])
Example #40
0
def make_client(**kw_args):
    _, _keyjar, _ = build_keyjar(kw_args["conf"].keys)
    _cli = Client(client_authn_method=CLIENT_AUTHN_METHOD, keyjar=_keyjar)
    _cli.kid = kw_args["kidd"]
    _cli.jwks_uri = kw_args["jwks_uri"]

    try:
        _cli_info = kw_args["conf"].INFO["client"]
    except KeyError:
        pass
    else:
        for arg, val in _cli_info.items():
            setattr(_cli, arg, val)

    return _cli
Example #41
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"}
Example #42
0
def test_client_parse_args():
    cli = Client()

    args = {
        "response_type": "",
        "client_id": "client_id",
        "redirect_uri": "http://example.com/authz",
        "scope": "scope",
        "state": "state",
    }
    ar_args = cli._parse_args(AuthorizationRequest, **args)

    print ar_args.keys()
    assert _eq(ar_args.keys(), ['scope', 'state', 'redirect_uri',
                                'response_type', 'client_id'])
Example #43
0
    def __init__(self, flask_app, client_registration_info=None, issuer=None,
                 provider_configuration_info=None, userinfo_endpoint_method='POST',
                 extra_request_args=None):
        self.app = flask_app
        self.userinfo_endpoint_method = userinfo_endpoint_method
        self.extra_request_args = extra_request_args or {}

        self.client = Client(client_authn_method=CLIENT_AUTHN_METHOD)
        if not issuer and not provider_configuration_info:
            raise ValueError(
                'Either \'issuer\' (for dynamic discovery) or \'provider_configuration_info\' (for static configuration must be specified.')
        if issuer and not provider_configuration_info:
            self.client.provider_config(issuer)
        else:
            self.client.handle_provider_config(
                ProviderConfigurationResponse(**provider_configuration_info),
                provider_configuration_info['issuer'])

        self.client_registration_info = client_registration_info or {}

        # setup redirect_uri
        self.app.add_url_rule('/redirect_uri', 'redirect_uri',
                              self._handle_authentication_response)
        with self.app.app_context():
            self.client_registration_info['redirect_uris'] = url_for('redirect_uri')

        if client_registration_info and 'client_id' in client_registration_info:
            # static client info provided
            self.client.store_registration_info(RegistrationRequest(**client_registration_info))

        self.logout_view = None
Example #44
0
def test_construct_UserInfoRequest_2():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(refresh_token="refresh_with_me",
                               access_token="access", id_token="IDTOKEN",
                               scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    uir = cli.construct_UserInfoRequest(state="foo", scope=["openid"])
    print uir
    assert uir.keys() == ["access_token"]
Example #45
0
def test_client_parse_extra_args():
    cli = Client()

    args = {
        "response_type": "",
        "client_id": "client_id",
        "redirect_uri": "http://example.com/authz",
        "scope": "scope",
        "state": "state",
        "extra_session": "home"
    }
    ar_args = cli._parse_args(AuthorizationRequest, **args)

    print ar_args.keys()
    assert _eq(ar_args.keys(), ['state', 'redirect_uri', 'response_type',
                                'client_id', 'scope', 'extra_session'])
Example #46
0
def test_construct_UserInfoRequest_2():
    cli = Client()
    cli.userinfo_endpoint = "https://example.org/oauth2/userinfo"
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(refresh_token="refresh_with_me",
                               access_token="access", id_token="IDTOKEN",
                               scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    uir = cli.construct_UserInfoRequest(state="foo", scope=["openid"])
    print uir
    assert uir.keys() == ["access_token"]
Example #47
0
    def __init__(self, client_id, secret, redirect_uri,
                 allow_empty_state=True, issuer=_issuer):
        super(MiraclClient, self).__init__()

        self.issuer = issuer
        self.allow_empty_state = allow_empty_state
        client = Client(client_authn_method=CLIENT_AUTHN_METHOD)

        self.provider_info = client.provider_config(issuer=self.issuer)

        _logger.info(MIRACL_LOG_RECEIVED_PROVIDER_INFO, self.provider_info)

        self.info = {"client_id": client_id,
                     "client_secret": secret,
                     "redirect_uris": [redirect_uri]
                     }
Example #48
0
def test_fetch_distributed_claims_with_no_callback():
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)

    client.http_request = fake_request  # type: ignore # FIXME: Replace with responses?
    userinfo = {
        "sub": "foobar",
        "_claim_names": {"shoe_size": "src1"},
        "_claim_sources": {
            "src1": {"endpoint": "https://bank.example.com/claim_source"}
        },
    }

    _ui = client.fetch_distributed_claims(userinfo, callback=None)

    assert _ui["shoe_size"] == 10
    assert _ui["sub"] == "foobar"
Example #49
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"}
Example #50
0
def authorization_request(request):
    client = Client()
    hapax = rndstr()
    state = rndstr()
    params = {
        "authorization_endpoint": WSO2IS__AUTHORIZATIONENDPOINT,
        "client_id": CLIENT__OAUTH2KEY,
        "response_type": "code",
        "scope": ["openid"],
        "nonce": hapax,
        "redirect_uri": CLIENT__REDIRECTURL,
    }
    result = client.do_authorization_request(state=state, request_args=params)
    logger.debug(" auth (1) %s" % (state))
    request.session["state"] = state
    return HttpResponseRedirect(result.headers["location"])
Example #51
0
    def test_should_register_dynamic_client_if_client_registration_info_is_given(
            self):
        registration_endpoint = self.PROVIDER_BASEURL + '/register'
        redirect_uris = [
            'https://client.example.com/redirect',
            'https://client.example.com/redirect2'
        ]
        post_logout_redirect_uris = ['https://client.example.com/logout']
        responses.add(responses.POST,
                      registration_endpoint,
                      json={
                          'client_id': 'client1',
                          'client_secret': 'secret1',
                          'redirect_uris': redirect_uris,
                          'post_logout_redirect_uris':
                          post_logout_redirect_uris
                      })

        provider_config = ProviderConfiguration(
            provider_metadata=self.provider_metadata(
                registration_endpoint=registration_endpoint),
            client_registration_info=ClientRegistrationInfo(
                redirect_uris=redirect_uris,
                post_logout_redirect_uris=post_logout_redirect_uris))

        provider_config.register_client(Client(CLIENT_AUTHN_METHOD))
        assert provider_config._client_metadata['client_id'] == 'client1'
        assert provider_config._client_metadata['client_secret'] == 'secret1'
        assert provider_config._client_metadata[
            'redirect_uris'] == redirect_uris
        assert provider_config._client_metadata[
            'post_logout_redirect_uris'] == post_logout_redirect_uris
Example #52
0
def test_construct_EndSessionRequest():
    cli = Client()
    cli.redirect_uris = ["http://example.com/authz"]
    cli.grant["foo"] = Grant()
    cli.grant["foo"].grant_expiration_time = time.time() + 60
    cli.grant["foo"].code = "access_code"

    resp = AccessTokenResponse(id_token="id_id_id_id",
                               access_token="access", scope=["openid"])

    cli.grant["foo"].tokens.append(Token(resp))

    args = {"redirect_url": "http://example.com/end"}
    esr = cli.construct_EndSessionRequest(state="foo", request_args=args)
    print esr.keys()
    assert _eq(esr.keys(), ['id_token', 'state', "redirect_url"])
Example #53
0
    def __init__(self, client_id=None, verify_ssl=None, settings=None):
        self.settings = settings or OicClientSettings()
        if verify_ssl is not None:
            warnings.warn(
                "`verify_ssl` is deprecated, please use `settings` instead if you need to set a non-default value.",
                DeprecationWarning,
                stacklevel=2,
            )
            self.settings.verify_ssl = verify_ssl

        Client.__init__(self, client_id, settings=self.settings)

        self.request2endpoint = REQUEST2ENDPOINT.copy()
        self.request2endpoint["UserClaimsRequest"] = "userclaims_endpoint"
        self.response2error = RESPONSE2ERROR.copy()
        self.response2error["UserClaimsResponse"] = ["ErrorResponse"]
    def __enter__(self):
        self.patch_requests()

        self.client = Client(client_authn_method=CLIENT_AUTHN_METHOD)

        self.client.provider_config(self.https_issuer)
        self.client.store_registration_info(
            RegistrationRequest(
                **{
                    'issuer': self.issuer,
                    'client_id': 'test-client',
                    'client_secret': 'test-secret',
                    'redirect_uris': 'http://example.com/oidc_callback'
                }))

        return self
Example #55
0
def pedir_autorizacion(request):
    cliente = Client()
    hapax = rndstr()
    estado = rndstr()
    parametros = {
        "authorization_endpoint": endpoint_autorizacion,
        "client_id": llave,
        "response_type": "code",
        "scope": ["openid"],
        "nonce": hapax,
        "redirect_uri": callback
    }
    resultado = cliente.do_authorization_request(state=estado,
                                                 request_args=parametros)
    request.session['estado'] = estado
    return HttpResponseRedirect(resultado.headers['location'])
Example #56
0
 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.keyjar[""] = KC_RSA
     self.client.behaviour = {"request_object_signing_alg": DEF_SIGN_ALG["openid_request_object"]}
     self._state = ""
Example #57
0
def test_construct_RegistrationRequest():
    cli = Client()
    cli.redirect_uris = ["http://example.com/authz"]

    request_args = {
        "type": "client_associate",
        "client_id": CLIENT_ID,
        "contacts": ["*****@*****.**"],
        "application_type": "web",
        "application_name": "EXAMPLE OIC service",
    }

    crr = cli.construct_RegistrationRequest(request_args=request_args)

    print crr.keys()
    assert _eq(crr.keys(), ["application_name", "application_type", "type", "client_id", "contacts", "redirect_uris"])
Example #58
0
    def __init__(
        self,
        session_db,
        consumer_config,
        client_config=None,
        server_info=None,
        debug=False,
        client_prefs=None,
    ):
        """
        Initialize a Consumer instance.

        :param session_db: Where info are kept about sessions
        :param config: Configuration of the consumer
        :param client_config: Client configuration
        :param server_info: Information about the server
        :param client_prefs: Run time preferences, which are chosen depends
        on what the server can do.
        """
        if client_config is None:
            client_config = {}

        Client.__init__(self, **client_config)

        self.consumer_config = consumer_config
        if consumer_config:
            try:
                self.debug = consumer_config["debug"]
            except KeyError:
                self.debug = 0

        if server_info:
            for endpoint in ENDPOINTS:
                try:
                    setattr(self, endpoint, server_info[endpoint])
                except KeyError:
                    setattr(self, endpoint, "")

        self.sdb = session_db
        self.debug = debug
        self.seed = ""
        self.nonce = ""
        self.request_filename = ""
        self.request_uri = ""
        self.user_info = None
        self.registration_expires_at = 0
        self.secret_type = "Bearer"
Example #59
0
def test_fetch_distributed_claims_with_no_callback():
    """ Mirrors the first lines in do_userinfo_request"""
    client = Client(CLIENT_ID, client_authn_method=CLIENT_AUTHN_METHOD)

    client.http_request = fake_request
    userinfo = {
        'sub': 'foobar',
        '_claim_names': {'shoe_size': 'src1'},
        '_claim_sources': {
            "src1": {
                "endpoint": "https://bank.example.com/claim_source"}}
    }

    _ui = client.fetch_distributed_claims(userinfo, callback=None)

    assert _ui['shoe_size'] == 10
    assert _ui['sub'] == 'foobar'