django logo
python logo

Django/Python API: Role-Based Access Control Code Sample

v3
Published on November 19, 2021

This code sample demonstrates how to implement Role-Based Access Control (RBAC) in a Django API server using Auth0 by Okta. This code sample shows you how to accomplish the following tasks:

  • Create permissions, roles, and users in the Auth0 Dashboard.

  • Use Django permission classes to enforce API security policies.

  • Perform Role-Based Access Control (RBAC) in Django using a token-based authorization strategy powered by JSON Web Tokens (JWTs).

  • Validate access tokens in JSON Web Token (JWT) format using Django authentication classes.

  • Request resources that require different access levels from a secure API server.

Code Sample Specs

This code sample uses the following main tooling versions:

  • Django v3.2.8

  • Pythonv3.7+

Quick Auth0 Set Up

First and foremost, if you haven't already, sign up for an Auth0 account to connect your API with the Auth0 Identity Platform.

Next, you'll connect your API with Auth0. You'll need to create an API registration in the Auth0 Dashboard and get two configuration values: the Auth0 Audience and the Auth0 Domain.

Get the Auth0 audience

  • Open the APIs section of the Auth0 Dashboard.

  • Click on the Create API button and fill out the "New API" form with the following values:

Name

Name
Hello World API Server
Identifier
https://hello-world.example.com
  • Click on the Create button.
Visit the "Register APIs" document for more details.

When setting up APIs, we also refer to the API identifier as the Audience value. Store that value in the following field to set up your API server in the next section:

Get the Auth0 domain

Now, follow these steps to get the Auth0 Domain value.

  • Open the Auth0 Domain Settings

  • Locate the bold text in the page description that follows this pattern: tenant-name.region.auth0.com. That's your Auth0 domain!

  • Paste the Auth0 domain value in the following field so that you can use it in the next section to set up your API server:

The region subdomain (au, us, or eu) is optional. Some Auth0 Domains don't have it.

Set Up and Run the Django Project

Ensure that you have Python v3.7 or higher installed in your machine.

Start by cloning the Django project:

COMMAND
git clone https://github.com/auth0-developer-hub/api_django_python_hello-world.git

Make the project directory your current working directory:

COMMAND
cd api_django_python_hello-world

Then, check out the basic-role-based-access-control branch, which holds all the code related to implementing token-based authorization to protect resources in a Django API:

COMMAND
git checkout basic-role-based-access-control

Create a virtual environment under the root project directory using the appropriate command for your operating system:

MACOS
WINDOWS
LINUX
python3 -m venv venv

Then, activate the virtual environment:

MACOS
WINDOWS
LINUX
. venv/bin/activate

Install the Django project dependencies:

COMMAND
pip install -r requirements.txt

Use the following command to generate a random secret key for Django:

COMMAND
python -c "from django.core.management.utils import get_random_secret_key;print(get_random_secret_key())"

Store the output from the command above in the following field:

Now, create a .env file under the project directory and populate it as follows:

.env
DJANGO_SECRET_KEY=KEY-VALUE
CLIENT_ORIGIN_URL=http://localhost:4040
PORT=6060
DEBUG_ENABLE=false
AUTH0_DOMAIN=AUTH0-DOMAIN
AUTH0_AUDIENCE=AUTH0-AUDIENCE

With the .env file all set up, run the database migrations:

COMMAND
python manage.py migrate

Finally, execute the following command to run the Django server:

COMMAND
gunicorn

Set Up Role-Based Access Control (RBAC)

Within the context of Auth0, Role-based access control (RBAC) systems assign permissions to users based on their role within an organization. Everyone who holds that role has the same set of access rights. Those who hold different roles have different access rights.

Developers who use Role-based access control (RBAC) for access management can mitigate the errors that come from assigning permissions to users individually.

You can use the Auth0 Dashboard to enable Role-Based Access Control (RBAC) in any API that you have already registered with Auth0. You then implement RBAC by creating API permissions, assigning those permissions to a role, and assigning that role to any of your users.

Whenever a user logs in to one of your client applications, the Auth0 authorization server issues an access token that the client can use to make authenticated requests to an API server. Auth0 authorization servers issue access tokens in JSON Web Token (JWT) format.

When you enable Auth0 Role-Based Access Control (RBAC) for an API, the access token will include a permissions claim that has all the permissions associated with any roles that you have assigned to that user.

For this particular API code sample, the access token present in the authorization header of a request must include a permissions claim that contains the read:admin-messages permission to access the GET /api/messages/admin endpoint.

Enable Role-Based Access Control (RBAC)

  • Open the APIs section of the Auth0 Dashboard and select your "Hello World API Server" registration.

  • Click on the "Settings" tab and locate the "RBAC Settings" section.

  • Switch on the "Enable RBAC" and "Add Permissions in the Access Token" options.

Visit the "Role-Based Access Control" document for more details.

Create an API permission

In the same Auth0 API registration page, follow these steps:

  • Click on the "Permissions" tab and fill a field from the "Add a Permission (Scope)" section with the following information:
Permission (Scope)
read:admin-messages
Description
Read admin messages
  • Click the "+ Add" button to store the permission.
Visit the "Add API Permissions" document for more details.

Create a role with permissions

Create a role

  • Open the User Management > Roles section of the Auth0 Dashboard.

  • Click on the Create role button and fill out the "New Role" form with the following values:

Name
messages-admin
Description
Access admin messaging features
  • Click on the Create button.
Visit the "Create Roles" document for more details.

Add permissions to the role

  • Click on the "Permissions" tab of the roles page.

  • Click on the "Add Permissions" button.

  • Select the "Hello World API Server" from the dropdown menu that comes up and click the "Add Permissions" button.

  • Select all the permissions available by clicking on them one by one or by using the "All" link.

  • Finally, click on the "Add Permissions" button to finish up.

Visit the "Add Permissions to Roles" document for more details.

Create an admin user

  • Open the User Management > Users section from the Auth0 Dashboard.

  • Click on the "Create user" button and fill out the form with the required information. Alternatively, you can also click on any of your existing users to give one of them the admin role.

  • On the user's page, click on the "Roles" tab and then click on the "Assign Roles" button.

  • Select the messages-admin role from the dropdown menu and click on the "Assign" button.

Visit the "Assign Roles to Users" document for more details.

Access the Admin Endpoint

Let's test access to the GET /api/messages/admin endpoint by simulating a real user login and requesting that protected resource using a real access token.

You can pair this API server with a client application that matches the technology stack that you use at work. Any "Hello World" client application can communicate with this "Hello World" API server sample.

When you log in to a "Hello World" client application as a user who has the messages-admin role, your access token will have the required permissions to access the GET /api/messages/admin endpoint.

You can simulate a secure full-stack application system in no time. Each client application sample gives you clear instructions to get it up and running quickly.

Pick a Single-Page Application (SPA) code sample in your preferred frontend framework and language:

angular
typescript
Angular Standalone Components Code Sample:Basic Authentication
This code sample uses Angular Standalone Components with TypeScript to implement single-page application authentication using the Auth0 Angular SDK.
angular
typescript
Angular Code Sample:Basic Authentication
This code sample uses Angular with TypeScript to implement single-page application authentication using the Auth0 Angular SDK.
react
javascript
React Router 6 Code Sample:Basic Authentication
Code sample showing how to protect a simple React single-page application using React Router 6, Auth0, and JavaScript.
react
typescript
React Router 6/TypeScript Code Sample:Basic Authentication
Code sample showing how to protect a simple React single-page application using React Router 6, Auth0, and TypeScript.
react
javascript
React Code Sample:Basic Authentication
JavaScript code that implements user login, logout and sign-up features to secure a React Single-Page Application (SPA) using Auth0.
react
typescript
React/TypeScript Code Sample:Basic Authentication
Code sample of a simple React single-page application built TypeScript that implements authentication using Auth0.
svelte
javascript
Svelte Code Sample:Basic Authentication
JavaScript code that implements user login, logout and sign-up features to secure a Svelte Single-Page Application (SPA), using routing middleware.
vue
javascript
Vue.js Composition API Code Sample:Basic Authentication
This code sample uses Vue.js 3 with JavaScript and the Composition API to implement single-page application authentication using the Auth0 Vue SDK.
vue
javascript
Vue.js Options API Code Sample:Basic Authentication
This code sample uses Vue.js 3 with JavaScript and the Options API to implement single-page application authentication using the Auth0 Vue SDK.
vue
javascript
Vue.js 2 Code Sample:Basic Authentication
This code sample uses Vue.js 2 with JavaScript to implement single-page application authentication using the Auth0 SPA SDK.

Once you set up the client application, log in and visit the guarded "Admin" page (http://localhost:4040/admin).

When you log in to a "Hello World" client application as a user who has the messages-admin role, your access token will have the required permissions to access the GET /api/messages/admin endpoint, and you'll get the following response:

{
"text": "This is an admin message."
}

However, when you log in as a user who doesn't have the messages-admin role, you'll get a 403 Forbidden status code and the following response:

{
"message": "Permission denied"
}