Package: nereo-django-cas-ng
django-cas-ngis Central Authentication Service (CAS) client implementation.
This project inherits fromdjango-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.FeaturesSupportsCASversions 1.0, 2.0 and 3.0.Support Single Sign OutCan fetch Proxy Granting TicketSupports Django 1.5, 1.6, 1.7 and 1.8 withUser custom modelSupports Python 2.7, 3.xInstallationInstall withpip:pip install django-cas-ngInstall the latest code:pip install https://github.com/mingchen/django-cas-ng/archive/master.zipInstall from source code:python setup.py installSettingsNow 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:INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django_cas_ng',
    ...
)

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    ...
)

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend',
    'django_cas_ng.backends.CASBackend',
)Set the following required setting insettings.py:CAS_SERVER_URL: This is the only setting you must explicitly define.Set it to the base URL of your CAS source (e.g.https://account.example.com/cas/).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 indjango.contrib.admin.views.CAS_CREATE_USER: Create a user when the CAS authentication is successful.
The default isTrue.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 toNoneCAS_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 toNoneCAS_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 passrenewparameter 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 isFalse.CAS_IGNORE_REFERER: IfTrue, logging out of the application will
always send the user to the URL specified byCAS_REDIRECT_URL.CAS_LOGOUT_COMPLETELY: IfFalse, 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: IfTrueand an unknown or invalid ticket is
received, the user is redirected back to the login page.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 isuid.CAS_PROXY_CALLBACK: The full url to the callback view if you want to
retrive a Proxy Granting TicketCAS_FORCE_CHANGE_USERNAME_CASE: Iflower, usernames returned from CAS are lowercased before
we check whether their account already exists. Allows userJoeto log in to CAS either asjoeorJOEwithout duplicate accounts being created by Django (since Django allows
case-sensitive duplicates). Ifupper, the submitted username will be uppercased. Default isFalse.Make sure your project knows how to log users in and out by adding these to
your URL mappings:import django_cas_ng

url(r'^accounts/login$', django_cas_ng.views.login, name='cas_ng_login'),
url(r'^accounts/logout$', django_cas_ng.views.logout, name='cas_ng_logout'),You should also add an URL mapping for theCAS_PROXY_CALLBACKsettings:url(r'^accounts/callback$', django_cas_ng.views.callback, name='cas_ng_proxy_callback'),Run./manage.py syncdbto create Single Sign On and Proxy Granting Ticket tables.
On update you can just delete thedjango_cas_ng_sessiontickettable and thedjango_cas_ng_proxygrantingticketbefore calling./manage.py syncdb.Consider running the command./manage.py django_cas_ng_clean_sessionson a regular basis
right after the command./manage.py clearsessionscfclearsessions.
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 exampleThesettings.CAS_EXTRA_LOGIN_PARAMSallows 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:fromdjango_cas_ngimportviewsasbaseviews@csrf_exemptdeflogin(request,**kwargs):return_add_locale(request,baseviews.login(request,**kwargs))deflogout(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)andresponse['Location'].startswith(settings.CAS_SERVER_URL)):fromourapp.some_moduleimportget_currently_used_languageurl=response['Location']url+='&'if'?'inurlelse'&'url+="locale=%s"%get_currently_used_language(request)response['Location']=urlreturnresponseCustom backendsTheCASBackendclass is heavily inspired from Django’s ownRemoteUserBackendand 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:fromdjango_cas_ng.backendsimportCASBackendclassMyCASBackend(CASBackend):defuser_can_authenticate(self,user):ifuser.has_permission('can_cas_login'):returnTruereturnFalseIf 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 fromdjango_cas_ng.backends.CASBackendand override
these attributes or methods:CASBackend.clean_username(username)Performs any cleaning on theusernameprior to using it to get or create aUserobject. Returns the cleaned username. The default implementations
changes the case according to the value ofCAS_FORCE_CHANGE_USERNAME_CASE.CASBackend.user_can_authenticate(user)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 withis_active=Falsefrom
authenticating.CASBackend.configure_user(user)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.Signalsdjango_cas_ng.signals.cas_user_authenticatedSent on successful authentication, theCASBackendwill fire thecas_user_authenticatedsignal.Arguments sent with this signalsenderThe authentication backend instance that authenticated the user.userThe user instance that was just authenticated.createdBoolean as to whether the user was just created.attributesAttributes returned during by the CAS during authentication.ticketThe ticket used to authenticate the user with the CAS.serviceThe service used to authenticate the user with the CAS.django_cas_ng.signals.cas_user_logoutSent on user logout. Will be fired over manual logout or logout via CAS SingleLogOut query.Arguments sent with this signalsendermanualif manual logout,sloon SingleLogOutuserThe user instance that is logged out.sessionThe current session we are loging out.ticketThe ticket used to authenticate the user with the CAS. (if found, else value if set toNone)Proxy Granting TicketIf 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 ProxyGrantingTicketdef my_pretty_view(request, …):proxy_ticket = ProxyGrantingTicket.retrieve_pt(request, service)whereserviceis the service url for which you want a proxy ticket.InternationalizationYou can contribute to the translation of welcome messages by runningdjango-adminmakemessages-llang_codeinside of the django_cas_ng directory. Wherelang_codeis the language code for which you want to submit a
translation. Then open the filedjango_cas_ng/locale/lang_code/LC_MESSAGES/django.powith a gettex translations
editor (for examplehttps://poedit.net/). Translate and save the file.
Think to adddjango_cas_ng/locale/lang_code/LC_MESSAGES/django.poto repo. Please do not adddjango_cas_ng/locale/lang_code/LC_MESSAGES/django.moto repo since .mo file can be generated by .po file.TestingEvery code commit triggers atravis-cibuild. checkout current build status athttps://travis-ci.org/mingchen/django-cas-ngTesting is managed bypytestandtox.
Before run install, you need install required packages for testing:pip install -r requirements-dev.txtTo run testing on locally:py.testTo run all testing on all enviroments locally:toxContributionContributions 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 toCreditssection of this document.New code should follow bothPEP8and theDjango coding style.Creditsdjango-casStefan HoromneaPiotr BulińskiPiper MerriamNathan BrownJason BrownbridgeBryce GroffJeffrey P Gilltimkung1Domingo Yeray Rodríguez MartínRayco Abad-MartínÉdouard LopezGuillaume VincentWojciech RygielskiValentin SamirAlexander KavanaughReferencesdjango-casCAS protocolJasig CAS server