当前位置: 首页>>代码示例>>Python>>正文


Python IdPConfig.load方法代码示例

本文整理汇总了Python中saml2.config.IdPConfig.load方法的典型用法代码示例。如果您正苦于以下问题:Python IdPConfig.load方法的具体用法?Python IdPConfig.load怎么用?Python IdPConfig.load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在saml2.config.IdPConfig的用法示例。


在下文中一共展示了IdPConfig.load方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_crypto_backend

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
def test_crypto_backend():
    idpc = IdPConfig()
    idpc.load(IDP_XMLSECURITY)

    assert idpc.crypto_backend == 'XMLSecurity'
    sec = security_context(idpc)
    assert isinstance(sec.crypto, CryptoBackendXMLSecurity)
开发者ID:Amli,项目名称:pysaml2,代码行数:9,代码来源:test_31_config.py

示例2: SamlServer

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
class SamlServer(object):
    """
    SAML Wrapper around pysaml2.

    Implements SAML2 Identity Provider functionality for Flask.
    """
    def __init__(self, config, attribute_map=None):
        """Initialize SAML Identity Provider.

        Args:
            config (dict): Identity Provider config info in dict form
            attribute_map (dict): Mapping of attribute keys to user data
        """
        self._config = IdPConfig()
        self._config.load(config)
        self._server = Server(config=self._config)
        self.attribute_map = {}
        if attribute_map is not None:
            self.attribute_map = attribute_map

    def handle_authn_request(self, request, login_form_cb):
        """Handles authentication request.

        TODO: create default login_form_cb, with unstyled login form?

        Args:
            request (Request): Flask request object for this HTTP transaction.
            login_form_cb (function): Function that displays login form with 
                username and password fields. Takes a single parameter which
                is the service_provider_id so the form may be styled accordingly.
        """
        if 'SAMLRequest' in request.values:
            details = self._server.parse_authn_request(request.details,
                BINDING_HTTP_REDIRECT)
            # TODO: check session for already authenticated user
            # and send authn_response immediately.
            # TODO: otherwise render login form login_form_cb(service_provider_id)
        else:
            pass # TODO: bad request?

    def get_service_provider_id(self, request):
        # TODO: pull service_provider_id from session
        pass

    def authn_response(self, userid):
        service_provider_id = get_service_provider_id()
        # TODO: send authn_response
        pass

    def get_metadata(self):
        """Returns SAML Identity Provider Metadata"""
        edesc = entity_descriptor(self._config, 24)
        if self._config.key_file:
            edesc = sign_entity_descriptor(edesc, 24, None, security_context(self._config))
        response = make_response(str(edesc))
        response.headers['Content-type'] = 'text/xml; charset=utf-8'
        return response
开发者ID:dellintosh,项目名称:flask_pysaml2,代码行数:59,代码来源:flask_pysaml2.py

示例3: create_authn_response

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
def create_authn_response(session_id, identity=dict(), sign=True):
    config = IdPConfig()
    config.load(idp_config)
    idp_server = Server(config=config)
    idp_server.ident = Identifier(auth.AuthDictCache(dict(), '_ident'))
    authn_response = str(idp_server.authn_response(
        identity=identity,
        in_response_to=session_id,
        destination='https://foo.example.com/sp/acs',
        sp_entity_id='https://foo.example.com/sp/metadata',
        name_id_policy=None,
        userid='Irrelevent',
        sign=sign,
        instance=True))
    response = samlp.response_from_string(authn_response)
    return response.assertion[0].subject.name_id.text, authn_response
开发者ID:dellintosh,项目名称:flask_pysaml2,代码行数:18,代码来源:test_saml.py

示例4: auth_response

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
def auth_response(identity, in_response_to, sp_conf):
    """Generates a fresh signed authentication response"""
    sp_entity_id = sp_conf.entityid
    idp_entity_id = sp_conf.idps().keys()[0]
    acs = sp_conf.endpoint('assertion_consumer_service')[0]
    issuer = saml.Issuer(text=idp_entity_id, format=saml.NAMEID_FORMAT_ENTITY)
    response = response_factory(issuer=issuer,
                                in_response_to=in_response_to,
                                destination=acs,
                                status=success_status_factory())
    idp_conf = IdPConfig()
    name_form = "urn:oasis:names:tc:SAML:2.0:attrname-format:uri"
    idp_conf.load({
            'entityid': idp_entity_id,
            'xmlsec_binary': sp_conf.xmlsec_binary,
            'attribute_map_dir': os.path.join(BASEDIR, 'attribute-maps'),
            'service': {
                'idp': {
                    'endpoints': tuple(),
                    'policy':  {
                        'default': {
                            "lifetime": {"minutes": 15},
                            "attribute_restrictions": None,
                            "name_form": name_form,
                            }
                        }
                    },
                },
            'key_file': os.path.join(BASEDIR, 'idpcert.key'),
            'cert_file': os.path.join(BASEDIR, 'idpcert.pem'),
            'metadata': {
                'local': [os.path.join(BASEDIR, 'sp_metadata.xml')],
                },
            })
    server = Server("", idp_conf)
    server.ident = Identifier(FakeDb())

    userid = 'irrelevant'
    response = server.authn_response(identity, in_response_to, acs,
                                     sp_entity_id, None, userid)
    return '\n'.join(response)
开发者ID:FluidReview,项目名称:djangosaml2,代码行数:43,代码来源:auth_response.py

示例5: _parse_metadata_dict_to_inline

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
def _parse_metadata_dict_to_inline(metadata):
    """Convert any metadata included as dict to PySAML2's `inline` type.

    Currently PySAML supports remote, local files, and string IdP metadata to
    be included in the SP config dict as XML. It is also possible to pull your
    IdP metadata from local JSON files (the format of the JSON is nearly
    unparsable for any normal human).

    This function adds the ability to include the IdP metadata directly in the
    SP config as a dict of IdP attributes by hacking around this PySAML2
    limitation and converting the dict into XML via PySAML2's IdPConfig class.

    Note: In the process of trying to find an alternative which will allow us
        to NOT be hacking around PySAML so rudely in order to load IdP metadata
        from a Python dict. https://github.com/rohe/pysaml2/issues/172

    Args:
        metadata (dict): The IdP metadata this SP is configured for.

    Returns:
        (dict) config where any metadata `inline_dict` data has been
            converted to `inline` XML.
    """
    if metadata.get('inline_dict', None):
        metadata['inline'] = metadata.get('inline', [])
        for _idp in metadata.get('inline_dict'):
            idp_config = IdPConfig()
            idp_config.load(_idp)
            entity_desc = entity_descriptor(idp_config)
            # Hack for supporting multiple certificates.
            if _idp.get('certs'):
                # `certs` config directive overrides `cert_file`.
                entity_desc.idpsso_descriptor.key_descriptor = \
                    _parse_key_descriptors(_idp['certs'])
            idp_metadata_str = str(entity_desc)
            LOGGER.debug("IdP XML Metadata for %s: %s",
                         _idp['entityid'], idp_metadata_str)
            metadata['inline'].append(idp_metadata_str)
        del metadata['inline_dict']
    return metadata
开发者ID:KaviCorp,项目名称:flask_pysaml2,代码行数:42,代码来源:flask_pysaml2.py

示例6: create_logout_response

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
def create_logout_response(subject_id, destination, issuer_entity_id,
        req_entity_id, sign=True):
    config = IdPConfig()
    config.load(idp_config)
    idp_server = Server(config=config)
    # construct a request
    logout_request = create_logout_request(
        subject_id=subject_id,
        destination=destination,
        issuer_entity_id=issuer_entity_id,
        req_entity_id=req_entity_id)
    #idp_server.ident = Identifier(auth.AuthDictCache(dict(), '_ident'))
    resp, headers, message = idp_server.logout_response(
        request=logout_request,
        bindings=[BINDING_HTTP_REDIRECT],
        sign=sign)
    location = dict(headers).get('Location')
    url = urlparse.urlparse(location)
    params = urlparse.parse_qs(url.query)
    logout_response_xml = decode_base64_and_inflate(params['SAMLResponse'][0])
    response = samlp.logout_response_from_string(logout_response_xml)
    return response.in_response_to, logout_response_xml
开发者ID:dellintosh,项目名称:flask_pysaml2,代码行数:24,代码来源:test_saml.py

示例7: __init__

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
    def __init__(self, config, attribute_map=None):
        """Initialize SAML Service Provider.

        Args:
            config (dict): Service Provider config info in dict form
            attribute_map (dict): Mapping of attribute keys to user data
        """
        self._config = SPConfig()
        self._config.load(config)
        if config['metadata'].get('config'):
            # Hacked in a way to get the IdP metadata from a python dict
            # rather than having to resort to loading XML from file or http.
            idp_config = IdPConfig()
            idp_config.load(config['metadata']['config'][0])
            idp_entityid = config['metadata']['config'][0]['entityid']
            idp_metadata_str = str(entity_descriptor(idp_config, 24))
            LOGGER.debug('IdP XML Metadata for %s: %s' % (
                idp_entityid, idp_metadata_str))
            self._config.metadata.import_metadata(
                idp_metadata_str, idp_entityid)
        self.attribute_map = {}
        if attribute_map is not None:
            self.attribute_map = attribute_map
开发者ID:dellintosh,项目名称:flask_pysaml2,代码行数:25,代码来源:flask_pysaml2.py

示例8: saml_redirect

# 需要导入模块: from saml2.config import IdPConfig [as 别名]
# 或者: from saml2.config.IdPConfig import load [as 别名]
def saml_redirect(request, sp_name, ms):
    '''
    Redirect to a saml sp acs
    '''
    # ** Init SAML IDP
    setting = get_saml_setting(sp_name)

    conf = IdPConfig()
    conf.load(copy.deepcopy(setting))

    IDP = server.Server(config=conf, cache=Cache())
    IDP.ticket = {}

    # ** Get sp entity id from sp.xml
    entity_id = IDP.metadata.keys()[0]

    # ** Get binding and acs destination
    # pass bindings=None, correct?
    binding, destination = IDP.pick_binding("assertion_consumer_service", entity_id=entity_id)

    authn = {'class_ref': 'urn:oasis:names:tc:SAML:2.0:ac:classes:Password'}

    # ** Prepare attributes
    attribute_setting = ms.get('attributes')
    parsed_data = {}
    for attr in attribute_setting:
        if not attr['name']:
            continue

        mapped_name = attr['map'] if 'map' in attr else attr['name']
        value = None

        try:
            if attr['name'] == "email":
                value = request.user.email
            if attr['name'] == "first_name":
                value = request.user.first_name
            elif attr['name'] == "last_name":
                value = request.user.last_name
            elif attr['name'] == "username":
                value = request.user.username
            elif attr['name'] == "state":
                value = request.user.profile.district.state.name
            elif attr['name'] == "district":
                value = request.user.profile.district.name
            elif attr['name'] == "school":
                value = request.user.profile.school.name
            elif attr['name'] == "grades":
                value = request.user.profile.grade_level_id
            elif attr['name'] == "bio":
                value = request.user.profile.bio
            elif attr['name'] == "internal_id":
                value = str(request.user.id)
            elif attr['name'] == "avatar":
                value = request.build_absolute_uri(reverse('user_photo', args=[request.user.id]))
        except:
            value = None
        if value is not None:
            parsed_data[mapped_name] = [value]
        else:
            parsed_data[mapped_name] = ['']


    # ** Get the X509Certificate string from sp.xml
    sign = IDP.metadata.certs(entity_id, "any", "signing")

    # ** Create authn response
    identity = parsed_data
    resp = IDP.create_authn_response(
        issuer=setting.get('entityid'),  # "https://localhost:8088/idp.xml",
        identity=identity,
        sign_response=sign,
        sign_assertion=sign,
        in_response_to=None,
        destination=destination,
        sp_entity_id=entity_id,
        name_id_policy=None,             # "urn:oasis:names:tc:SAML:2.0:nameid-format:transient"
        authn=authn,
        encrypt_cert="",
        encrypt_assertion="",
        # userid="%s" % request.user.id,
        )

    # ** Translate to http response
    http_args = IDP.apply_binding(
        binding=binding,
        msg_str=resp,
        destination=destination,
        relay_state="",
        response=True)

    resp = "\n".join(http_args["data"])
    resp = resp.replace("<body>", "<body style='display:none'>")
    return HttpResponse(resp)
开发者ID:EduPepperPDTesting,项目名称:pepper2013-testing,代码行数:96,代码来源:idp.py


注:本文中的saml2.config.IdPConfig.load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。