Python onelogin.saml2.auth.OneLogin_Saml2_Auth() Examples

The following are 30 code examples of onelogin.saml2.auth.OneLogin_Saml2_Auth(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module onelogin.saml2.auth , or try the search function .
Example #1
Source File: authentication.py    From rucio with Apache License 2.0 7 votes vote down vote up
def POST(self):

        if not EXTRA_MODULES['onelogin']:
            header('X-Rucio-Auth-Token', None)
            return "SAML not configured on the server side."

        SAML_PATH = config_get('saml', 'config_path')
        request = ctx.env
        data = dict(param_input())
        req = prepare_webpy_request(request, data)
        auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

        auth.process_response()
        errors = auth.get_errors()
        if not errors:
            if auth.is_authenticated():
                setcookie('saml-nameid', value=auth.get_nameid(), path='/') 
Example #2
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLoginSigned(self):
        """
        Tests the login method of the OneLogin_Saml2_Auth class
        Case Login signed. An AuthnRequest signed is built an redirect executed
        """
        settings_info = self.loadSettingsJSON()
        settings_info['security']['authnRequestsSigned'] = True
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        return_to = u'http://example.com/returnto'

        target_url = auth.login(return_to)
        parsed_query = parse_qs(urlparse(target_url)[4])
        sso_url = settings_info['idp']['singleSignOnService']['url']
        self.assertIn(sso_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        self.assertIn('RelayState', parsed_query)
        self.assertIn('SigAlg', parsed_query)
        self.assertIn('Signature', parsed_query)
        self.assertIn(return_to, parsed_query['RelayState'])
        self.assertIn(OneLogin_Saml2_Constants.RSA_SHA1, parsed_query['SigAlg']) 
Example #3
Source File: userauth.py    From confidant with Apache License 2.0 6 votes vote down vote up
def _saml_auth(self, req_dict=None):
        """
        Instantiate a OneLogin_Saml2_Auth object from the current request data
        (or from req_dict, if given).

        :param req_dict: A dict containing request information, optional.
        :type req_dict: dict

        :returns: a SAML Auth object
        :rtype: onelogin.saml2.auth.OneLogin_Saml2_Auth
        """
        if req_dict is None:
            req_dict = self._saml_req_dict_from_request()

        auth = OneLogin_Saml2_Auth(req_dict, self.saml_config)
        return auth 
Example #4
Source File: userauth.py    From confidant with Apache License 2.0 6 votes vote down vote up
def _render_saml_errors_json(self, auth):
        """
        Log and handle SAML errors, returning as json.
        Return a Response object appropriate to return in a route handler.

        :param auth: The python-saml Auth class.
        :type auth: onelogin.saml2.auth.OneLogin_Saml2_Auth

        :returns: a flask response
        :rtype: flask.Response
        """

        logger.warning('Handling SAML errors')
        data = {
            'message': 'SAML request failed',
            'errors': auth.get_errors(),
            'reason': auth.get_last_error_reason(),
            'request_id': auth.get_last_request_id(),
        }
        logger.warning('Errors: {0}'.format(data))

        resp = jsonify(**data)
        resp.status_code = 500
        return resp 
Example #5
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testGetLastSAMLResponse(self):
        settings = self.loadSettingsJSON()
        message = self.file_contents(join(self.data_path, 'responses', 'signed_message_response.xml.base64'))
        message_wrapper = {'post_data': {'SAMLResponse': message}}
        auth = OneLogin_Saml2_Auth(message_wrapper, old_settings=settings)
        auth.process_response()
        expected_message = self.file_contents(join(self.data_path, 'responses', 'pretty_signed_message_response.xml'))
        self.assertEqual(auth.get_last_response_xml(True), expected_message)

        # with encrypted assertion
        message = self.file_contents(join(self.data_path, 'responses', 'valid_encrypted_assertion.xml.base64'))
        message_wrapper = {'post_data': {'SAMLResponse': message}}
        auth = OneLogin_Saml2_Auth(message_wrapper, old_settings=settings)
        auth.process_response()
        decrypted_response = self.file_contents(join(self.data_path, 'responses', 'decrypted_valid_encrypted_assertion.xml'))
        self.assertEqual(auth.get_last_response_xml(False), decrypted_response)
        pretty_decrypted_response = self.file_contents(join(self.data_path, 'responses', 'pretty_decrypted_valid_encrypted_assertion.xml'))
        self.assertEqual(auth.get_last_response_xml(True), pretty_decrypted_response) 
Example #6
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testGetLastAuthnRequest(self):
        settings = self.loadSettingsJSON()
        auth = OneLogin_Saml2_Auth({'http_host': 'localhost', 'script_name': 'thing'}, old_settings=settings)
        auth.login()
        expectedFragment = (
            '  Destination="http://idp.example.com/SSOService.php"\n'
            '  ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST"\n'
            '  AssertionConsumerServiceURL="http://stuff.com/endpoints/endpoints/acs.php">\n'
            '    <saml:Issuer>http://stuff.com/endpoints/metadata.php</saml:Issuer>\n'
            '    <samlp:NameIDPolicy\n'
            '        Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified"\n'
            '        AllowCreate="true" />\n'
            '    <samlp:RequestedAuthnContext Comparison="exact">\n'
            '        <saml:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport</saml:AuthnContextClassRef>\n'
            '    </samlp:RequestedAuthnContext>\n'
        )
        self.assertIn(expectedFragment, auth.get_last_request_xml()) 
Example #7
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testBuildRequestSignature(self):
        """
        Tests the build_request_signature method of the OneLogin_Saml2_Auth
        """
        settings = self.loadSettingsJSON()
        message = self.file_contents(join(self.data_path, 'logout_requests', 'logout_request_deflated.xml.base64'))
        relay_state = 'http://relaystate.com'
        parameters = {"SAMLRequest": message, "RelayState": relay_state}
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings)

        auth.add_request_signature(parameters)
        valid_signature = 'Pb1EXAX5TyipSJ1SndEKZstLQTsT+1D00IZAhEepBM+OkAZQSToivu3njgJu47HZiZAqgXZFgloBuuWE/+GdcSsRYEMkEkiSDWTpUr25zKYLJDSg6GNo6iAHsKSuFt46Z54Xe/keYxYP03Hdy97EwuuSjBzzgRc5tmpV+KC7+a0='
        self.assertEqual(valid_signature, parameters["Signature"])

        settings['sp']['privateKey'] = ''
        settings['custom_base_path'] = u'invalid/path/'
        auth2 = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings)
        with self.assertRaisesRegex(OneLogin_Saml2_Error, "Trying to sign the SAMLRequest but can't load the SP private key"):
            auth2.add_request_signature(parameters) 
Example #8
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testGetLastLogoutRequest(self):
        settings = self.loadSettingsJSON()
        auth = OneLogin_Saml2_Auth({'http_host': 'localhost', 'script_name': 'thing'}, old_settings=settings)
        auth.logout()
        expectedFragment = (
            '  Destination="http://idp.example.com/SingleLogoutService.php">\n'
            '    <saml:Issuer>http://stuff.com/endpoints/metadata.php</saml:Issuer>\n'
            '    <saml:NameID Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity">http://idp.example.com/</saml:NameID>\n'
            '    \n</samlp:LogoutRequest>'
        )
        self.assertIn(expectedFragment, auth.get_last_request_xml())

        request = self.file_contents(join(self.data_path, 'logout_requests', 'logout_request.xml'))
        message = OneLogin_Saml2_Utils.deflate_and_base64_encode(request)
        message_wrapper = {'get_data': {'SAMLRequest': message}}
        auth = OneLogin_Saml2_Auth(message_wrapper, old_settings=settings)
        auth.process_slo()
        self.assertEqual(request, auth.get_last_request_xml()) 
Example #9
Source File: __init__.py    From cloud-inquisitor with Apache License 2.0 6 votes vote down vote up
def _init_saml_request(self):
        tmpl = get_template('saml_settings.json')
        config = tmpl.render(
            strict=str(self.dbconfig.get('strict', self.ns, True)).lower(),
            debug=str(self.dbconfig.get('debug', self.ns, False)).lower(),
            sp_entity_id=self.dbconfig.get('sp_entity_id', self.ns),
            sp_acs=self.dbconfig.get('sp_acs', self.ns),
            sp_sls=self.dbconfig.get('sp_sls', self.ns),
            idp_entity_id=self.dbconfig.get('idp_entity_id', self.ns),
            idp_ssos=self.dbconfig.get('idp_ssos', self.ns),
            idp_sls=self.dbconfig.get('idp_sls', self.ns),
            idp_x509cert=self.dbconfig.get('idp_x509cert', self.ns)
        )

        auth = OneLogin_Saml2_Auth(self.req, json.loads(config))
        auth.set_strict(False)
        return auth 
Example #10
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testGetSessionExpiration(self):
        """
        Tests the get_session_expiration method of the OneLogin_Saml2_Auth class
        """
        settings_info = self.loadSettingsJSON()
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        self.assertIsNone(auth.get_session_expiration())

        request_data = self.get_request()
        message = self.file_contents(join(self.data_path, 'responses', 'valid_response.xml.base64'))
        del request_data['get_data']
        request_data['post_data'] = {
            'SAMLResponse': message
        }
        auth2 = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())
        self.assertIsNone(auth2.get_session_expiration())

        auth2.process_response()
        self.assertEqual(2655106621, auth2.get_session_expiration()) 
Example #11
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testIsAuthenticated(self):
        """
        Tests the is_authenticated method of the OneLogin_Saml2_Auth
        """
        request_data = self.get_request()
        del request_data['get_data']
        message = self.file_contents(join(self.data_path, 'responses', 'response1.xml.base64'))
        request_data['post_data'] = {
            'SAMLResponse': message
        }
        auth = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())
        auth.process_response()
        self.assertFalse(auth.is_authenticated())

        message = self.file_contents(join(self.data_path, 'responses', 'valid_response.xml.base64'))
        request_data['post_data'] = {
            'SAMLResponse': message
        }
        auth = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())
        auth.process_response()
        self.assertTrue(auth.is_authenticated()) 
Example #12
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testProcessResponseInvalid(self):
        """
        Tests the process_response method of the OneLogin_Saml2_Auth class
        Case Invalid Response, After processing the response the user
        is not authenticated, attributes are notreturned, no nameID and
        the error array is not empty, contains 'invalid_response
        """
        request_data = self.get_request()
        message = self.file_contents(join(self.data_path, 'responses', 'response1.xml.base64'))
        del request_data['get_data']
        request_data['post_data'] = {
            'SAMLResponse': message
        }
        auth = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())
        auth.process_response()

        self.assertFalse(auth.is_authenticated())
        self.assertEqual(len(auth.get_attributes()), 0)
        self.assertEqual(auth.get_nameid(), None)
        self.assertEqual(auth.get_attribute('uid'), None)
        self.assertEqual(auth.get_errors(), ['invalid_response']) 
Example #13
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLogoutNameIDandSessionIndex(self):
        """
        Tests the logout method of the OneLogin_Saml2_Auth class
        Case nameID and sessionIndex as parameters.
        """
        settings_info = self.loadSettingsJSON()
        request_data = self.get_request()
        auth = OneLogin_Saml2_Auth(request_data, old_settings=settings_info)

        name_id = 'name_id_example'
        session_index = 'session_index_example'
        target_url = auth.logout(name_id=name_id, session_index=session_index)
        parsed_query = parse_qs(urlparse(target_url)[4])
        slo_url = settings_info['idp']['singleLogoutService']['url']
        self.assertIn(slo_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)

        logout_request = OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query['SAMLRequest'][0])
        name_id_from_request = OneLogin_Saml2_Logout_Request.get_nameid(logout_request)
        sessions_index_in_request = OneLogin_Saml2_Logout_Request.get_session_indexes(logout_request)
        self.assertIn(session_index, sessions_index_in_request)
        self.assertEqual(name_id, name_id_from_request) 
Example #14
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLogoutSigned(self):
        """
        Tests the logout method of the OneLogin_Saml2_Auth class
        Case Logout signed. A logout Request signed in
        the assertion is built and redirect executed
        """
        settings_info = self.loadSettingsJSON()
        settings_info['security']['logoutRequestSigned'] = True
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        return_to = u'http://example.com/returnto'

        target_url = auth.logout(return_to)
        parsed_query = parse_qs(urlparse(target_url)[4])
        slo_url = settings_info['idp']['singleLogoutService']['url']
        self.assertIn(slo_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        self.assertIn('RelayState', parsed_query)
        self.assertIn('SigAlg', parsed_query)
        self.assertIn('Signature', parsed_query)
        self.assertIn(return_to, parsed_query['RelayState'])
        self.assertIn(OneLogin_Saml2_Constants.RSA_SHA1, parsed_query['SigAlg']) 
Example #15
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testProcessSLOResponseInvalid(self):
        """
        Tests the process_slo method of the OneLogin_Saml2_Auth class
        Case Invalid Logout Response
        """
        request_data = self.get_request()
        message = self.file_contents(join(self.data_path, 'logout_responses', 'logout_response_deflated.xml.base64'))
        request_data['get_data']['SAMLResponse'] = message
        auth = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())

        auth.process_slo(True)
        self.assertEqual(len(auth.get_errors()), 0)

        auth.set_strict(True)
        auth.process_slo(True)
        # The Destination fails
        self.assertEqual(auth.get_errors(), ['invalid_logout_response'])

        auth.set_strict(False)
        auth.process_slo(True)
        self.assertEqual(len(auth.get_errors()), 0) 
Example #16
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testSetStrict(self):
        """
        Tests the set_strict method of the OneLogin_Saml2_Auth
        """
        settings_info = self.loadSettingsJSON()
        settings_info['strict'] = False
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)

        settings = auth.get_settings()
        self.assertFalse(settings.is_strict())

        auth.set_strict(True)
        settings = auth.get_settings()
        self.assertTrue(settings.is_strict())

        auth.set_strict(False)
        settings = auth.get_settings()
        self.assertFalse(settings.is_strict())

        self.assertRaises(AssertionError, auth.set_strict, '42') 
Example #17
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testProcessSLOResponseNoSucess(self):
        """
        Tests the process_slo method of the OneLogin_Saml2_Auth class
        Case Logout Response not sucess
        """
        request_data = self.get_request()
        message = self.file_contents(join(self.data_path, 'logout_responses', 'invalids', 'status_code_responder.xml.base64'))
        # In order to avoid the destination problem
        plain_message = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(message))
        current_url = OneLogin_Saml2_Utils.get_self_url_no_query(request_data)
        plain_message = plain_message.replace('http://stuff.com/endpoints/endpoints/sls.php', current_url)
        message = OneLogin_Saml2_Utils.deflate_and_base64_encode(plain_message)
        request_data['get_data']['SAMLResponse'] = message
        auth = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())

        auth.set_strict(True)
        auth.process_slo(True)
        self.assertEqual(auth.get_errors(), ['logout_not_success']) 
Example #18
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLogoutWithRelayState(self):
        """
        Tests the logout method of the OneLogin_Saml2_Auth class
        Case Logout with relayState. A logout Request with a the RelayState in
        the assertion is built and redirect executed
        """
        settings_info = self.loadSettingsJSON()
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        relay_state = 'http://sp.example.com'

        target_url = auth.logout(relay_state)
        parsed_query = parse_qs(urlparse(target_url)[4])
        slo_url = settings_info['idp']['singleLogoutService']['url']
        self.assertIn(slo_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        self.assertIn('RelayState', parsed_query)
        self.assertIn(relay_state, parsed_query['RelayState']) 
Example #19
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLogout(self):
        """
        Tests the logout method of the OneLogin_Saml2_Auth class
        Case Logout with no parameters. A logout Request is built and redirect
        executed
        """
        settings_info = self.loadSettingsJSON()
        request_data = self.get_request()
        auth = OneLogin_Saml2_Auth(request_data, old_settings=settings_info)

        target_url = auth.logout()
        parsed_query = parse_qs(urlparse(target_url)[4])
        slo_url = settings_info['idp']['singleLogoutService']['url']
        self.assertIn(slo_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        self.assertIn('RelayState', parsed_query)
        hostname = OneLogin_Saml2_Utils.get_self_host(request_data)
        self.assertIn(u'http://%s/index.html' % hostname, parsed_query['RelayState']) 
Example #20
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testProcessSLORequestNotOnOrAfterFailed(self):
        """
        Tests the process_slo method of the OneLogin_Saml2_Auth class
        Case Logout Request NotOnOrAfter failed
        """
        request_data = self.get_request()
        message = self.file_contents(join(self.data_path, 'logout_requests', 'invalids', 'not_after_failed.xml.base64'))
        # In order to avoid the destination problem
        plain_message = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(message))
        current_url = OneLogin_Saml2_Utils.get_self_url_no_query(request_data)
        plain_message = plain_message.replace('http://stuff.com/endpoints/endpoints/sls.php', current_url)
        message = OneLogin_Saml2_Utils.deflate_and_base64_encode(plain_message)
        request_data['get_data']['SAMLRequest'] = message
        auth = OneLogin_Saml2_Auth(request_data, old_settings=self.loadSettingsJSON())

        auth.set_strict(True)
        auth.process_slo(True)
        self.assertEqual(auth.get_errors(), ['invalid_logout_request']) 
Example #21
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLogin(self):
        """
        Tests the login method of the OneLogin_Saml2_Auth class
        Case Login with no parameters. An AuthnRequest is built an redirect executed
        """
        settings_info = self.loadSettingsJSON()
        request_data = self.get_request()
        auth = OneLogin_Saml2_Auth(request_data, old_settings=settings_info)

        target_url = auth.login()
        parsed_query = parse_qs(urlparse(target_url)[4])
        sso_url = settings_info['idp']['singleSignOnService']['url']
        self.assertIn(sso_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        self.assertIn('RelayState', parsed_query)
        hostname = OneLogin_Saml2_Utils.get_self_host(request_data)
        self.assertIn(u'http://%s/index.html' % hostname, parsed_query['RelayState']) 
Example #22
Source File: auth_test.py    From python3-saml with MIT License 6 votes vote down vote up
def testLoginWithRelayState(self):
        """
        Tests the login method of the OneLogin_Saml2_Auth class
        Case Login with relayState. An AuthnRequest is built with a the
        RelayState in the assertion is built and redirect executed
        """
        settings_info = self.loadSettingsJSON()
        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        relay_state = 'http://sp.example.com'

        target_url = auth.login(relay_state)
        parsed_query = parse_qs(urlparse(target_url)[4])
        sso_url = settings_info['idp']['singleSignOnService']['url']
        self.assertIn(sso_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        self.assertIn('RelayState', parsed_query)
        self.assertIn(relay_state, parsed_query['RelayState']) 
Example #23
Source File: authentication.py    From rucio with Apache License 2.0 6 votes vote down vote up
def POST(self):

        if not EXTRA_MODULES['onelogin']:
            header('X-Rucio-Auth-Token', None)
            return "SAML not configured on the server side."

        SAML_PATH = config_get('saml', 'config_path')
        request = ctx.env
        data = dict(param_input())
        req = prepare_webpy_request(request, data)
        auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)

        auth.process_response()
        errors = auth.get_errors()
        if not errors:
            if auth.is_authenticated():
                setcookie('saml-nameid', value=auth.get_nameid(), path='/') 
Example #24
Source File: auth_test.py    From python3-saml with MIT License 5 votes vote down vote up
def testGetIdFromLogoutResponse(self):
        """
        Tests the get_last_message_id of the OneLogin_Saml2_Auth class
        Case Valid Logout response
        """
        settings = self.loadSettingsJSON()
        response = self.file_contents(join(self.data_path, 'logout_responses', 'logout_response.xml'))
        message = OneLogin_Saml2_Utils.deflate_and_base64_encode(response)
        message_wrapper = {'get_data': {'SAMLResponse': message}}
        auth = OneLogin_Saml2_Auth(message_wrapper, old_settings=settings)
        auth.process_slo()
        self.assertIn(auth.get_last_message_id(), '_f9ee61bd9dbf63606faa9ae3b10548d5b3656fb859') 
Example #25
Source File: views.py    From python3-saml with MIT License 5 votes vote down vote up
def init_saml_auth(req):
    auth = OneLogin_Saml2_Auth(req, custom_base_path=SAML_PATH)
    return auth 
Example #26
Source File: auth_test.py    From python3-saml with MIT License 5 votes vote down vote up
def testGetNameIdSPNameQualifier2(self):
        """
        Tests the get_nameid_spnq method of the OneLogin_Saml2_Auth
        """
        settings = self.loadSettingsJSON()
        message = self.file_contents(join(self.data_path, 'responses', 'valid_response.xml.base64'))
        request_data = self.get_request()
        request_data['post_data'] = {
            'SAMLResponse': message
        }
        auth = OneLogin_Saml2_Auth(request_data, old_settings=settings)
        self.assertIsNone(auth.get_nameid_spnq())
        auth.process_response()
        self.assertTrue(auth.is_authenticated())
        self.assertEqual("http://stuff.com/endpoints/metadata.php", auth.get_nameid_spnq()) 
Example #27
Source File: auth_test.py    From python3-saml with MIT License 5 votes vote down vote up
def testLoginForceAuthN(self):
        """
        Tests the login method of the OneLogin_Saml2_Auth class
        Case AuthN Request is built with ForceAuthn and redirect executed
        """
        settings_info = self.loadSettingsJSON()
        return_to = u'http://example.com/returnto'

        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        target_url = auth.login(return_to)
        parsed_query = parse_qs(urlparse(target_url)[4])
        sso_url = settings_info['idp']['singleSignOnService']['url']
        self.assertIn(sso_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        request = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query['SAMLRequest'][0]))
        self.assertNotIn('ForceAuthn="true"', request)

        auth_2 = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        target_url_2 = auth_2.login(return_to, False, False)
        parsed_query_2 = parse_qs(urlparse(target_url_2)[4])
        self.assertIn(sso_url, target_url_2)
        self.assertIn('SAMLRequest', parsed_query_2)
        request_2 = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query_2['SAMLRequest'][0]))
        self.assertNotIn('ForceAuthn="true"', request_2)

        auth_3 = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        target_url_3 = auth_3.login(return_to, True, False)
        parsed_query_3 = parse_qs(urlparse(target_url_3)[4])
        self.assertIn(sso_url, target_url_3)
        self.assertIn('SAMLRequest', parsed_query_3)
        request_3 = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query_3['SAMLRequest'][0]))
        self.assertIn('ForceAuthn="true"', request_3) 
Example #28
Source File: auth_test.py    From python3-saml with MIT License 5 votes vote down vote up
def testLoginWithSubject(self):
        """
        Tests the login method of the OneLogin_Saml2_Auth class
        Case AuthN Request is built with and without Subject
        """
        settings_info = self.loadSettingsJSON()
        return_to = u'http://example.com/returnto'
        sso_url = settings_info['idp']['singleSignOnService']['url']

        auth = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        target_url = auth.login(return_to)
        parsed_query = parse_qs(urlparse(target_url)[4])
        self.assertIn(sso_url, target_url)
        self.assertIn('SAMLRequest', parsed_query)
        request = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query['SAMLRequest'][0]))
        self.assertNotIn('<saml:Subject>', request)
        self.assertNotIn('<saml:NameID', request)
        self.assertNotIn('<saml:saml:SubjectConfirmation', request)

        auth_2 = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        target_url_2 = auth_2.login(return_to, name_id_value_req='testuser@example.com')
        parsed_query_2 = parse_qs(urlparse(target_url_2)[4])
        self.assertIn(sso_url, target_url_2)
        self.assertIn('SAMLRequest', parsed_query_2)
        request_2 = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query_2['SAMLRequest'][0]))
        self.assertIn('<saml:Subject>', request_2)
        self.assertIn('Format="urn:oasis:names:tc:SAML:1.1:nameid-format:unspecified">testuser@example.com</saml:NameID>', request_2)
        self.assertIn('<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">', request_2)

        settings_info['sp']['NameIDFormat'] = 'urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress'
        auth_3 = OneLogin_Saml2_Auth(self.get_request(), old_settings=settings_info)
        target_url_3 = auth_3.login(return_to, name_id_value_req='testuser@example.com')
        parsed_query_3 = parse_qs(urlparse(target_url_3)[4])
        self.assertIn(sso_url, target_url_3)
        self.assertIn('SAMLRequest', parsed_query_3)
        request_3 = compat.to_string(OneLogin_Saml2_Utils.decode_base64_and_inflate(parsed_query_3['SAMLRequest'][0]))
        self.assertIn('<saml:Subject>', request_3)
        self.assertIn('Format="urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress">testuser@example.com</saml:NameID>', request_3)
        self.assertIn('<saml:SubjectConfirmation Method="urn:oasis:names:tc:SAML:2.0:cm:bearer">', request_3) 
Example #29
Source File: views.py    From python3-saml with MIT License 5 votes vote down vote up
def init_saml_auth(req):
    auth = OneLogin_Saml2_Auth(req, custom_base_path=Settings.SAML_PATH)
    return auth 
Example #30
Source File: auth_test.py    From python3-saml with MIT License 5 votes vote down vote up
def testGetIdFromLogoutRequest(self):
        """
        Tests the get_last_message_id of the OneLogin_Saml2_Auth class
        Case Valid Logout request
        """
        settings = self.loadSettingsJSON()
        request = self.file_contents(join(self.data_path, 'logout_requests', 'logout_request.xml'))
        message = OneLogin_Saml2_Utils.deflate_and_base64_encode(request)
        message_wrapper = {'get_data': {'SAMLRequest': message}}
        auth = OneLogin_Saml2_Auth(message_wrapper, old_settings=settings)
        auth.process_slo()
        self.assertIn(auth.get_last_message_id(), 'ONELOGIN_21584ccdfaca36a145ae990442dcd96bfe60151e')