Coder Social home page Coder Social logo

fangli / django-saml2-auth Goto Github PK

View Code? Open in Web Editor NEW
499.0 15.0 222.0 74 KB

Django SAML2 Authentication Made Easy. Easily integrate with SAML2 SSO identity providers like Okta

License: Other

Python 94.66% HTML 5.34%
django saml2 authentication

django-saml2-auth's Introduction

Django SAML2 Authentication Made Easy

Author: Fang Li
Version: Use 1.1.4 for Django <=1.9, 2.x.x for Django >= 1.9, Latest supported django version is 2.1

This project aims to provide a dead simple way to integrate SAML2 Authentication into your Django powered app. Try it now, and get rid of the complicated configuration of SAML.

Any SAML2 based SSO(Single-Sign-On) identity provider with dynamic metadata configuration is supported by this Django plugin, for example Okta.

When you raise an issue or PR

Please note this library is used in tons of production environment and plays a mission-critical role in most deployment. It supports almost all django versions since 1.1.4. We need to be extremely careful when merging any changes.

So most non-security features or enhancements will be REJECTED. please fork your own version or just copy the code as you need. I want to make this module dead simple and reliable. That means when you have it properly configured, you are not likely to get into any troubles in the future.

The supports to new versions of django are still welcome and I'll make best effort to make it latest django compatible.

Donate

We accept your donations by clicking the awesome star instead of any physical transfer.

Dependencies

This plugin is compatible with Django 1.6/1.7/1.8/1.9/1.10. The pysaml2 Python module is required.

Install

You can install this plugin via pip:

# pip install django_saml2_auth

or from source:

# git clone https://github.com/fangli/django-saml2-auth
# cd django-saml2-auth
# python setup.py install

xmlsec is also required by pysaml2:

# yum install xmlsec1
// or
# apt-get install xmlsec1
// Mac
# brew install xmlsec1

What does this plugin do?

This plugin takes over Django's login page and redirect the user to a SAML2 SSO authentication service. Once the user is logged in and redirected back, the plugin will check if the user is already in the system. If not, the user will be created using Django's default UserModel, otherwise the user will be redirected to their last visited page.

How to use?

  1. Import the views module in your root urls.py

    import django_saml2_auth.views
  2. Override the default login page in the root urls.py file, by adding these lines BEFORE any urlpatterns:

    # These are the SAML2 related URLs. You can change "^saml2_auth/" regex to
    # any path you want, like "^sso_auth/", "^sso_login/", etc. (required)
    url(r'^saml2_auth/', include('django_saml2_auth.urls')),
    
    # The following line will replace the default user login with SAML2 (optional)
    # If you want to specific the after-login-redirect-URL, use parameter "?next=/the/path/you/want"
    # with this view.
    url(r'^accounts/login/$', django_saml2_auth.views.signin),
    
    # The following line will replace the admin login with SAML2 (optional)
    # If you want to specific the after-login-redirect-URL, use parameter "?next=/the/path/you/want"
    # with this view.
    url(r'^admin/login/$', django_saml2_auth.views.signin),
  3. Add 'django_saml2_auth' to INSTALLED_APPS

    INSTALLED_APPS = [
        '...',
        'django_saml2_auth',
    ]
  4. In settings.py, add the SAML2 related configuration.

    Please note, the only required setting is METADATA_AUTO_CONF_URL. The following block shows all required and optional configuration settings and their default values.

    SAML2_AUTH = {
        # Metadata is required, choose either remote url or local file path
        'METADATA_AUTO_CONF_URL': '[The auto(dynamic) metadata configuration URL of SAML2]',
        'METADATA_LOCAL_FILE_PATH': '[The metadata configuration file path]',
    
        # Optional settings below
        'DEFAULT_NEXT_URL': '/admin',  # Custom target redirect URL after the user get logged in. Default to /admin if not set. This setting will be overwritten if you have parameter ?next= specificed in the login URL.
        'CREATE_USER': 'TRUE', # Create a new Django user when a new user logs in. Defaults to True.
        'NEW_USER_PROFILE': {
            'USER_GROUPS': [],  # The default group name when a new user logs in
            'ACTIVE_STATUS': True,  # The default active status for new users
            'STAFF_STATUS': True,  # The staff status for new users
            'SUPERUSER_STATUS': False,  # The superuser status for new users
        },
        'ATTRIBUTES_MAP': {  # Change Email/UserName/FirstName/LastName to corresponding SAML2 userprofile attributes.
            'email': 'Email',
            'username': 'UserName',
            'first_name': 'FirstName',
            'last_name': 'LastName',
        },
        'TRIGGER': {
            'CREATE_USER': 'path.to.your.new.user.hook.method',
            'BEFORE_LOGIN': 'path.to.your.login.hook.method',
        },
        'ASSERTION_URL': 'https://mysite.com', # Custom URL to validate incoming SAML requests against
        'ENTITY_ID': 'https://mysite.com/saml2_auth/acs/', # Populates the Issuer element in authn request
        'NAME_ID_FORMAT': FormatString, # Sets the Format property of authn NameIDPolicy element
        'USE_JWT': False, # Set this to True if you are running a Single Page Application (SPA) with Django Rest Framework (DRF), and are using JWT authentication to authorize client users
        'FRONTEND_URL': 'https://myfrontendclient.com', # Redirect URL for the client if you are using JWT auth with DRF. See explanation below
    }
  5. In your SAML2 SSO identity provider, set the Single-sign-on URL and Audience URI(SP Entity ID) to http://your-domain/saml2_auth/acs/

Explanation

METADATA_AUTO_CONF_URL Auto SAML2 metadata configuration URL

METADATA_LOCAL_FILE_PATH SAML2 metadata configuration file path

CREATE_USER Determines if a new Django user should be created for new users.

NEW_USER_PROFILE Default settings for newly created users

ATTRIBUTES_MAP Mapping of Django user attributes to SAML2 user attributes

TRIGGER Hooks to trigger additional actions during user login and creation flows. These TRIGGER hooks are strings containing a dotted module name which point to a method to be called. The referenced method should accept a single argument which is a dictionary of attributes and values sent by the identity provider, representing the user's identity.

TRIGGER.CREATE_USER A method to be called upon new user creation. This method will be called before the new user is logged in and after the user's record is created. This method should accept ONE parameter of user dict.

TRIGGER.BEFORE_LOGIN A method to be called when an existing user logs in. This method will be called before the user is logged in and after user attributes are returned by the SAML2 identity provider. This method should accept ONE parameter of user dict.

ASSERTION_URL A URL to validate incoming SAML responses against. By default, django-saml2-auth will validate the SAML response's Service Provider address against the actual HTTP request's host and scheme. If this value is set, it will validate against ASSERTION_URL instead - perfect for when django running behind a reverse proxy.

ENTITY_ID The optional entity ID string to be passed in the 'Issuer' element of authn request, if required by the IDP.

NAME_ID_FORMAT Set to the string 'None', to exclude sending the 'Format' property of the 'NameIDPolicy' element in authn requests. Default value if not specified is 'urn:oasis:names:tc:SAML:2.0:nameid-format:transient'.

USE_JWT Set this to the boolean True if you are using Django Rest Framework with JWT authentication

FRONTEND_URL If USE_JWT is True, you should set the URL of where your frontend is located (will default to DEFAULT_NEXT_URL if you fail to do so). Once the client is authenticated through the SAML/SSO, your client is redirected to the FRONTEND_URL with the user id (uid) and JWT token (token) as query parameters. Example: 'https://myfrontendclient.com/?uid=<user id>&token=<jwt token>' With these params your client can now authenticate will server resources.

Customize

The default permission denied page and user welcome page can be overridden.

To override these pages put a template named 'django_saml2_auth/welcome.html' or 'django_saml2_auth/denied.html' in your project's template folder.

If a 'django_saml2_auth/welcome.html' template exists, that page will be shown to the user upon login instead of the user being redirected to the previous visited page. This welcome page can contain some first-visit notes and welcome words. The Django user object is available within the template as the user template variable.

To enable a logout page, add the following lines to urls.py, before any urlpatterns:

# The following line will replace the default user logout with the signout page (optional)
url(r'^accounts/logout/$', django_saml2_auth.views.signout),

# The following line will replace the default admin user logout with the signout page (optional)
url(r'^admin/logout/$', django_saml2_auth.views.signout),

To override the built in signout page put a template named 'django_saml2_auth/signout.html' in your project's template folder.

If your SAML2 identity provider uses user attribute names other than the defaults listed in the settings.py ATTRIBUTES_MAP, update them in settings.py.

For Okta Users

I created this plugin originally for Okta.

The METADATA_AUTO_CONF_URL needed in settings.py can be found in the Okta web UI by navigating to the SAML2 app's Sign On tab, in the Settings box. You should see :

Identity Provider metadata is available if this application supports dynamic configuration.

The Identity Provider metadata link is the METADATA_AUTO_CONF_URL.

How to Contribute

  1. Check for open issues or open a fresh issue to start a discussion around a feature idea or a bug.
  2. Fork the repository on GitHub to start making your changes to the master branch (or branch off of it).
  3. Write a test which shows that the bug was fixed or that the feature works as expected.
  4. Send a pull request and bug the maintainer until it gets merged and published. :) Make sure to add yourself to AUTHORS.

Release Log

2.2.1: Fixed is_safe_url parameters issue for django 2.1

2.2.0: ADFS SAML compatibility and fixed some issue for Django2.0

2.1.2: Merged #35

2.1.1: Added ASSERTION_URL in settings.

2.1.0: Add DEFAULT_NEXT_URL. Issue #19.

2.0.4: Fixed compatibility with Windows.

2.0.3: Fixed a vulnerabilities in the login flow, thanks qwrrty.

2.0.1: Add support for Django 1.10

1.1.4: Fixed urllib bug

1.1.2: Added support for Python 2.7/3.x

1.1.0: Added support for Django 1.6/1.7/1.8/1.9

1.0.4: Fixed English grammar mistakes

django-saml2-auth's People

Contributors

andreloose avatar ayr-ton avatar dspeichert avatar fangli avatar gene1wood avatar jacobh avatar jberkz avatar kevpo avatar mahaffey avatar qwrrty avatar rrauenza avatar sahir avatar tonylechner-mitel avatar tonymke avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

django-saml2-auth's Issues

DRF support?

We're currently looking into implementing authentication on top of our API, where ADFS/SAML would be the cleanest solution. How ever, only certain user groups in AD should have access.
Reading through the docs here, its not clear whether this package only support pure Django or also DRF?

add config for admin:index

Hey,

would it be a good idea to make default login page configurable through some setting? we have the scenario that to protect all the views with okta. it does not make sense to redirect to admin:login for all the views.

thanks,

Implement functionality as authentication backend?

Is it possible to implement this functionality as an authentication backend, instead of being built directly into views? I would like to use this in conjunction with other authentication packages, such as django-rest-auth, but the current structure of this project makes that very difficult.

Also, I would like to utilize django-rest-framework-jwt as an alternative authentication method, but again, that's difficult with this.

getting none for authn_response variable

Line no 127, views.py:

authn_response = saml_client.parse_authn_request_response(
resp, entity.BINDING_HTTP_POST)
if authn_response is None:
return HttpResponseRedirect(get_reverse([denied, 'denied', 'django_saml2_auth:denied']))

I am getting None value for this authn_response variable, so my website redirecting to denied page.

I am helpless for this

SigverError: Can't find ['xmlsec1'] and metadata never fetched ?

Hello.

I'm trying to setup SAML Authentication using a KeyCloak server, I've setup the django app like this :

SAML2_AUTH = {
    # Required setting
    'METADATA_AUTO_CONF_URL': 'https://xxx.xxx.net/auth/realms/xxx/protocol/saml/descriptor',
}

But so far

All the pages related to SAML (/saml2_auth/..., /admin/login/) are returning :

SigverError at /admin/login/
Can't find ['xmlsec1']

And I don't see any incoming request fetching the SAML metadata

What could be the cause ?

Thanks

Django 2.0 url Support (broken code)

File "/usr/local/lib/python3.6/site-packages/django_saml2_auth/views.py", line 49, in get_reverse
from django.core.urlresolvers import reverse
ModuleNotFoundError: No module named 'django.core.urlresolvers'

Looks like views.py line #49 should be updated
from:
from django.core.urlresolvers import reverse
to:
from django.urls import reverse

due to code deprecation

NoReverseMatch u'admin' is not a registered namespace

Hi Fang,
I was excited to find your github for Okta w/ django. I ran into an issue though.

NoReverseMatch at /accounts/login/
u'admin' is not a registered namespace
Request Method: GET
Request URL: http://127.0.0.1:8000/accounts/login/
Django Version: 1.9.5
Exception Type: NoReverseMatch
Exception Value:
u'admin' is not a registered namespace
Exception Location: /Users/mrose/Dropbox/dev/samlauth/venv/lib/python2.7/site-packages/django/core/urlresolvers.py in reverse, line 596
Python Executable: /Users/mrose/Dropbox/dev/samlauth/venv/bin/python
Python Version: 2.7.10

/Users/mrose/Dropbox/dev/samlauth/venv/lib/python2.7/site-packages/django_saml2_auth/views.py in signin
next_url = r.GET.get('next', reverse('admin:index'))

def signin(r):
import urlparse
from urllib import unquote
next_url = r.GET.get('next', reverse('admin:index')) ...
try:
if "next=" in unquote(next_url):
next_url = urlparse.parse_qs(urlparse.urlparse(unquote(next_url)).query)['next'][0]
except:
next_url = r.GET.get('next', reverse('admin:index'))

So i tried adding 'namespace="admin"' to the urlpatterns.

urlpatterns = [
url(r'^saml2_auth/', include('django_saml2_auth.urls', namespace="admin")),`

However, i then received the following error.

Django Version: 1.9.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'index' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
Exception Location: /Users/mrose/Dropbox/dev/samlauth/venv/lib/python2.7/site-packages/django/core/urlresolvers.py in _reverse_with_prefix, line 508

Do you know what I'm doing wrong? Thanks for your help!!

open redirect vulnerability

We discovered recently while experimenting that a site using django-saml2-auth to authenticate against Okta is vulnerable to an open redirect vulnerability. For example, a maliciously crafted URL like https://safe.site/accounts/login_okta?next=//evil.site will redirect the user to Okta for authentication, which will then redirect them to evil.site after they successfully authenticate. The evil site operator can then engage in a phishing attack, or even take advantage of the user's safe.site credentials to compromise the original site.

PR #17 was filed to address this issue.

ookta setup

is there any more comprehensive guides?
I am having a lot of issues with this.

setup exactly how the README says.
When testing on my local runserver I get the redirect to ookta login then on the redirect it goes in an infinite loop on firefox with:
image
clicking continue just reloads and pops up again

Looking at the django log it is constantly looping:

Starting development server at http://0.0.0.0:8006/
Quit the server with CONTROL-C.
[10/Jan/2019 14:02:29] "GET / HTTP/1.1" 302 0
[10/Jan/2019 14:02:30] "GET /accounts/login/?next=/ HTTP/1.1" 302 0
[10/Jan/2019 14:02:32] "POST /saml2_auth/acs/ HTTP/1.1" 302 0
[10/Jan/2019 14:02:33] "GET /accounts/login/?next=/saml2_auth/acs/ HTTP/1.1" 302 0
[10/Jan/2019 14:02:34] "POST /saml2_auth/acs/ HTTP/1.1" 302 0
[10/Jan/2019 14:02:34] "GET /accounts/login/?next=/saml2_auth/acs/ HTTP/1.1" 302 0
[10/Jan/2019 14:02:36] "POST /saml2_auth/acs/ HTTP/1.1" 302 0
[10/Jan/2019 14:02:36] "GET /accounts/login/?next=/saml2_auth/acs/ HTTP/1.1" 302 0

On ookta side:
image

Had to dig through issues to see that i should configure allow request to other SSos.
And it still doesn't work.

Also authentication backend is default:

AUTHENTICATION_BACKENDS = (                                                                                             
'django.contrib.auth.backends.ModelBackend',
)

Support SP Metadata

Although request signing is not required by the protocol, there are some IdPs that may require it.
Is there any option to support SP Metadata and request signing?

Using pysaml2 > 4.5.0 causes errors wrt to entityid attribute being missing.

Traceback (most recent call last):
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/registry_library/src/django-saml2-auth/django_saml2_auth/views.py", line 160, in acs
    resp, entity.BINDING_HTTP_POST)
  File "/usr/local/lib/python3.7/site-packages/saml2/client_base.py", line 679, in parse_authn_request_response
    if not getattr(self.config, 'entityid', None):
saml2.SAMLError: Missing entity_id specification

I've had to pin my requireemnts to install from master for this project.
But I've also had to pin my requirements for pysaml2 to 4.5.0 cause a release in pysaml2 checks for the existance of the entityid in the pysaml config. When we instantiate the saml client here I think we need to pass in a config object.

cause later in the pysaml2 lib here we are checking for the existance of an attribute config.

G-Suite Error 400

When using G-Suite as Identity provider, i get the following 400 error:

Error parsing the request, invalid_sp_id: The <Issuer> element MUST be present in <AuthnRequest> element.

AttributeError: module 'django_saml2_auth' has no attribute 'urls'

I followed all the instruction but their is error with following AttributeError: module 'django_saml2_auth' has no attribute 'urls'.

code !!

from django.contrib import admin
from django.urls import path,include
from . import views
import django_saml2_auth.views

urlpatterns = [
path('', views.login , name='index'),
path('admin/', admin.site.urls),
path('accounts/login/', views.login ),
path('success', views.loggedin),
path('sso_auth/', include(django_saml2_auth.urls)),
]
screenshot 2

We got a URL reverse issue: ['admin:index']

I received this error when trying to integrate with Okta. I looked at other issues opened, and I do have the url(r'^saml2_auth/', include('django_saml2_auth.urls')), line at the top of my URL patterns, but still have the issue.

How to implement SLO services ?

Thank you for the awesome lib , I can using the lib to do the authentication for saml2 .

But is there any ways to do the slo server to single logout ?

Hitting /saml2_auth/acs immediately redirects to /saml2_auth/denied with no logs

Hi all,

How do I enable debug logging for this scenario? Browsing to /saml2_auth/acs immediately redirects me to /saml2_auth/denied and there are no logs available. I have the following logging configuration:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'django': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'saml2': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'saml2.client_base': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'saml2.sigver': {
            'handlers': ['console'],
            'level': 'DEBUG',
        },
        'django.request':{
            'handlers': ['console'],
            'level': 'DEBUG',
        },
    },
}

Small readme logout typo

Thank you for writing this!
I think the logout views references are quoted by accident in the readme.
I submitted a small PR #40

unable to work with windows

I'm using windows 10 but it give me missing [xmlsec,xmlsec1]
I tried couple of ways
- pip install`,
- downloaded zip file
but unable to install.

Is there any way to install that I'm not aware of?

Logging unavailable

I am trying to figure out what's going on in this application and it's kind of impossible cause there's 0 logging.

It would be great if you could enable some logging so I can read the debug logs, and as such hopfully figure out why the CSRF token is failing.
#30

Getting Blank page and 500 internal server error for redirect to /saml2_auth/acs/

Not really sure what to do here. I have nginx running, listening on port 80 and passing to the gunicorn server. I think this may have something to do with it, but really, no clue at this point.

I go to http://mysite.com/admin -> Okta to Authenticate -> redirects to http://mysite.com/saml2_auth/acs/ with a 500.

Would appreciate any help. Thanks!

EDIT: Looks like every time I go to /admin, its successfully authenticates on the Okta side.

Saml2 metadata file?

More than an issue, this is a question.
I need to implement SAML2 in my django app.

I want it to make it work with http://www.testshib.org

At http://www.testshib.org/register.html they are requesting a Metadata file I believe all Saml service providers must have. But in the documentation, unless I've missed it, I haven't seen anything. The METADATA_AUTO_CONF_URL doesn't seem to be an option in my case. I guess since it is required, there's nothing to do?.

page not found

getting this error:
image

Whats wrong with the url definitions?
Followed instructions:

from django.conf.urls import include, url
from django.contrib import admin
import django_saml2_auth.views

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^saml2_auth/', include('django_saml2_auth.urls')),
    url(r'^accounts/login/$', django_saml2_auth.views.signin),
    url(r'^admin/login/$', django_saml2_auth.views.signin),
]

Am i missing something obvious?

NoneType' object has no attribute 'subject'

Hi-

The idp I have , that is okta, is encrypting the saml response with the public key of my server. I have the private key of the server.

I need to decrypt it to get the user identity.

My saml setting is

saml_settings = {
'metadata': {
"local": [
metadat_xml

        ],           
    },
    'service': {
        'sp': {
            'endpoints': {
                'assertion_consumer_service': [
                    (acs_url, BINDING_HTTP_REDIRECT),
                    (acs_url, BINDING_HTTP_POST),
                    (https_acs_url, BINDING_HTTP_REDIRECT),
                    (https_acs_url, BINDING_HTTP_POST)
                ],
            },
            'allow_unsolicited': True,
            'authn_requests_signed': False,
            'logout_requests_signed': True,
            'want_assertions_signed': True,
            'want_response_signed': False,
        },
    },

    'key_file': "mykey.key",  # private part
    'cert_file': "mykey.crt",  # public part
    'xmlsec_path': '/usr/bin/xmlsec1',
    'encryption_keypairs': [{
        'key_file': 'mykey.key',
        'cert_file': 'mykey.crt',
    }]
}

I am not abel to get the user identity and it says NoneType' object has no attribute 'subject'

I tried decrypting the token using the below url with my private key and I am able to decrypt it.
https://www.samltool.com/decrypt.php

Can you please let me know what I am missing?

NoReverseMatch

Request Method: GET
Request URL: http://127.0.0.1:8000/saml_auth2/acs/acs/
Django Version: 1.9.5
Exception Type: NoReverseMatch
Exception Value:
Reverse for 'acs' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []

From this file:

.../venv/lib/python2.7/site-packages/django_saml2_auth-1.0.4-py2.7.egg/django_saml2_auth/views.py in _get_saml_client

    return '{scheme}://{host}'.format(
        scheme=r.scheme,
        host=r.get_host(),
    )
def _get_saml_client(domain):
    acs_url = domain + reverse('acs') ...
    import tempfile
    tmp = tempfile.NamedTemporaryFile()
    f = open(tmp.name, 'w')
    f.write(urllib2.urlopen(settings.SAML2_AUTH['METADATA_AUTO_CONF_URL']).read())
    f.close()
    saml_settings = {

my urls.py file:

urlpatterns = [

    # These are the SAML2 related URLs. You can change "^saml2_auth/" regex to
    # any path you want, like "^sso_auth/", "^sso_login/", etc. (required)
    url(r'^saml_auth2/acs/', include('django_saml2_auth.urls')),

    # The following line will replace the default user login with SAML2 (optional)
    url(r'^accounts/login/$', 'django_saml2_auth.views.signin'),

    # The following line will replace the admin login with SAML2 (optional)
    url(r'^admin/login/$', 'django_saml2_auth.views.signin'),

    # google chrome favicon fix
    url(r'^favicon.ico/$', lambda x: HttpResponseRedirect(settings.STATIC_URL + 'img/favicon.ico')),
    url(r'^$', RedirectView.as_view(url='outage')),
    url(r'^admin/', admin.site.urls),
    url(r'^manage/', admin.site.urls),
    url(r'^outage/', include('comapp.urls')),

I'm not entirely sure where the problem is, so I don't know what files I should post to help troubleshoot.

G-Suite Integration

I'm trying to setup G-Suite SAML authentication, during the setup process, G-Suite is asking for the ACS url and entity ID, both are required. From reading the README it says that identiy id would be "http://your-domain/saml2_auth/acs/" so what would the ACS url be?

With ADFS

It can be configured as Service Provider for ADFS 2.0, which operates as Identity Provider?

Infinite redirect loop

I am using the main / url to be my login page.

When I set that url to be handled by django-saml2-auth it causes an infinite redirect loop.

Any idea on how to solve this?

JWT Token Authentication for Frontend app, Custom User Model, Will send PR soon

My application required both of these features.

I was able to edit the code of this repo in order to make my use case work.

I will be making a pull request that adds my functionality in a general sense, which will use Django Settings file.

The repo in its current state will only get you a Django session and requires you to use the default Django User model.

If you are using a frontend that requires token auth (in my case JWT), you will need to write some custom code in the views.py.

I will add to the possible settings and to the readme to explain how to use this my newly added functionality.

Expect this pull request early next week.

๐Ÿ˜„

URL reverse issue: ['admin:index']

See error message below.

Please let me know if you need any more info.

Request Method: GET
http://localhost:8000/login/?next=http://localhost:8000
1.11.3
Exception
We got a URL reverse issue: ['admin:index']. This is a known issue but please still submit a ticket at https://github.com/fangli/django-saml2-auth/issues/new
/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django_saml2_auth/views.py in get_reverse, line 58
/Users/sohd001/IdeaProjects/qatools_venv/bin/python
3.6.1
['/Users/sohd001/IdeaProjects/QA-Tools', '/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python36.zip', '/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6', '/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/lib-dynload', '/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages', '/Users/sohd001/IdeaProjects/QA-Tools/python_scripts/ipa_tools/', '/Users/sohd001/IdeaProjects/QA-Tools/python_scripts/charles_tools/', '/Users/sohd001/IdeaProjects/QA-Tools/python_scripts/apk_tools/', '/Users/sohd001/IdeaProjects/QA-Tools/python_scripts/common/']
Thu, 21 Sep 2017 01:54:40 -0500

rfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware')

Traceback:

File "/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner
41. response = get_response(request)

File "/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _legacy_get_response
249. response = self._get_response(request)

File "/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
187. response = self.process_exception_by_middleware(e, request)

File "/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response
185. response = wrapped_callback(request, *callback_args, **callback_kwargs)

File "/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django_saml2_auth/views.py" in signin
180. next_url = r.GET.get('next', settings.SAML2_AUTH.get('DEFAULT_NEXT_URL', get_reverse('admin:index')))

File "/Users/sohd001/IdeaProjects/qatools_venv/lib/python3.6/site-packages/django_saml2_auth/views.py" in get_reverse
58. raise Exception('We got a URL reverse issue: %s. This is a known issue but please still submit a ticket at https://github.com/fangli/django-saml2-auth/issues/new' % str(objs))

Exception Type: Exception at /login/
Exception Value: We got a URL reverse issue: ['admin:index']. This is a known issue but please still submit a ticket at https://github.com/fangli/django-saml2-auth/issues/new

Change page displayed after login

Hi,

I'm trying to make my application redirect to / instead of /admin after the login.
In #5, you mention adding the next parameter, but I'm not sure where I should add this.

I'm using this plugin to integrate with Okta.

Cheers,
Mario

Can we use this in partnership with existing django auth?

Would it be possible to split the responsibility of this SAML module to be an option for login, instead of "taking over" the login page completely? Seems like maybe this module is an "all or nothing" approach, and I'd like to build a service provider which allows me to use my existing authentication plus add a SAML login (perhaps from a different login landing page) for a third-party IDP.

Code improvements

Hello.

Some time ago I decided to use your package but I had to make a few changes. After forking and editing I realized the code isn't of a very high quality. Would you mind if I sent PR with some PEP8 changes and maybe other improvements?

Support for Django 1.10

Several deprecation warnings appear when running with Django 1.9, as shown below, which need to be handled in order to support Django 1.10.

/.../lib/python3.4/site-packages/django_saml2_auth/urls.py:8: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got acs). Pass the callable instead.
url(r'^acs/$', "acs", name="acs"),

/.../lib/python3.4/site-packages/django_saml2_auth/urls.py:9: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got welcome). Pass the callable instead.
url(r'^welcome/$', "welcome", name="welcome"),

/.../lib/python3.4/site-packages/django_saml2_auth/urls.py:10: RemovedInDjango110Warning: Support for string view arguments to url() is deprecated and will be removed in Django 1.10 (got denied). Pass the callable instead.
url(r'^denied/$', "denied", name="denied"),

/.../lib/python3.4/site-packages/django_saml2_auth/urls.py:10: RemovedInDjango110Warning: django.conf.urls.patterns() is deprecated and will be removed in Django 1.10. Update your urlpatterns to be a list of django.conf.urls.url() instances instead.
url(r'^denied/$', "denied", name="denied"),

METADATA_AUTO_CONF_URL requires authentication

I am using this plugin for my django application for Okta integration. However I am unable to use it as my metadata url is also authenticated by session which is present in browser but not in my app. Please provide a method so that I can download the contents of metadata url in a xml file and provide path for same in settings instead of url.

Active Directory/SAML IDP can't process request

Trying to access an Active Directory SAML IDP and they are unable to process my request. According to the IDP staff the problem is with the following line in the Request:

<ns1:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:entity"

They want it to be:
<ns1:Issuer Format="urn:oasis:names:tc:SAML:2.0:nameid-format:unspecified"

or possibly removed from the request altogether as it is not an attribute they have ever used before. I am having to trust their word as this is my first SAML project and while it worked with Okta, it is erroring on their server.

<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)> Request Method: POST

I am new to configuring django auth and saml2. At my work , I am building a single page django application that I want to authenticate access to via okta which has been connected to an identity provider by IT. Within my django app that I am running on my dev laptop:
In my urls.py I added the entry for django_saml2 to handle all urls and in the okta admin console I set all of the settings to django_saml2_auth/acs/

for eg. in urls.py
url(r'^saml2_auth/', include('django_saml2_auth.urls')),

On the console I have
Single Sign On URLhttp://localhost:8000/saml2_auth/acs/

Now when I navigate to my app or to http://localhost:8000/saml2_auth/acs/

I get the error from my django debug toolbar informing below. The error may be in my django app or in my okta-config. Please can you help me figure our where something is going wrong and how I can troubleshoot it.

I also created a dev-okta account so that I have full admin control and it gives me the same error.
Thanks

Request Method: | GET
-- | --
http://127.0.0.1:8000/saml2_auth/acs/
1.11
URLError
<urlopen error [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)>
/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/urllib/request.py in do_open, line 1320
/Users/hari/.virtualenvs/ic50project/bin/python
3.6.0
['/Users/hari/ec50_django_project',  '/Applications/PyCharm.app/Contents/helpers/pydev',  '/Users/hari/ec50_django_project',  '/Applications/PyCharm.app/Contents/helpers/pydev',  '/Users/hari/.virtualenvs/ic50project/lib/python36.zip',  '/Users/hari/.virtualenvs/ic50project/lib/python3.6',  '/Users/hari/.virtualenvs/ic50project/lib/python3.6/lib-dynload',  '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6',  '/Users/hari/.virtualenvs/ic50project/lib/python3.6/site-packages']
Fri, 14 Jul 2017 20:43:12 +0000

Internal Server Error KeyError:

Hello i try to use this plugin with okta, when run my app i get the followin error
Internal Server Error: /saml2_auth/acs/
KeyError: 'Email'

Setting to disable automatically creating a new user

I'm currently in a situation where I'd rather not create a new Django user if one can't be found. To me, this mimics the idea that the user is authenticated, but not authorized to use the application.

I would be glad to add this setting if others thought it was useful as well. It's a pretty small code change.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.