Skip to content

Django Rest Framework - Security

Permissions

  • can use built in permissions by updating settings' DEFAULT_PERMISSION_CLASSES
  • has built in auth URL path("api-auth/", include("rest_framework.urls")),
  • can assign permissions to specific views using permission_classes

Custom Permissions

  • custom permissions should inherit from BasePermission class
    • is strongly advised to always set both has_permission and has_object_permission methods explicitly because each defaults to True
    • has_permission works on list views while detail views execute both

Authentication

Four options: basic, session, token and default

  • Basic
    • every request verifies username and password
      • inefficient
  • Session
    • uses session ids to verify authentication
    • a stateful approach because session ids must be maintained on both server and client
    • is generally not advised to use session based auth for any API that will have more than one front end
    • sessions cannot cross domains only the domain where the initial login occurred
  • Token
    • most popular option currently
    • stateless auth
    • once credentials are verified a token is generated and then returned and stored by the client
      • the server does not keep a record of the user, only whether a token is valid or not
    • best practice is to store tokens in a cookie with the httpOnly and Secure cookie flags
    • tokens can cross domains and represent a user on a website and mobile app
    • tokens can grow in size and become a performance issue
    • JSON Web Tokens (JWTs)
      • a newer form of token containing cryptographically signed JSON data
      • originally designed for use in OAuth
  • third party packages
    • django-allauth
      • comes with user registration endpoints
      • allows for social auth via google, etc.
      • can be updated to handle registration confirmation emails
    • dj-rest-auth

JWT Tokens

  • login
    • get an access_token returned
    • get a refresh_token returned in Headers
  • for authenticated API requests like the /me/ and /logout/ endpoint the access_token is passed as an Authorization header Authorization: Bearer
  • the refresh_token is only used to get a new access_token
    • access_token is returned in Headers