Ejemplo n.º 1
0
def verify_client(inst, areq, authn, type_method=TYPE_METHOD):
    """
    Guess authentication method and get client from that.

    :param inst: Entity instance
    :param areq: The request
    :param authn: client authentication information
    :return: tuple containing client id and client authentication method
    """
    if authn:  # HTTP Basic auth (client_secret_basic)
        cid = get_client_id(inst.cdb, areq, authn)
        auth_method = "client_secret_basic"
    elif "client_secret" in areq:  # client_secret_post
        client_id = get_client_id(inst.cdb, areq, authn)
        logger.debug("Verified Client ID: %s" % client_id)
        cid = ClientSecretBasic(inst).verify(areq, client_id)
        auth_method = "client_secret_post"
    elif "client_assertion" in areq:  # client_secret_jwt or private_key_jwt
        check_key_availability(inst, areq["client_assertion"])

        for typ, method in type_method:
            if areq["client_assertion_type"] == typ:
                cid, auth_method = method(inst).verify(areq)
                break
        else:
            logger.error(
                "UnknownAssertionType: {}".format(areq["client_assertion_type"])
            )
            raise UnknownAssertionType(areq["client_assertion_type"], areq)
    else:
        logger.error("Missing client authentication.")
        raise FailedAuthentication("Missing client authentication.")

    if isinstance(areq, AccessTokenRequest):
        try:
            _method = inst.cdb[cid]["token_endpoint_auth_method"]
        except KeyError:
            _method = "client_secret_basic"

        if _method != auth_method:
            logger.error(
                "Wrong authentication method used: {} != {}".format(
                    auth_method, _method
                )
            )
            raise FailedAuthentication("Wrong authentication method used")

    # store which authn method was used where
    try:
        inst.cdb[cid]["auth_method"][areq.__class__.__name__] = auth_method
    except KeyError:
        try:
            inst.cdb[cid]["auth_method"] = {areq.__class__.__name__: auth_method}
        except KeyError:
            pass

    return cid
Ejemplo n.º 2
0
def verify_client(inst, areq, authn, type_method=TYPE_METHOD):
    """
    Initiated Guessing !

    :param areq: The request
    :param authn: client authentication information
    :return: tuple containing client id and client authentication method
    """

    if authn:  # HTTP Basic auth (client_secret_basic)
        cid = get_client_id(inst.cdb, areq, authn)
        auth_method = 'client_secret_basic'
    elif "client_secret" in areq:  # client_secret_post
        client_id = get_client_id(inst.cdb, areq, authn)
        logger.debug("Verified Client ID: %s" % client_id)
        cid = ClientSecretBasic(inst).verify(areq, client_id)
        auth_method = 'client_secret_post'
    elif "client_assertion" in areq:  # client_secret_jwt or private_key_jwt
        for typ, method in type_method:
            if areq["client_assertion_type"] == typ:
                cid, auth_method = method(inst).verify(areq)
                break
        else:
            raise UnknownAssertionType(areq["client_assertion_type"], areq)
    else:
        raise FailedAuthentication("Missing client authentication.")

    if isinstance(areq, AccessTokenRequest):
        try:
            _method = inst.cdb[cid]['token_endpoint_auth_method']
        except KeyError:
            _method = 'client_secret_basic'

        if _method != auth_method:
            raise FailedAuthentication("Wrong authentication method used")

    # store which authn method was used where
    try:
        inst.cdb[cid]['auth_method'][areq.__class__.__name__] = auth_method
    except KeyError:
        try:
            inst.cdb[cid]['auth_method'] = {
                areq.__class__.__name__: auth_method
            }
        except KeyError:
            pass

    return cid
Ejemplo n.º 3
0
def get_client_id(cdb, req, authn):
    """
    Verify the client and return the client id

    :param req: The request
    :param authn: Authentication information from the HTTP header
    :return:
    """

    logger.debug("REQ: %s" % req.to_dict())
    if authn:
        if authn.startswith("Basic "):
            logger.debug("Basic auth")
            (_id, _secret) = base64.b64decode(
                authn[6:].encode("utf-8")).decode("utf-8").split(":")

            _id = as_unicode(_id)
            if _id not in cdb:
                logger.debug("Unknown client_id")
                raise FailedAuthentication("Unknown client_id")
            else:
                if not valid_client_info(cdb[_id]):
                    logger.debug("Invalid Client info")
                    raise FailedAuthentication("Invalid Client")

                if _secret != cdb[_id]["client_secret"]:
                    logger.debug("Incorrect secret")
                    raise FailedAuthentication("Incorrect secret")
        else:
            if authn[:6].lower() == "bearer":
                logger.debug("Bearer auth")
                _token = authn[7:]
            else:
                raise FailedAuthentication("AuthZ type I don't know")

            try:
                _id = cdb[_token]
            except KeyError:
                logger.debug("Unknown access token")
                raise FailedAuthentication("Unknown access token")
    else:
        try:
            _id = str(req["client_id"])
            if _id not in cdb:
                logger.debug("Unknown client_id")
                raise FailedAuthentication("Unknown client_id")
            if not valid_client_info(cdb[_id]):
                raise FailedAuthentication("Invalid client_id")
        except KeyError:
            raise FailedAuthentication("Missing client_id")

    return _id
Ejemplo n.º 4
0
def get_client_id(cdb, req, authn):
    """
    Verify the client and return the client id.

    :param req: The request
    :param authn: Authentication information from the HTTP header
    :return:
    """
    logger.debug("REQ: %s" % sanitize(req.to_dict()))
    _secret = None
    if not authn:
        try:
            _id = str(req["client_id"])
        except KeyError:
            raise FailedAuthentication("Missing client_id")
    elif authn.startswith("Basic "):
        logger.debug("Basic auth")
        (_id, _secret) = (
            base64.b64decode(authn[6:].encode("utf-8")).decode("utf-8").split(":")
        )
        # Either as string or encoded
        if _id not in cdb:
            _bid = as_bytes(_id)
            _id = _bid
    elif authn[:6].lower() == "bearer":
        logger.debug("Bearer auth")
        _token = authn[7:]
        try:
            _id = cdb[_token]
        except KeyError:
            logger.debug("Unknown access token")
            raise FailedAuthentication("Unknown access token")
    else:
        raise FailedAuthentication("AuthZ type I don't know")
    # We have the client_id by now, so let's verify it
    _cinfo = cdb.get(_id)
    if _cinfo is None:
        raise FailedAuthentication("Unknown client")
    if not valid_client_info(_cinfo):
        logger.debug("Invalid Client info")
        raise FailedAuthentication("Invalid Client")
    if _secret is not None:
        if _secret != _cinfo["client_secret"]:
            logger.debug("Incorrect secret")
            raise FailedAuthentication("Incorrect secret")
    # All should be good, so return it
    return _id
    def get_client_id(self, req, authn):
        """
        Verify the client and return the client id

        :param req: The request
        :param authn: Authentication information from the HTTP header
        :return:
        """

        logger.debug("REQ: %s" % req.to_dict())
        if authn:
            if authn.startswith("Basic "):
                logger.debug("Basic auth")
                (_id, _secret) = base64.b64decode(authn[6:]).split(":")
                if _id not in self.cdb:
                    logger.debug("Unknown client_id")
                    raise FailedAuthentication("Unknown client_id")
                else:
                    try:
                        assert _secret == self.cdb[_id]["client_secret"]
                    except AssertionError:
                        logger.debug("Incorrect secret")
                        raise FailedAuthentication("Incorrect secret")
            else:
                try:
                    assert authn[:6].lower() == "bearer"
                    logger.debug("Bearer auth")
                    _token = authn[7:]
                except AssertionError:
                    raise FailedAuthentication("AuthZ type I don't know")

                try:
                    _id = self.cdb[_token]
                except KeyError:
                    logger.debug("Unknown access token")
                    raise FailedAuthentication("Unknown access token")
        else:
            try:
                _id = req["client_id"]
                if _id not in self.cdb:
                    logger.debug("Unknown client_id")
                    raise FailedAuthentication("Unknown client_id")
            except KeyError:
                raise FailedAuthentication("Missing client_id")

        return _id
Ejemplo n.º 6
0
def verify_client(inst, areq, authn, type_method=TYPE_METHOD):
    """
    Initiated Guessing !

    :param areq: The request
    :param authn: client authentication information
    :return:
    """

    if authn:  # HTTP Basic auth (client_secret_basic)
        return get_client_id(inst.cdb, areq, authn)
    elif "client_secret" in areq:  # client_secret_post
        client_id = get_client_id(inst.cdb, areq, authn)
        logger.debug("Verified Client ID: %s" % client_id)
        return ClientSecretBasic(inst).verify(areq, client_id)
    elif "client_assertion" in areq:  # client_secret_jwt or private_key_jwt
        for typ, method in type_method:
            if areq["client_assertion_type"] == typ:
                return method(inst).verify(areq)
        else:
            raise UnknownAssertionType(areq["client_assertion_type"], areq)
    else:
        raise FailedAuthentication("Missing client authentication.")