Giter Site home page Giter Site logo

api_django_python_hello-world's Introduction

Hello World API: Django + Python Sample

You can use this sample project to learn how to secure a simple Django API server using Auth0.

The starter branch offers a working API server that exposes three public endpoints. Each endpoint returns a different type of message: public, protected, and admin.

The goal is to use Auth0 to only allow requests that contain a valid access token in their authorization header to access the protected and admin data. Additionally, only access tokens that contain a read:admin-messages permission should access the admin data, which is referred to as Role-Based Access Control (RBAC).

Check out the add-authorization branch to see authorization in action using Auth0.

Check out the add-rbac branch to see authorization and Role-Based Access Control (RBAC) in action using Auth0.

Get Started

Prerequisites:

  • Python >= 3.7

Initialize a python virtual environment:

python3 -m venv venv
source ./venv/bin/activate

Install the project dependencies:

pip install -r requirements.txt

Setup virtual environments: Copy the .env.example file to .env and edit it to populate its variables.

cp .env.example .env

Run the following command to generate a random secret key and add it to your .env file.

python manage.py generate_secret

# .env
DJANGO_SECRET_KEY=<generated_key>

Run DB migrations:

python manage.py migrate

Run the project:

gunicorn

Security Configuration

HTTP Headers

  • X-XSS-Protection

    Default set to 0.

    See the documentation for more details.

  • HTTP Strict Transport Security (HSTS)

    Disabled by default, so we need to add this configuration:

    SECURE_HSTS_INCLUDE_SUBDOMAINS = True
    SECURE_HSTS_SECONDS = 31536000

    See the documentation for more details.

  • X-Frame-Options (XFO)

    Default set to DENY.

    See the documentation for more details.

  • X-Content-Type-Options

    Default set to nosniff.

    See the documentation for more details.

  • Content-Security-Policy (CSP)

    Not enabled by default, we need to install the django-csp dependency and add it to the MIDDLEWARES. It comes pre-configured with the directives:

    • default-src: self
    • frame-ancestors: none

    See the documentation for more details.

  • Cache-Control

    We need to add a custom middleware to call add_never_cache_headers on all responses. This will add the header:

    Cache-Control: max-age=0, no-cache, no-store, must-revalidate, private
    

    See the documentation for more details.

  • Content-Type

    By setting the default renderer to JSONRenderer, it will use utf-8 encoding by default.

    See the documentation for more details.

Remove HTTP Headers

  • X-Powered-By: Not added by Django.
  • Server: There is no easy way to remove this header since it's mostly the responsibility of the environment server. On development it doesn't matter, but on production its usually NGINX, Apache, etc. which handles this header.

CORS

Django doesn't have CORS built-in, so we need to install the django-cors-headers dependency and add the configuration needed on the settings.

It comes pre-configured with:

  • Access-Control-Max-Age: 86400

See the documentation for more details.

API Endpoints

The API server defines the following endpoints:

๐Ÿ”“ Get public message

GET /api/messages/public

Response

Status: 200 OK
{
  "text": "The API doesn't require an access token to share this message."
}

๐Ÿ”“ Get protected message

You need to protect this endpoint using Auth0.

GET /api/messages/protected

Response

Status: 200 OK
{
  "text": "The API successfully validated your access token."
}

๐Ÿ”“ Get admin message

You need to protect this endpoint using Auth0 and Role-Based Access Control (RBAC).

GET /api/messages/admin

Response

Status: 200 OK
{
  "text": "The API successfully recognized you as an admin."
}

Error Handling

400s errors

Status: Corresponding 400 status code
{
  "message": "Not Found"
}

Request without authorization header

curl localhost:6060/api/messages/admin
{
  "message":"Authentication credentials were not provided.",
}

HTTP Status: 401

Request with malformed authorization header

curl localhost:6060/api/messages/admin --header "authorization: <valid_token>"
{
  "message":"Authentication credentials were not provided.",
}

HTTP Status: 401

Request with wrong authorization scheme

curl localhost:6060/api/messages/admin --header "authorization: Basic <valid_token>"
{
  "message":"Authentication credentials were not provided.",
}

HTTP Status: 401

Request without token

curl localhost:6060/api/messages/admin --header "authorization: Bearer"
{
  "message":"Authorization header must contain two space-delimited values",
}

HTTP Status: 401

JWT validation error

curl localhost:6060/api/messages/admin --header "authorization: Bearer asdf123"
{
  "message":"Given token not valid for any token type",
}

HTTP Status: 401

Token without required permissions

curl localhost:6060/api/messages/admin --header "authorization: Bearer <token_without_permissions>"
{
  "error":"insufficient_permissions",
  "error_description":"You do not have permission to perform this action.",
  "message":"Permission denied"
}

HTTP Status: 403

500s errors

Status: 500 Internal Server Error
{
  "message": "Server Error"
}

api_django_python_hello-world's People

Contributors

maylonpedroso avatar mmena1 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.