Package: django-oauth2-authcodeflow
SummaryAuthenticate with any OpenId Connect/Oauth2 provider through authorization code flow withDjango.Supported protocols:Oauth 2.0PKCEOpenIDConnect 1.0WordingOP = OpenId Connect Provider, the auth serverRP = Relying Party, the client, your applicationSetupaddoauth2_authcodeflowto theINSTALLED_APPS(afterdjango.contrib.authanddjango.contrib.sessionsapps)addpath('oidc/', include('oauth2_authcodeflow.urls')),in your globalurls.pyfile.You can change the path prefix to what you wantaddoauth2_authcodeflow.auth.AuthenticationBackendto theAUTHENTICATION_BACKENDSconfig.You can keepdjango.contrib.auth.backends.ModelBackendas a second-fallback auth mechanism.get your callback urls by doing:./manage.pyoidc_urls[--secure]<HOST_NAME>Configure your application on the OpenId Connect Provider.This should give you aclient_idand asecret_id.You will need to fill theredirect_urlandlogout_urlthere.Ensue to include thesid, email, first name, last name (if applicable) parameters in the id token claims on the OP.Ensure thatdjango.contrib.sessions.middleware.SessionMiddlewareis inMIDDLEWAREMinimal configurationSESSION_COOKIE_SECUREtoTrueif your Django is served throughHTTPSOIDC_OP_DISCOVERY_DOCUMENT_URLto the well-known openid configuration url of the OPOIDC_RP_CLIENT_IDclient id provided by the OPOIDC_RP_CLIENT_SECRETsecrect id provided by the OPLoginGet your browser/frontend to go to theoidc_authenticationpage name (/oidc/authenticateby default) with the following parameters:next: the url to redirect on successfail: the url to redirect on failure,errorquery string may contain an error descriptionLogoutGet your browser/frontend to go to theoidc_logoutpage name (/oidc/logoutby default) with the following parameters:next: the url to redirect on successfail: the url to redirect on failure,errorquery string may contain an error descriptionLogout from the OP as wellThis will logout the user from the application but also from the OP (if user say yes) and the OP should also logout the user from all other apps connected to this OP.The spec is not well followed by the OP, so you mileage may vary.Get your browser/frontend to go to theoidc_total_logoutpage name (/oidc/total_logoutby default) with the following parameters:next: the url to redirect on successfail: the url to redirect on failure,errorquery string may contain an error descriptionProtect your urlsAt least three options are possible.Use default django way tolimit access to logged-in usersby definingLOGIN_URLin your settings and andlogin_requireddecorators in your views.# settings.pyfromdjango.urlsimportreverse_lazyfromdjango.utils.textimportformat_lazyLOGIN_URL=format_lazy('{url}?fail=/',url=reverse_lazy(OIDC_URL_AUTHENTICATION_NAME))# urls.pyfromdjango.contrib.auth.decoratorsimportlogin_requiredpath('restricted_url/',login_required(your_view)),A slightly different version, by directly and only using thelogin_requiredfromoauth2_authcodeflow.utils.Use theLoginRequiredMiddlewarewithOIDC_MIDDLEWARE_NO_AUTH_URL_PATTERNSconfiguration.Optional middlewaresYou can add some middlewares to add some features:oauth2_authcodeflow.middleware.LoginRequiredMiddlewareto automaticaly force a login request to urls not inOIDC_MIDDLEWARE_NO_AUTH_URL_PATTERNSif not authenticated.oauth2_authcodeflow.middleware.RefreshAccessTokenMiddlewareto automaticaly refresh the access token when it’s expired.oauth2_authcodeflow.middleware.RefreshSessionMiddlewareto automaticaly ask for a new id token when it’s considered expired.oauth2_authcodeflow.middleware.BearerAuthMiddlewareto authenticate the user usingAuthorizationHTTP header (API, scripts, CLI usage).LoginRequiredMiddlewarewill refresh to the original page uppon user logged-in.RefreshAccessTokenMiddlewareandRefreshSessionMiddlewarewill try the refresh and return a redirect to the same page (or the one configured as next in the login phase) if the refresh cannot happen.Use them to silently refresh your access/id tokens.BearerAuthMiddleware will useoauth2_authcodeflow.auth.BearerAuthenticationBackendto authenticate the user based onAuthorizationHTTP header instead of using the sessions.Use this to allow to authenticate without cookies/session. You then need to login withfrom_cli=1in yourloginurl. You then needs to go to the displayed url with a browser and copy the result http header to make further requests.SignalsOne can use Djangouser_logged_inanduser_logged_outsignalsto know and act when a user is logged in or disconnected.Full configurationSecure session cookie settings:SESSION_COOKIE_AGEto a reasonable time (default 2 weeks)SESSION_COOKIE_HTTPONLYmustbeTrue(defaultTrue)SESSION_COOKIE_PATHbe sure to use/to prevent some weird behavior (default/)SESSION_COOKIE_SAMESITEshouldbeLax(defaultLax)SESSION_COOKIE_SECUREshouldbeTrueinhttpscontext (defaultFalse)Specific OIDC settings:SettingsDescriptionDefaultOIDC_OP_DISCOVERY_DOCUMENT_URLURL of your OpenID connect Provider discovery document url (recommended).If you provide this, the following configs will be ignored:-OIDC_OP_AUTHORIZATION_URL-OIDC_OP_TOKEN_URL-OIDC_OP_USERINFO_URL-OIDC_OP_JWKS_URLNoneOIDC_OP_AUTHORIZATION_URLURL of your OpenID connect Provider authorization endpoint (not recommended,OIDC_OP_DISCOVERY_DOCUMENT_URLis preferred).NoneOIDC_OP_TOKEN_URLURL of your OpenID connect Provider token endpoint (not recommended,OIDC_OP_DISCOVERY_DOCUMENT_URLis preferred).NoneOIDC_OP_USERINFO_URLURL of your OpenID connect Provider userinfo endpoint (not recommended,OIDC_OP_DISCOVERY_DOCUMENT_URLis preferred).NoneOIDC_OP_JWKS_URLURL of your OpenId connect Provider endpoint to get public signing keys (inPEMorDERformat).This is used to verify theid_token.This isnot recommendedto provide this url here but rather useOIDC_OP_DISCOVERY_DOCUMENT_URLconfig.NoneOIDC_OP_END_SESSION_URLURL of your OpenID connect Provider end session endpoint (not recommended,OIDC_OP_DISCOVERY_DOCUMENT_URLis preferred).NoneOIDC_OP_FETCH_USER_INFOFetch user info on login or not.TrueOIDC_OP_TOTAL_LOGOUTDo a call to total logout will call the OP for a logout. Default true.Be careful, some OP will not follow the RFC and will not allow the user to NOT logout all connected apps.Azure is such a bad example.TrueOIDC_OP_EXPECTED_EMAIL_CLAIMexpected email key.'email'OIDC_OP_EXPECTED_CLAIMSOIDC_OP_EXPECTED_EMAIL_CLAIMvalue is automatically included in this list.[]OIDC_RP_CLIENT_IDOpenID Connect client ID provided for your Relaying Party/client by your OpenIdConnect ProviderOIDC_RP_CLIENT_SECRETOpenID Connect client secret provided for your Relaying Party/client by your OpenIdConnect Provider.Could be empty in PKCE case.OIDC_RP_USE_PKCEPKCEimprove security, disable it only if your provider cannot handle it.TrueOIDC_RP_FORCE_CONSENT_PROMPTForce to ask for consent on login, even ifoffline_accessis not in scopesFalseOIDC_RP_SCOPESThe OpenID Connect scopes to request during login.The scopes could be usefull later to get access to other ressources.openidmust be in the list.You can also include theemailscope to ensure that the email field will be in the claims (recommended).You can also include theprofilescope to get more (like names, …) info in theid_token(recommended).You can also get arefresh_tokenby specifying theoffline_accessscope.['openid', 'email', 'profile', 'offline_access']OIDC_RP_USERINFO_CLAIMSOpenID Connect authorizationrequest parameteruserinfomemberto optionaly add to id token request (dict type).NoneOIDC_RP_TOKEN_CLAIMSOpenID Connect authorizationrequest parameterid_tokenmemberto optionaly add to id token request (dict type).NoneOIDC_RP_SIGN_ALGOS_ALLOWEDSets the algorithms the IdP may use to sign ID tokens.Typical values arHS256(no key required) andRS256(public key required)The public keys might be defined inOIDC_RP_IDP_SIGN_KEYor deduced using theOIDC_OP_JWKS_URLconfig.['HS256', 'HS384', 'HS512', 'RS256', 'RS384', 'RS512']OIDC_RP_IDP_SIGN_KEYPublic RSA used to verify signatures. Overrides keys from JWKS endpoint.Should be inPEMorDERformat.NoneOIDC_CREATE_USEREnables or disables automatic user creation during authenticationTrueOIDC_RANDOM_SIZESets the length of the random string used in the OAuth2 protocol.32OIDC_PROXYDefines a proxy for all requests to the OpenID Connect provider (fetch JWS, retrieve JWT tokens, Userinfo Endpoint).The default is set toNonewhich means the library will not use a proxy and connect directly.For configuring a proxy check the Python requests documentation:https://requests.readthedocs.io/en/master/user/advanced/#proxiesNoneOIDC_TIMEOUTDefines a timeout for all requests to the OpenID Connect provider (fetch JWS, retrieve JWT tokens, Userinfo Endpoint).The default is set toNonewhich means the library will wait indefinitely.The time can be defined as seconds (integer).More information about possible configuration values, see Python requests:https://requests.readthedocs.io/en/master/user/quickstart/#timeoutsNoneOIDC_REDIRECT_OK_FIELD_NAMESets the GET parameter that is being used to define the redirect URL after succesful authentication'next'OIDC_REDIRECT_ERROR_FIELD_NAMESets the GET parameter that is being used to define the redirect URL after failed authentication'fail'OIDC_DJANGO_USERNAME_FUNCFunction or dotted path to a function that compute the django username based on claims.The username should be unique for this app.The default is to use a base64 url encode of the email hash (sha1).get_default_django_usernameOIDC_EMAIL_CLAIMClaim name for emailNonevalue means useOIDC_OP_EXPECTED_EMAIL_CLAIMvalueYou can also provide a lambda that takes all the claims as argument and return an emailNoneOIDC_FIRSTNAME_CLAIMYou can also provide a lambda that takes all the claims as argument and return a firstname'given_name'OIDC_LASTNAME_CLAIMYou can also provide a lambda that takes all the claims as argument and return a lastname'family_name'OIDC_EXTEND_USERCallable that takes theuser, theclaimsand optionaly therequestandaccess_tokenas arguments and that can extend user properties.You can also specify a dotted path to a callable.NoneOIDC_UNUSABLE_PASSWORDScramble the password on each SSO connection/renewal.IfFalse, it will only scramble it when creating an accountTrueOIDC_BLACKLIST_TOKEN_TIMEOUT_SECONDS7 days by default7 * 86400OIDC_AUTHORIZATION_HEADER_PREFIXOnly used when using authorization in header:Authorization: Bearer id_tokenThis is only possible ifoauth2_authcodeflow.middleware.BearerAuthMiddlewarehas been added toMIDDLEWAREsetting list.'Bearer'OIDC_MIDDLEWARE_NO_AUTH_URL_PATTERNSTheRefreshAccessTokenMiddlewareandRefreshSessionMiddlewarewill use this list to bypass auth checks.Any url listed here will not be tried to be authenticated using Auth Code Flow.You should include at least any failure/error or admin urls in it.[]OIDC_MIDDLEWARE_LOGIN_REQUIRED_REDIRECTRedirect to login page if not authenticated when usingLoginRequiredMiddleware.TrueOIDC_MIDDLEWARE_API_URL_PATTERNSTheRefreshAccessTokenMiddlewareandRefreshSessionMiddlewarewill use this list to answer JSON response in case of refresh failure.Expected list of regexp URL patterns.['^/api/']OIDC_MIDDLEWARE_SESSION_TIMEOUT_SECONDS7 days by default7 * 86400