def test_crypto_backend():
    idpc = IdPConfig()
    idpc.load(IDP_XMLSECURITY)

    assert idpc.crypto_backend == 'XMLSecurity'
    sec = security_context(idpc)
    assert isinstance(sec.crypto, CryptoBackendXMLSecurity)
Beispiel #2
0
 def dispatch(self, request, *args, **kwargs):
     """ Construct IDP server with config from settings dict
     """
     conf = IdPConfig()
     conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
     self.IDP = Server(config=conf)
     return super(IdPHandlerViewMixin, self).dispatch(request, *args, **kwargs)
Beispiel #3
0
def test_crypto_backend():
    idpc = IdPConfig()
    idpc.load(IDP_XMLSECURITY)

    assert idpc.crypto_backend == 'XMLSecurity'
    sec = security_context(idpc)
    assert isinstance(sec.crypto, CryptoBackendXMLSecurity)
Beispiel #4
0
def metadata(request):
    """ Returns an XML with the SAML 2.0 metadata for this Idp.
        The metadata is constructed on-the-fly based on the config dict in the django settings.
    """
    conf = IdPConfig()
    conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
    metadata = entity_descriptor(conf)
    return HttpResponse(content=text_type(metadata).encode('utf-8'), content_type="text/xml; charset=utf8")
Beispiel #5
0
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
 def metadata(cls) -> str:
     conf = IdPConfig()
     try:
         conf.load(cls.construct_metadata())
         metadata = entity_descriptor(conf)
     except:
         pass
     return str(metadata)
             
Beispiel #7
0
 def metadata(cls) -> str:
     """ Get the IDP metadata as a string. """
     conf = IdPConfig()
     try:
         conf.load(cls.construct_metadata())
         metadata = entity_descriptor(conf)
     except Exception as e:
         raise ImproperlyConfigured(_('Could not instantiate IDP metadata based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
     return str(metadata)
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
Beispiel #9
0
 def dispatch(self, request, *args, **kwargs):
     """ Construct IDP server with config from settings dict
     """
     conf = IdPConfig()
     try:
         conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
         self.IDP = Server(config=conf)
     except Exception as e:
         return self.handle_error(request, exception=e)
     return super().dispatch(request, *args, **kwargs)
 def load(cls, force_refresh:bool = False) -> Server:
     if cls._server_instance is None or force_refresh:
         conf = IdPConfig() #
         md = cls.construct_metadata() #
         try:
             conf.load(md)
             cls._server_instance = Server(config=conf)
         except:
             pass
     return cls._server_instance
Beispiel #11
0
 def dispatch(self, request, *args, **kwargs):
     """ Construct IDP server with config from settings dict
     """
     conf = IdPConfig()
     try:
         conf.load(copy.deepcopy(get_idp_config()))
         self.IDP = Server(config=conf)
     except Exception as e:
         return self.handle_error(request, exception=e)
     return super(IdPHandlerViewMixin,
                  self).dispatch(request, *args, **kwargs)
Beispiel #12
0
 def load(cls, force_refresh: bool = False) -> Server:
     """ Instantiate a IDP Server instance based on the config defined in the SAML_IDP_CONFIG settings.
         Throws an ImproperlyConfigured exception if it could not do so for any reason.
     """
     if cls._server_instance is None or force_refresh:
         conf = IdPConfig()
         md = cls.construct_metadata()
         try:
             conf.load(md)
             cls._server_instance = Server(config=conf)
         except Exception as e:
             raise ImproperlyConfigured(_('Could not instantiate an IDP based on the SAML_IDP_CONFIG settings and configured ServiceProviders: {}').format(str(e)))
     return cls._server_instance
Beispiel #13
0
def run():
    '''配置IdP,生成证书、元数据文件'''
    if not os.path.exists(BASEDIR+'/djangosaml2idp/certificates/mycert.pem') or not \
        os.path.exists(BASEDIR+'/djangosaml2idp/certificates/mykey.pem'):
        create_self_signed_cert()

    conf = IdPConfig()  # pylint: disable=invalid-name
    conf.load(copy.deepcopy(idpsettings.SAML_IDP_CONFIG))
    meta_data = entity_descriptor(conf)  # pylint: disable=invalid-name
    content = text_type(meta_data).encode('utf-8')
    with open(BASEDIR + '/djangosaml2idp/saml2_config/idp_metadata.xml',
              'wb') as f:
        f.write(content)
Beispiel #14
0
    def dispatch(self, request, *args, **kwargs):
        """
        Construct IDP server with config from settings dict
        """
        conf = IdPConfig()
        try:
            SAML_IDP_CONFIG = {  # pylint: disable=invalid-name
                'debug': settings.DEBUG,
                'xmlsec_binary': get_xmlsec_binary(['/opt/local/bin', '/usr/bin/xmlsec1']),
                'entityid': '%s/saml/metadata/' % settings.BASE_URL,
                'description': 'longguikeji IdP setup',

                'service': {
                    'idp': {
                        'name': 'Django localhost IdP',
                        'endpoints': {
                            'single_sign_on_service': [
                                ('%s/saml/sso/post/' % settings.BASE_URL, BINDING_HTTP_POST),
                                ('%s/saml/sso/redirect/' % settings.BASE_URL, BINDING_HTTP_REDIRECT),
                            ],
                        },
                        'name_id_format': [NAMEID_FORMAT_EMAILADDRESS, NAMEID_FORMAT_UNSPECIFIED],
                        'sign_response': True,
                        'sign_assertion': True,
                    },
                },

                'metadata': {
                    'local': [os.path.join(os.path.join(os.path.join(BASEDIR, 'djangosaml2idp'), \
                                                        'saml2_config'), f) for f in
                              os.listdir(BASEDIR + '/djangosaml2idp/saml2_config/') \
                              if f.split('.')[-1] == 'xml'],
                },
                # Signing
                'key_file': BASEDIR + '/djangosaml2idp/certificates/mykey.pem',
                'cert_file': BASEDIR + '/djangosaml2idp/certificates/mycert.pem',
                # Encryption
                'encryption_keypairs': [{
                    'key_file': BASEDIR + '/djangosaml2idp/certificates/mykey.pem',
                    'cert_file': BASEDIR + '/djangosaml2idp/certificates/mycert.pem',
                }],
                'valid_for': 365 * 24,
            }

            conf.load(copy.copy(SAML_IDP_CONFIG))
            self.IDP = Server(config=conf)  # pylint: disable=invalid-name
        except Exception as e:  # pylint: disable=invalid-name, broad-except
            return self.handle_error(request, exception=e)
        return super(IdPHandlerViewMixin,
                     self).dispatch(request, *args, **kwargs)
Beispiel #15
0
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
Beispiel #16
0
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
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)
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)
Beispiel #19
0
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
Beispiel #20
0
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
Beispiel #21
0
def get_idp_config(saml_idp_config=settings.SAML_IDP_CONFIG):
    conf = IdPConfig()
    idp_config = copy.deepcopy(saml_idp_config)

    # this is only used for merge DB metadatastores configurations
    db_mdstores = MetadataStore.as_pysaml_mdstore_dict()
    for k,v in db_mdstores.items():
        if not idp_config['metadata'].get(k):
            idp_config['metadata'][k] = []
        for endpoint in v:
            if endpoint not in idp_config['metadata'][k]:
                idp_config['metadata'][k].append(endpoint)
    # end DB metadatastores configurations
    try:
        conf.load(idp_config)
    except FileNotFoundError as e: # pragma: no cover
        raise MetadataNotFound(e)
    except xml.etree.ElementTree.ParseError as e: # pragma: no cover
        raise SPConfigurationMissing(e)
    except Exception as e: # pragma: no cover
        raise Exception(e)
    return Server(config=conf)
Beispiel #22
0
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
Beispiel #23
0
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
    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
Beispiel #25
0
def login_process(request):
    """ View which processes the actual SAML request and returns a self-submitting form with the SAML response.
        The login_required decorator ensures the user authenticates first on the IdP using 'normal' ways.
    """
    # Construct server with config from settings dict
    conf = IdPConfig()
    conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))
    IDP = Server(config=conf)
    # Parse incoming request
    try:
        req_info = IDP.parse_authn_request(request.session['SAMLRequest'],
                                           BINDING_HTTP_POST)
    except Exception as excp:
        return HttpResponseBadRequest(excp)
    # TODO this is taken from example, but no idea how this works or whats it does. Check SAML2 specification?
    # Signed request for HTTP-REDIRECT
    if "SigAlg" in request.session and "Signature" in request.session:
        _certs = IDP.metadata.certs(req_info.message.issuer.text, "any",
                                    "signing")
        verified_ok = False
        for cert in _certs:
            # TODO implement
            #if verify_redirect_signature(_info, IDP.sec.sec_backend, cert):
            #    verified_ok = True
            #    break
            pass
        if not verified_ok:
            return HttpResponseBadRequest(
                "Message signature verification failure")

    binding_out, destination = IDP.pick_binding(
        service="assertion_consumer_service",
        entity_id=req_info.message.issuer.text)

    # Gather response arguments
    try:
        resp_args = IDP.response_args(req_info.message)
    except (UnknownPrincipal, UnsupportedBinding) as excp:
        return HttpResponseServerError(excp)

    try:
        sp_config = settings.SAML_IDP_SPCONFIG[resp_args['sp_entity_id']]
    except Exception:
        raise ImproperlyConfigured(
            "No config for SP %s defined in SAML_IDP_SPCONFIG" %
            resp_args['sp_entity_id'])

    # Create user-specified processor or fallback to all-access base processor
    processor_string = sp_config.get('processor', None)
    if processor_string is None:
        processor = BaseProcessor
    else:
        processor_class = import_string(processor_string)
        processor = processor_class()

    # Check if user has access to the service of this SP
    if not processor.has_access(request.user):
        raise PermissionDenied("You do not have access to this resource")

    # Create Identity dict (SP-specific)
    sp_mapping = sp_config.get('attribute_mapping', {'username': '******'})
    identity = processor.create_identity(request.user, sp_mapping)

    # TODO investigate how this works, because I don't get it. Specification?
    req_authn_context = req_info.message.requested_authn_context or PASSWORD
    AUTHN_BROKER = AuthnBroker()
    AUTHN_BROKER.add(authn_context_class_ref(req_authn_context), "")

    # Construct SamlResponse message
    try:
        authn_resp = IDP.create_authn_response(
            identity=identity,
            userid=request.user.username,
            name_id=NameID(format=resp_args['name_id_policy'].format,
                           sp_name_qualifier=destination,
                           text=request.user.username),
            authn=AUTHN_BROKER.get_authn_by_accr(req_authn_context),
            sign_response=IDP.config.getattr("sign_response", "idp") or False,
            sign_assertion=IDP.config.getattr("sign_assertion", "idp")
            or False,
            **resp_args)
    except Exception as excp:
        return HttpResponseServerError(excp)

    # Return as html with self-submitting form.
    http_args = IDP.apply_binding(binding=binding_out,
                                  msg_str="%s" % authn_resp,
                                  destination=destination,
                                  relay_state=request.session['RelayState'],
                                  response=True)

    logger.debug('http args are: %s' % http_args)

    if processor.enable_multifactor(request.user):
        # Store http_args in session for after multi factor is complete
        request.session['saml_data'] = http_args['data']
        logger.debug("Redirecting to process_multi_factor")
        return HttpResponseRedirect(reverse('saml_multi_factor'))
    else:
        logger.debug("Performing SAML redirect")
        return HttpResponse(http_args['data'])
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)
from django.conf import settings
from djangosaml2idp.utils import repr_saml
from saml2.attribute_converter import ac_factory
from saml2.config import IdPConfig
from saml2.mdstore import MetadataStore
from saml2.metadata import entity_descriptor

try:
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
except:
    BASE_DIR = os.getcwd()
    print('BASE_DIR is', BASE_DIR)
conf = IdPConfig()

# conf.load_file("idp_conf_mdb")
conf.load(copy.deepcopy(settings.SAML_IDP_CONFIG))

for i in conf.__dict__.items():
    print(i)

# generate metadata
idp_metadata = entity_descriptor(conf)
# print metadata
print(repr_saml(idp_metadata.__str__()))

# load sp metadata from FILE
attr_conv = ''  # void

mds = MetadataStore('', conf, disable_ssl_certificate_validation=True)
# Import metadata from local file.
sp1_fpath = (os.path.join(