Skip to content
Django CAS (Central Authentication Service) client
Branch: master
Clone or download
Pull request Compare This branch is 13 commits behind mingchen:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Type Name Latest commit message Commit time
Failed to load latest commit information.


Django CAS NG

django-cas-ng is a Central Authentication Service (CAS) client implementation. This project inherits from django-cas (which has not been updated since April 2013). The NG stands for "next generation". Our fork will include bugfixes and new features contributed by the community.


  • Supports CAS versions 1.0, 2.0 and 3.0.
  • Support Single Sign Out
  • Supports Token auth schemes
  • Can fetch Proxy Granting Ticket
  • Supports Django 1.5, 1.6, 1.7, 1.8, 1.9, 1.10, 1.11 and 2.0
  • Supports using a User custom model
  • Supports Python 2.7, 3.x


Install with pip:

pip install django-cas-ng

Install the latest code:

pip install

Install from source code:

python install


Now add it to the middleware, authentication backends and installed apps in your settings. Make sure you also have the authentication middleware installed. Here's an example:




Set the following required setting in

Optional settings include:

  • CAS_ADMIN_PREFIX: The URL prefix of the Django administration site. If undefined, the CAS middleware will check the view being rendered to see if it lives in django.contrib.admin.views.

  • CAS_CREATE_USER: Create a user when the CAS authentication is successful. The default is True.

  • CAS_CREATE_USER_WITH_ID: Create a user using the id field provided by the attributes returned by the CAS provider. Default is False. Raises ImproperlyConfigured exception if attributes are not provided or do not contain the field id.

  • CAS_LOGIN_MSG: Welcome message send via the messages framework upon successful authentication. Take the user login as formatting argument. The default is "Login succeeded. Welcome, %s." or some translation of it if you have enabled django internationalization (USE_I18N = True) You cas disable it by setting this parametter to None

  • CAS_LOGGED_MSG: Welcome message send via the messages framework upon authentication attempt if the user is already authenticated. Take the user login as formatting argument. The default is "You are logged in as %s." or some translation of it if you have enabled django internationalization (USE_I18N = True) You cas disable it by setting this parametter to None

  • CAS_LOGIN_URL_NAME: Name of the login url, defaults to 'cas_ng_login'. This is only necessary if you use the middleware and want to use some other name for the login url (e.g. 'my_app:cas_login').

  • CAS_EXTRA_LOGIN_PARAMS: Extra URL parameters to add to the login URL when redirecting the user. Example:

    CAS_EXTRA_LOGIN_PARAMS = {'renew': true}

    If you need these parameters to be dynamic, then we recommend to implement a wrapper for our default login view (the same can be done in case of the logout view). See an example in the section below.

  • CAS_RENEW: whether pass renew parameter on login and verification of ticket to enforce that the login is made with a fresh username and password verification in the CAS server. Default is False.

  • CAS_IGNORE_REFERER: If True, logging out of the application will always send the user to the URL specified by CAS_REDIRECT_URL.

  • CAS_LOGOUT_COMPLETELY: If False, logging out of the application won't log the user out of CAS as well.

  • CAS_REDIRECT_URL: Where to send a user after logging in or out if there is no referrer and no next page set. This setting also accepts named URL patterns. Default is /.

  • CAS_RETRY_LOGIN: If True and an unknown or invalid ticket is received, the user is redirected back to the login page.

  • CAS_STORE_NEXT: If True, the page to redirect to following login will be stored as a session variable, which can avoid encoding errors depending on the CAS implementation.

  • CAS_VERSION: The CAS protocol version to use. '1' '2' '3' and 'CAS_2_SAML_1_0' are supported, with '2' being the default.

  • CAS_USERNAME_ATTRIBUTE: The CAS user name attribute from response. The default is uid.

  • CAS_PROXY_CALLBACK: The full url to the callback view if you want to retrive a Proxy Granting Ticket

  • CAS_ROOT_PROXIED_AS: Useful if behind a proxy server. If host is listening on but request is Add CAS_ROOT_PROXIED_AS = '' to your settings.

  • CAS_FORCE_CHANGE_USERNAME_CASE: If lower, usernames returned from CAS are lowercased before we check whether their account already exists. Allows user Joe to log in to CAS either as joe or JOE without duplicate accounts being created by Django (since Django allows case-sensitive duplicates). If upper, the submitted username will be uppercased. Default is False.

  • CAS_APPLY_ATTRIBUTES_TO_USER: If True any attributes returned by the CAS provider included in the ticket will be applied to the User model returned by authentication. This is useful if your provider is including details about the User which should be reflected in your model. The default is False.

  • CAS_RENAME_ATTRIBUTES: a dict used to rename the (key of the) attributes that the CAS server may retrun. For example, if CAS_RENAME_ATTRIBUTES = {'ln':'last_name'} the ln attribute returned by the cas server will be renamed as last_name. Used with CAS_APPLY_ATTRIBUTES_TO_USER = True, this provides an easy way to fill in Django Users' info independtly from the attributes' keys returned by the CAS server.

  • CAS_VERIFY_SSL_CERTIFICATE: If False CAS server certificate won't be verified. This is useful when using a CAS test server with a self-signed certificate in a development environment. Default is True.

  • CAS_LOCAL_NAME_FIELD: If set, will make user lookup against this field and not model's nautral key. This allows you to authenticate arbitrary users.

Make sure your project knows how to log users in and out by adding these to your URL mappings:

import django_cas_ng.views

url(r'^accounts/login$', django_cas_ng.views.LoginView.as_view(), name='cas_ng_login'),
url(r'^accounts/logout$', django_cas_ng.views.LogoutView.as_view(), name='cas_ng_logout'),

If you use the middleware, the login url must be given the name cas_ng_login or it will create redirection issues, unless you set the CAS_LOGIN_URL_NAME setting.

You should also add an URL mapping for the CAS_PROXY_CALLBACK settings:

url(r'^accounts/callback$', django_cas_ng.views.callback, name='cas_ng_proxy_callback'),

Run ./ syncdb to create Single Sign On and Proxy Granting Ticket tables. On update you can just delete the django_cas_ng_sessionticket table and the django_cas_ng_proxygrantingticket before calling ./ syncdb.

Consider running the command ./ django_cas_ng_clean_sessions on a regular basis right after the command ./ clearsessions cf clearsessions. It could be a good idea to put it in the crontab.

Users should now be able to log into your site using CAS.

View-wrappers example

The settings.CAS_EXTRA_LOGIN_PARAMS allows you to define a static dictionary of extra parameters to be passed on to the CAS login page. But what if you want this dictionary to be dynamic (e.g. based on user session)?

Our current advice is to implement simple wrappers for our default views, like these ones:

from django_cas_ng import views as baseviews

def login(request, **kwargs):
    return _add_locale(request, baseviews.login(request, **kwargs))

def logout(request, **kwargs):
    return _add_locale(request, baseviews.logout(request, **kwargs))

def _add_locale(request, response):
    """If the given HttpResponse is a redirect to CAS, then add the proper
    `locale` parameter to it (and return the modified response). If not, simply
    return the original response."""

    if (
        isinstance(response, HttpResponseRedirect)
        and response['Location'].startswith(settings.CAS_SERVER_URL)
        from ourapp.some_module import get_currently_used_language
        url = response['Location']
        url += '&' if '?' in url else '&'
        url += "locale=%s" % get_currently_used_language(request)
        response['Location'] = url
    return response

Custom backends

The CASBackend class is heavily inspired from Django's own RemoteUserBackend and allows for some configurability through subclassing if you need more control than django-cas-ng's settings provide. For instance, here is an example backend that only allows some users to login through CAS:

from django_cas_ng.backends import CASBackend

class MyCASBackend(CASBackend):
    def user_can_authenticate(self, user):
        if user.has_permission('can_cas_login'):
            return True
        return False

If you need more control over the authentication mechanism of your project than django-cas-ng's settings provide, you can create your own authentication backend that inherits from django_cas_ng.backends.CASBackend and override these attributes or methods:


Performs any cleaning on the username prior to using it to get or create a User object. Returns the cleaned username. The default implementations changes the case according to the value of CAS_FORCE_CHANGE_USERNAME_CASE.


Returns whether the user is allowed to authenticate. For consistency with Django's own behavior, django-cas-ng will allow all users to authenticate through CAS on Django versions lower than 1.10; starting with Django 1.10 however, django-cas-ng will prevent users with is_active=False from authenticating.


Configures a newly created user. This method is called immediately after a new user is created, and can be used to perform custom setup actions. Returns the user object.

CASBackend.bad_attributes_reject(request, username, attributes)

Rejects a user if the returned username/attributes are not OK. For example, to accept a user belonging to departmentNumber 421 only, define in mysite/ the key-value constant:

MY_ATTRIBUTE_CONTROL = ('departmentNumber', '421')

and the authentication backends:


and create a file mysite/ containing:

from django_cas_ng.backends import CASBackend
from django.contrib import messages
from django.conf import settings

class MyCASBackend(CASBackend):
    def user_can_authenticate(self, user):
        return True

    def bad_attributes_reject(self, request, username, attributes):
        attribute = settings.MY_ATTRIBUTE_CONTROL[0]
        value = settings.MY_ATTRIBUTE_CONTROL[1]

        if attribute not in attributes:
            message = 'No \''+ attribute + '\' in SAML attributes'
            messages.add_message(request, messages.ERROR, message)
            return message

        if value not in attributes[attribute]:
            message = 'User ' + str(username) + ' is not in ' + value + ' ' + attribute + ', should be one of ' + str(attributes[attribute])
            messages.add_message(request, messages.ERROR, message)
            return message

        return None



Sent on successful authentication, the CASBackend will fire the cas_user_authenticated signal.

Arguments sent with this signal

The authentication backend instance that authenticated the user.
The user instance that was just authenticated.
Boolean as to whether the user was just created.
Attributes returned during by the CAS during authentication.
The ticket used to authenticate the user with the CAS.
The service used to authenticate the user with the CAS.
The request that was used to login.


Sent on user logout. Will be fired over manual logout or logout via CAS SingleLogOut query.

Arguments sent with this signal

manual if manual logout, slo on SingleLogOut
The user instance that is logged out.
The current session we are loging out.
The ticket used to authenticate the user with the CAS. (if found, else value if set to None)

Proxy Granting Ticket

If you want your application to be able to issue Proxy Ticket to authenticate against some other CAS application, setup the CAS_PROXY_CALLBACK parameter. Allow on the CAS config django_cas_ng to act as a Proxy application. Then after a user has logged in using the CAS, you can retrieve a Proxy Ticket as follow:

from django_cas_ng.models import ProxyGrantingTicket

def my_pretty_view(request, ...):
    proxy_ticket = ProxyGrantingTicket.retrieve_pt(request, service)

where service is the service url for which you want a proxy ticket.


You can contribute to the translation of welcome messages by running django-admin makemessages -l lang_code inside of the django_cas_ng directory. Where lang_code is the language code for which you want to submit a translation. Then open the file django_cas_ng/locale/lang_code/LC_MESSAGES/django.po with a gettex translations editor (for example Translate and save the file. Think to add django_cas_ng/locale/lang_code/LC_MESSAGES/django.po to repo. Please do not add django_cas_ng/locale/lang_code/LC_MESSAGES/ to repo since .mo file can be generated by .po file.


Every code commit triggers a travis-ci build. checkout current build status at

Testing is managed by pytest and tox. Before run install, you need install required packages for testing:

pip install -r requirements-dev.txt

To run testing on locally:


To run all testing on all enviroments locally:



Contributions are welcome!

If you would like to contribute this project. Please feel free to fork and send pull request. Please make sure tests are passed. Also welcome to add your name to Credits section of this document.

New code should follow both PEP8 and the Django coding style.



You can’t perform that action at this time.