Package: oidc-drf
OverviewDjango DRF OIDC Auth library Securely authenticate users using OIDC in Django DRF.
It Supports Code Flow and Code Flow With PKCE. Easy integration with React Js or any front-end framework.InstallationInstall usingpip...pipinstalloidc_drfAdd'oidc_drf'to yourINSTALLED_APPSsetting.INSTALLED_APPS=[...'oidc_drf',]Configure the following settings in your Django project's settings module:OIDC_RP_CLIENT_ID=''# requiredOIDC_RP_CLIENT_SECRET=''# optional if public clientOIDC_OP_AUTHORIZATION_ENDPOINT=''# requiredOIDC_OP_TOKEN_ENDPOINT=''# requiredOIDC_OP_USER_ENDPOINT=''# requiredOIDC_OP_LOGOUT_ENDPOINT=''# requiredOIDC_AUTHENTICATION_SSO_CALLBACK_URL=''# required - identity provider will redirect you to this url after login# Django Rest Framework settingsREST_FRAMEWORK={'DEFAULT_AUTHENTICATION_CLASSES':['oidc_drf.drf.OIDCAuthentication',# This is important to be the first one],}# Authentication backendsAUTHENTICATION_BACKENDS=['oidc_drf.backends.OIDCAuthenticationBackend',]Next, edit your urls.py and add the following:fromdjango.urlsimportpath,includeurlpatterns=[# ...path('oidc/',include('oidc_drf.urls')),# ...]finnaly run the migrations commandspython3manage.pymakemigrations
python3manage.pymigrateThat's it, we're done!EXTRA SETTINGSthose settings are optional and populated with default values.OIDC_USE_NONCE=True# defalut trueOIDC_USE_PKCE=True# defalut true# For RS256 algorithm to work, you need to set either the OP signing key or the OP JWKS Endpoint.OIDC_RP_IDP_SIGN_KEY=None# defalut NoneOIDC_OP_JWKS_ENDPOINT=None# defalut NoneOIDC_USERNAME_CLAIM='preferred_username'# defalut 'preferred_username'OIDC_RP_SIGN_ALGO='HS256'# defalut HS256OIDC_RP_SCOPES='openid email profile'# defalut openidOIDC_VERIFY_SSL=True# defalut TrueOIDC_TIMEOUT=None# defalut NoneOIDC_PROXY=None# defalut NoneOIDC_USERNAME_ALGO=None# defalut NoneOIDC_USE_ENCODED_USERNAME=None# defalut NoneOIDC_CREATE_USER=True# defalut True, Enables or disables automatic user creation during authenticationOIDC_CHECK_USER_MODEL=True# defalut True, if it is set to false it can authenticated based on oidc without UserOIDC_VERIFY_KID=True# defalut TrueOIDC_ALLOW_UNSECURED_JWT=False# defalut FalseOIDC_TOKEN_USE_BASIC_AUTH=False# defalut FalseOIDC_USER_CREATED_IS_ACTIVE=True# defalut True created user by oidc is set to is_active TrueOIDC_USER_CREATED_IS_SUPERUSER=False# defalut False  created user by oidc is set to is_superuser FalseOIDC_SUPPORTED_ALGO=['RS256']# defalut ['RS256']OIDC_TRUSTED_AUDIENCE=['account']# defalut ['account']OIDC_ISSUER='http://keycloak:8080/realms/mol'# this is required to validate the token# you can map the info comming back from the IDP to user model# defalut is {}OIDC_FIELD_MAPPING={'field_in_my_user_model':'field_in_in_oidc','first_name':'given_name','last_name':'family_name',}OIDC_EXTRA_USER_FIELDS={"is_active":True,"is_superuser":False,# Add more fields as needed}Django AdminTo view the info or fields comming back from the IDP in order to do proper mapping for OIDC_FIELD_MAPPING, all the data saved under the user model as oidc extra data.Below:Screenshot from the django adminREST APIsThe REST API to the OIDC DRF is described below.AUTH ENDPOINTNoteIfOIDC_USE_PKCEis set toTrue:You should addcode_challengeandcode_challenge_methodparameters to the authentication endpoint.You should save thecode_verifierin local storage because it will be needed in the callback and refresh endpoints.IfOIDC_USE_NONCEis set toTrue:You should add thenonceparameter to the authentication endpoint.You should save thenoncein local storage because it will be needed in the callback endpoint.To generate thecode_challengeandnonce, refer to this JavaScript library:oidc_pkce.Example request with parameters:RequestGET /oidc/auth/curl --location 'http://localhost:8000/oidc/auth?code_challenge=4qZTfBVpD5xkxUIw0srf5rVV5H418hr-xQJLAd4c2Ss&code_challenge_method=S256&nonce=cFYLOJXZ8CANDC1SdQbvfUobixJdgUIc'ResponseStatus: 200 OK
{
    "redirect_url": "http://127.0.0.1:8080/realms/mol/protocol/openid-connect/auth?response_type=code&client_id=mowaamah&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fcallback&scope=openid+email&state=rhG5l83rwd81SytApbl7MzrTDBFRXqbo&nonce=cFYLOJXZ8CANDC1SdQbvfUobixJdgUIc&code_challenge=4qZTfBVpD5xkxUIw0srf5rVV5H418hr-xQJLAd4c2Ss0&code_challenge_method=S256"
}CALLBACK ENDPOINTNoteIfOIDC_USE_PKCEis set toTrue:you should include the "code_verifier" parameter in the request body.IfOIDC_USE_NONCEis set toTrue:you should include the "nonce" parameter in the request body.Remember to pass all the parameters returned from the 'OIDC_AUTHENTICATION_SSO_CALLBACK_URL', such asstate,session_state, andcode, to the callback endpoint.Example request with parameters and request body:RequestPOST /oidc/callback/curl --location 'http://localhost:8000/oidc/callback/?state=alksdfjlka&session_state=alsdjflajsdk&code=alsdjflaksdflkjls' \
--header 'Content-Type: application/json' \
--data '{
        "nonce": "cFYLOJXZ8CANDC1SdQbvfUobixJdgUIc",
        "code_verifier": "cNa9FYCujvVibPnosk1Fk3wvPPisaTjE8Ns83X0UcGsNlEfIUc3j49hFftYPEGAb"
}'ResponseStatus: 200 OK
{
   "access":"jwt access token",
   "refresh":"jwt refresh token",
}REFRESH ENDPOINTNoteIfOIDC_USE_PKCEis set toTrue:you should include the "code_verifier" parameter in the request body.RequestPOST /oidc/refresh/Example request with request body:curl --location 'http://localhost:8000/oidc/refresh/' \
--header 'Content-Type: application/json' \
--data '{
    "refresh": "jwt refresh token",
    "code_verifier": "cNa9FYCujvVibPnosk1Fk3wvPPisaTjE8Ns83X0UcGsNlEfIUc3j49hFftYPEGAb"
    }'ResponseStatus: 200 OK
{
   "access":"jwt access token",
   "refresh":"jwt refresh token",
}LOGOUT ENDPOINTRequestPOST /oidc/logout/curl --location 'http://localhost:8000/api/v1/oidc/logout' \
--data '{"refresh": "jwt refresh token"}'ResponseStatus: 200 OK
{
    "message": "Logout OIDC Successful"
}