How to use djangosaml2 - 10 common examples

To help you get started, we’ve selected a few djangosaml2 examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github knaperek / djangosaml2 / tests / testprofiles / tests.py View on Github external
)

    def test_get_or_create_user_create(self):
        with self.assertLogs('djangosaml2', level='DEBUG') as logs:
            with override_settings(SAML_USER_MODEL='testprofiles.TestUser'):
                user, created = self.backend.get_or_create_user(self.backend._user_lookup_attribute, 'paul', True, None, None, None, None)

        self.assertTrue(isinstance(user, TestUser))
        self.assertTrue(created)
        self.assertIn(
            "DEBUG:djangosaml2:New user created: {}".format(user),
            logs.output,
        )


class CustomizedBackend(Saml2Backend):
    """ Override the available methods with some customized implementation to test customization
    """
    def is_authorized(self, attributes, attribute_mapping):
        ''' Allow only staff users from the IDP '''
        return attributes.get('is_staff', (None, ))[0] == True
    
    def clean_attributes(self, attributes: dict) -> dict:
        ''' Keep only age attribute '''
        return {
            'age': attributes.get('age', (None, )),
            'is_staff': attributes.get('is_staff', (None, )),
            'uid': attributes.get('uid', (None, )),
        }

    def clean_user_main_attribute(self, main_attribute):
        ''' Replace all spaces an dashes by underscores '''
github knaperek / djangosaml2 / tests / testprofiles / tests.py View on Github external
def test_set_attribute(self):
        u = TestUser()
        self.assertFalse(hasattr(u, 'custom_attribute'))

        # Set attribute initially
        changed = set_attribute(u, 'custom_attribute', 'value')
        self.assertTrue(changed)
        self.assertEqual(u.custom_attribute, 'value')

        # 'Update' to the same value again
        changed_same = set_attribute(u, 'custom_attribute', 'value')
        self.assertFalse(changed_same)
        self.assertEqual(u.custom_attribute, 'value')

        # Update to a different value
        changed_different = set_attribute(u, 'custom_attribute', 'new_value')
        self.assertTrue(changed_different)
        self.assertEqual(u.custom_attribute, 'new_value')
github knaperek / djangosaml2 / tests / testprofiles / tests.py View on Github external
def test_set_attribute(self):
        u = TestUser()
        self.assertFalse(hasattr(u, 'custom_attribute'))

        # Set attribute initially
        changed = set_attribute(u, 'custom_attribute', 'value')
        self.assertTrue(changed)
        self.assertEqual(u.custom_attribute, 'value')

        # 'Update' to the same value again
        changed_same = set_attribute(u, 'custom_attribute', 'value')
        self.assertFalse(changed_same)
        self.assertEqual(u.custom_attribute, 'value')

        # Update to a different value
        changed_different = set_attribute(u, 'custom_attribute', 'new_value')
        self.assertTrue(changed_different)
        self.assertEqual(u.custom_attribute, 'new_value')
github knaperek / djangosaml2 / tests / testprofiles / tests.py View on Github external
def test_set_attribute(self):
        u = TestUser()
        self.assertFalse(hasattr(u, 'custom_attribute'))

        # Set attribute initially
        changed = set_attribute(u, 'custom_attribute', 'value')
        self.assertTrue(changed)
        self.assertEqual(u.custom_attribute, 'value')

        # 'Update' to the same value again
        changed_same = set_attribute(u, 'custom_attribute', 'value')
        self.assertFalse(changed_same)
        self.assertEqual(u.custom_attribute, 'value')

        # Update to a different value
        changed_different = set_attribute(u, 'custom_attribute', 'new_value')
        self.assertTrue(changed_different)
        self.assertEqual(u.custom_attribute, 'new_value')
github knaperek / djangosaml2 / djangosaml2 / views.py View on Github external
def do_logout_service(request, data, binding, config_loader_path=None, next_page=None,
                   logout_error_template='djangosaml2/logout_error.html'):
    """SAML Logout Response endpoint

    The IdP will send the logout response to this view,
    which will process it with pysaml2 help and log the user
    out.
    Note that the IdP can request a logout even when
    we didn't initiate the process as a single logout
    request started by another SP.
    """
    logger.debug('Logout service started')
    conf = get_config(config_loader_path, request)

    state = StateCache(request.session)
    client = Saml2Client(conf, state_cache=state,
                         identity_cache=IdentityCache(request.session))

    if 'SAMLResponse' in data:  # we started the logout
        logger.debug('Receiving a logout response from the IdP')
        response = client.parse_logout_request_response(data['SAMLResponse'], binding)
        state.sync()
        return finish_logout(request, response, next_page=next_page)

    elif 'SAMLRequest' in data:  # logout started by the IdP
        logger.debug('Receiving a logout request from the IdP')
        subject_id = _get_subject_id(request.session)
        if subject_id is None:
            logger.warning(
github cloudera / hue / desktop / core / ext-py / djangosaml2-0.16.11 / djangosaml2 / views.py View on Github external
def do_logout_service(request, data, binding, config_loader_path=None, next_page=None,
                   logout_error_template='djangosaml2/logout_error.html'):
    """SAML Logout Response endpoint

    The IdP will send the logout response to this view,
    which will process it with pysaml2 help and log the user
    out.
    Note that the IdP can request a logout even when
    we didn't initiate the process as a single logout
    request started by another SP.
    """
    logger.debug('Logout service started')
    conf = get_config(config_loader_path, request)

    state = StateCache(request.session)
    client = Saml2Client(conf, state_cache=state,
                         identity_cache=IdentityCache(request.session))

    if 'SAMLResponse' in data:  # we started the logout
        logger.debug('Receiving a logout response from the IdP')
        response = client.parse_logout_request_response(data['SAMLResponse'], binding)
        state.sync()
        return finish_logout(request, response, next_page=next_page)

    elif 'SAMLRequest' in data:  # logout started by the IdP
        logger.debug('Receiving a logout request from the IdP')
        subject_id = _get_subject_id(request.session)
        if subject_id is None:
            logger.warning(
github cloudera / hue / desktop / core / ext-py / djangosaml2-0.16.11 / djangosaml2 / views.py View on Github external
def echo_attributes(request,
                    config_loader_path=None,
                    template='djangosaml2/echo_attributes.html'):
    """Example view that echo the SAML attributes of an user"""
    state = StateCache(request.session)
    conf = get_config(config_loader_path, request)

    client = Saml2Client(conf, state_cache=state,
                         identity_cache=IdentityCache(request.session))
    subject_id = _get_subject_id(request.session)
    try:
        identity = client.users.get_identity(subject_id,
                                             check_not_on_or_after=False)
    except AttributeError:
        return HttpResponse("No active SAML identity found. Are you sure you have logged in via SAML?")

    return render(request, template, {'attributes': identity[0]}, using='django')
github opennode / waldur-mastermind / src / waldur_auth_saml2 / views.py View on Github external
def post(self, request):
        if not self.request.user.is_anonymous:
            error_message = _('This endpoint is for anonymous users only.')
            return JsonResponse({'error_message': error_message}, status=400)

        serializer = self.serializer_class(data=request.data)
        serializer.is_valid(raise_exception=True)
        idp = serializer.validated_data.get('idp')

        conf = get_config(request=request)

        # ensure our selected binding is supported by the IDP
        supported_bindings = utils.get_idp_sso_supported_bindings(idp, config=conf)
        default_binding = settings.WALDUR_AUTH_SAML2.get('DEFAULT_BINDING')

        if default_binding in supported_bindings:
            binding = default_binding
        elif BINDING_HTTP_POST in supported_bindings:
            binding = BINDING_HTTP_POST
        elif BINDING_HTTP_REDIRECT in supported_bindings:
            binding = BINDING_HTTP_REDIRECT
        else:
            error_message = _('Identity provider does not support available bindings.')
            return JsonResponse({'error_message': error_message}, status=400)

        client = Saml2Client(conf)
github knaperek / djangosaml2 / djangosaml2 / views.py View on Github external
def post(self,
             request,
             config_loader_path=None,
             attribute_mapping=None,
             create_unknown_user=None):
        """
        SAML Authorization Response endpoint
        """
        attribute_mapping = attribute_mapping or get_custom_setting('SAML_ATTRIBUTE_MAPPING', {'uid': ('username', )})
        create_unknown_user = create_unknown_user or get_custom_setting('SAML_CREATE_UNKNOWN_USER', True)
        conf = get_config(config_loader_path, request)
        try:
            xmlstr = request.POST['SAMLResponse']
        except KeyError:
            logger.warning('Missing "SAMLResponse" parameter in POST data.')
            raise SuspiciousOperation

        client = Saml2Client(conf, identity_cache=IdentityCache(self.request.session))

        oq_cache = OutstandingQueriesCache(self.request.session)
        outstanding_queries = oq_cache.outstanding_queries()

        try:
            response = client.parse_authn_request_response(xmlstr, BINDING_HTTP_POST, outstanding_queries)
        except (StatusError, ToEarly) as e:
            logger.exception("Error processing SAML Assertion.")
            return fail_acs_response(request, exception=e)
github opennode / waldur-mastermind / src / waldur_auth_saml2 / views.py View on Github external
def logout(self, request, data, binding):
        conf = get_config(request=request)

        state = StateCache(request.session)
        client = Saml2Client(
            conf, state_cache=state, identity_cache=IdentityCache(request.session)
        )

        if 'SAMLResponse' in data:
            # Logout started by us
            client.parse_logout_request_response(data['SAMLResponse'], binding)
            http_response = logout_completed()
        else:
            # Logout started by IdP
            subject_id = _get_subject_id(request.session)
            if subject_id is None:
                http_response = logout_completed()
            else: