Package: django-okta-auth
Django Okta AuthOverviewDjango Okta Auth is a library that acts as a client for the Okta OpenID Connect provider.The library provides a set of views for login, logout and callback, an auth backend for authentication, a middleware for token verification in requests, and a decorator that can be selectively applied to individual views.It's heavily influenced byokta-django-samplesbut there's a few fundamental changes and further implementation of things like refresh tokens which weren't initially implemented.This project is in no way affiliated with Okta.InstallationInstall from PyPI:pip install django-okta-authConfigurationInstall the AppAddokta_oauth2.apps.OktaOauth2ConfigtoINSTALLED_APPS:INSTALLED_APPS=("...",'okta_oauth2.apps.OktaOauth2Config',"...")Authentication BackendYou will need to install the authentication backend. This extends Django's defaultModelBackendwhich uses the configured database for user storage, but overrides theauthenticatemethod to accept theauth_codereturned by Okta's/authorizeAPI endpointas documented here.The Authentication Backend should be configured as so:AUTHENTICATION_BACKENDS=("okta_oauth2.backend.OktaBackend",)Using the middlewareYou can use the middleware to check for valid tokens during ever refresh and automatically refresh tokens when they expire. By using the middleware you are defaulting to requiring authentication on all your views unless they have been marked as public inPUBLIC_NAMED_URLSorPUBLIC_URLS.The order of middleware is important and theOktaMiddlewaremust be below theSessionMiddlewareandAuthenticationMiddlewareto ensure that the session and the user are both on the request:MIDDLEWARE=('django.middleware.security.SecurityMiddleware','django.contrib.sessions.middleware.SessionMiddleware','django.middleware.common.CommonMiddleware','django.middleware.csrf.CsrfViewMiddleware','django.contrib.auth.middleware.AuthenticationMiddleware','django.contrib.messages.middleware.MessageMiddleware','django.middleware.clickjacking.XFrameOptionsMiddleware','okta_oauth2.middleware.OktaMiddleware')Using the decoratorThe alternative to using the middleware is to selectively apply theokta_oauth2.decorators.okta_login_requireddecorator to views you wish to protect. When the view is accessed the decorator will check that valid tokens exist on the session, and if they don't then it will redirect to the login.The decorator is applied to a view like so:fromokta_oauth2.decoratorsimportokta_login_required@okta_login_requireddefdecorated_view(request):returnHttpResponse("i am a protected view")Update urls.pyAdd thedjango-okta-authviews to yoururls.py. This will provide thelogin,logoutandcallbackviews which are required by the login flows.fromdjango.urlsimportinclude,pathurlpatterns=[path('accounts/',include(("okta_oauth2.urls","okta_oauth2"),namespace="okta_oauth2")),]Setup your Okta ApplicationIn the Okta admin console create your application with the following steps:ClickCreate New AppChoose theWebplatformChoose theOpenID ConnectSign on methodClick theCreatebuttonGive the application a name and choose a logo if desiredAdd the URL to the login view as defined in the previous section, eg.http://localhost:8000/accounts/login/Click theSavebuttonIn the General Settings of the application click edit and checkAuthorization Codeand theRefresh TokenunderAllowed grant types.Save the settingsTake note of theClient IDand theClient secretin the Client Credentials for use in the next section. It is important to note that theClient secretis confidential and under no circumstances should be exposed publicly.Django Okta SettingsDjango Okta Auth settings should be specified in your djangosettings.pyas follows:OKTA_AUTH={"ORG_URL":"https://your-org.okta.com/","ISSUER":"https://your-org.okta.com/oauth2/default","CLIENT_ID":"yourclientid","CLIENT_SECRET":"yourclientsecret","SCOPES":"openid profile email offline_access",# this is the default and can be omitted"REDIRECT_URI":"http://localhost:8000/accounts/oauth2/callback","LOGIN_REDIRECT_URL":"/",# default"CACHE_PREFIX":"okta",# default"CACHE_ALIAS":"default",# default"PUBLIC_NAMED_URLS":(),# default"PUBLIC_URLS":(),# default"USE_USERNAME":False,# default}Login TemplateThe login view will render theokta_oauth2/login.htmltemplate. It will be passed the following information in theconfigtemplate context variable:{"clientId":settings.OKTA_AUTH["CLIENT_ID"],"url":settings.OKTA_AUTH["ORG_URL"],"redirectUri":settings.OKTA_AUTH["REDIRECT_URI"],"scope":settings.OKTA_AUTH["SCOPES"],"issuer":settings.OKTA_AUTH["ISSUER"]}The easiest way to use this is to implement theOkta Sign-In Widgetin your template.A minimal template for the login could be:<!DOCTYPE html><html><head><metacharset="utf-8"/><metaname="viewport"content="width=device-width, initial-scale=1.0"/><scriptsrc="https://global.oktacdn.com/okta-signin-widget/5.0.1/js/okta-sign-in.min.js"type="text/javascript"></script><linkhref="https://global.oktacdn.com/okta-signin-widget/5.0.1/css/okta-sign-in.min.css"type="text/css"rel="stylesheet"/></head><body><divid="okta-login-container"></div><scripttype="text/javascript">varoktaSignIn=newOktaSignIn({baseUrl:'{{config.url}}',clientId:'{{config.clientId}}',redirectUri:'{{config.redirectUri}}',authParams:{issuer:'{{config.issuer}}',responseType:['code'],scopes:"{{config.scope}}".split(" "),pkce:false,},});oktaSignIn.renderEl({el:'#okta-login-container'},function(res){console.log(res);}</script></body></html>Settings ReferenceORG_URL:str. URL Okta provides for your organization account. This is the URL that you log in to for the admin panel, minus the-admin. eg, if your admin URL ishttps://myorg-admin.okta.com/then yourORG_URLshould be:https://myorg.okta.com/ISSUERstr. This is the URL for your Authorization Server. If you're using the default authorization server then this will be:https://{ORG_URL}/oauth2/defaultCLIENT_IDstr. The Client ID provided by your Okta Application.CLIENT_SECRETstr. The Client Secret provided by your Okta Application.SCOPESstr. The scopes requested from the OpenID Authorization server. At the very least this needs to be"openid profile email"but if you want to use refresh tokens you will need"openid profile email offline_access". This is the default.If you want Okta to manage your groups then you should also includegroupsin your scopes.REDIRECT_URIstr. This is the URL to thecallbackview that the okta Sign-In Widget will redirect the browser to after the username and password have been authorized. If the directions in theurls.pysection of the documentation were followed and your django server is running onlocalhost:8000then this will be:http://localhost:8000/accounts/callback/LOGIN_REDIRECT_URLstr. This is the URL to redirect to from thecallbackafter a successful login. Defaults to/.CACHE_PREFIXstr. The application will utilise the django cache to store public keys requested from Okta in an effort to minimise network round-trips and speed up authorization. This setting will control the prefix for the cache keys. Defaults tookta.CACHE_ALIASstr. Specify which django cache should be utilised for storing public keys. Defaults todefault.PUBLIC_NAMED_URLSList[str]. A list or tuple of URL names that should be accessible without tokens. If you add a URL in this setting the middleware won't check for tokens. Default is:[]PUBLIC_URLSList[str]. A list or tuple of URL regular expressions that should be accessible without tokens. If you add a regex in this setting the middleware won't check matching paths for tokens. Default is[].SUPERUSER_GROUPstr. Members of this group will have the djangois_superuseruser flags set.STAFF_GROUPstr. Members of this group will have the djangois_staffuser flags set.MANAGE_GROUPSbool. If true the authentication backend will manage django groups for you.USE_USERNAMEbool. If true the authentication backend will lookup django users by username rather than email.LicenseMIT LicenseCopyright (c) 2020 Matt MaginPermission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.