Close Menu
    DevStackTipsDevStackTips
    • Home
    • News & Updates
      1. Tech & Work
      2. View All

      This week in AI updates: Mistral’s new Le Chat features, ChatGPT updates, and more (September 5, 2025)

      September 6, 2025

      Designing For TV: Principles, Patterns And Practical Guidance (Part 2)

      September 5, 2025

      Neo4j introduces new graph architecture that allows operational and analytics workloads to be run together

      September 5, 2025

      Beyond the benchmarks: Understanding the coding personalities of different LLMs

      September 5, 2025

      Hitachi Energy Pledges $1B to Strengthen US Grid, Build Largest Transformer Plant in Virginia

      September 5, 2025

      How to debug a web app with Playwright MCP and GitHub Copilot

      September 5, 2025

      Between Strategy and Story: Thierry Chopain’s Creative Path

      September 5, 2025

      What You Need to Know About CSS Color Interpolation

      September 5, 2025
    • Development
      1. Algorithms & Data Structures
      2. Artificial Intelligence
      3. Back-End Development
      4. Databases
      5. Front-End Development
      6. Libraries & Frameworks
      7. Machine Learning
      8. Security
      9. Software Engineering
      10. Tools & IDEs
      11. Web Design
      12. Web Development
      13. Web Security
      14. Programming Languages
        • PHP
        • JavaScript
      Featured

      Why browsers throttle JavaScript timers (and what to do about it)

      September 6, 2025
      Recent

      Why browsers throttle JavaScript timers (and what to do about it)

      September 6, 2025

      How to create Google Gemini AI component in Total.js Flow

      September 6, 2025

      Drupal 11’s AI Features: What They Actually Mean for Your Team

      September 5, 2025
    • Operating Systems
      1. Windows
      2. Linux
      3. macOS
      Featured

      Harnessing GitOps on Linux for Seamless, Git-First Infrastructure Management

      September 6, 2025
      Recent

      Harnessing GitOps on Linux for Seamless, Git-First Infrastructure Management

      September 6, 2025

      How DevOps Teams Are Redefining Reliability with NixOS and OSTree-Powered Linux

      September 5, 2025

      Distribution Release: Linux Mint 22.2

      September 4, 2025
    • Learning Resources
      • Books
      • Cheatsheets
      • Tutorials & Guides
    Home»Development»How to Create a JSON Web Token in the Django Rest Framework

    How to Create a JSON Web Token in the Django Rest Framework

    April 17, 2025

    When you’re building an API, security should be at the top of your list. You want to make sure only the right people can access the right stuff – and that’s where authentication comes in.

    One of the most common and reliable ways to handle authentication in modern web apps is using JWT, short for JSON Web Tokens.

    If you’re working with the Django Rest Framework (DRF), you might already know that it comes with a lot of helpful tools for building APIs.

    But when it comes to token-based authentication, you’ll need to bring in a bit of extra help. JWT isn’t built into DRF by default, but it’s super easy to set up once you know the steps.

    In this tutorial, I’ll walk you through exactly how to create and use JWTs in the Django Rest Framework step by step.

    Table of Contents:

    1. What is a JWT?

    2. Why Use JWT in the Django Rest Framework?

    3. How to Set Up JWT in the Django Rest Framework

    4. How to Use These Tokens

    5. FAQs

    6. Best Practices

    7. Final Thoughts

    What is a JWT?

    A JWT (JSON Web Token) is a compact, self-contained way to send information securely between two parties. It’s often used for authentication.

    When someone logs in, they get a token. That token gets stored in the frontend (like in localStorage), and every time the user makes a request, it’s sent along with it.

    The server checks that token, and if everything’s okay, it gives access to the requested data. No need for cookies or sessions.

    A JWT is made of three parts:

    1. Header – contains the type of token and the signing algorithm.

    2. Payload – contains the data (like user ID).

    3. Signature – used to verify the token wasn’t changed.

    Why Use JWT in the Django Rest Framework?

    Here’s why JWT is a solid choice for DRF apps:

    • Stateless: No sessions are needed on the server.

    • Scalable: Since it’s stateless, it works well with larger applications and microservices.

    • Widely used: JWT is a common standard. Many frontend frameworks (like React, Vue, and so on) already know how to work with it.

    How to Set Up JWT in the Django Rest Framework

    Let’s get into it. Here’s how to set up JWT authentication in DRF.

    Step 1: Install Required Packages

    You’ll need a library to handle JWTs. The most popular one is djangorestframework-simplejwt.

    Run this in your terminal:

    pip install djangorestframework-simplejwt
    

    This installs everything you need to generate, refresh, and verify JSON web tokens in your DRF project.

    Step 2: Update Your Django Settings

    Go to your settings.py and update the REST_FRAMEWORK part like this:

    REST_FRAMEWORK = {
        <span class="hljs-string">'DEFAULT_AUTHENTICATION_CLASSES'</span>: (
            <span class="hljs-string">'rest_framework_simplejwt.authentication.JWTAuthentication'</span>,
        )
    }
    

    This tells DRF to look for a JWT in the request’s Authorization header and use it to authenticate the user. It replaces session-based authentication, which is typical for web apps, with token-based authentication, ideal for API’s.

    Step 3: Add Token URLS to Your urls.py

    JWT works by issuing a pair of tokens: an access token (short-lived) and a refresh token (long-lived). These tokens are managed through two main views.

    In your urls.py (usually in the root project or api app):

    <span class="hljs-keyword">from</span> django.urls <span class="hljs-keyword">import</span> path
    <span class="hljs-keyword">from</span> rest_framework_simplejwt.views <span class="hljs-keyword">import</span> (
        TokenObtainPairView,
        TokenRefreshView,
    )
    
    urlpatterns = [
        path(<span class="hljs-string">'api/token/'</span>, TokenObtainPairView.as_view(), name=<span class="hljs-string">'token_obtain_pair'</span>),
        path(<span class="hljs-string">'api/token/refresh/'</span>, TokenRefreshView.as_view(), name=<span class="hljs-string">'token_refresh'</span>),
    ]
    

    In this code:

    • /api/token/: Clients (like frontend apps or mobile apps) send user credentials to this endpoint to get access and refresh tokens.

    • /api/token/refresh/: When the access token expires, the client sends the refresh token here to get a new access token.

    Step 4: Test It Out

    Let’s say you have a user with a username and password.

    You can make a POST request to /api/token/:

    {
      <span class="hljs-attr">"username"</span>: <span class="hljs-string">"your_username"</span>,
      <span class="hljs-attr">"password"</span>: <span class="hljs-string">"your_password"</span>
    }
    

    If the credentials are correct, you’ll get back something like:

    {
      <span class="hljs-attr">"refresh"</span>: <span class="hljs-string">"long_refresh_token"</span>,
      <span class="hljs-attr">"access"</span>: <span class="hljs-string">"short_lived_access_token"</span>
    }
    

    You’ll use the access token to make authenticated requests. When it expires, send the refresh token to /api/token/refresh/ to get a new one.

    How to Use These Tokens

    Include the access token in the Authorization header of your API requests like this:

    Authorization: Bearer your_access_token_here
    

    When the access token expires, send the refresh token to /api/token/refresh/ like this:

    {
      <span class="hljs-attr">"refresh"</span>: <span class="hljs-string">"your_refresh_token_here"</span>
    }
    

    And you’ll get a new access token.

    Securing Your API Views

    To make sure only authenticated users can access certain endpoints, add the IsAuthenticated permission class to your views.

    Here’s an example:

    <span class="hljs-keyword">from</span> rest_framework.permissions <span class="hljs-keyword">import</span> IsAuthenticated
    <span class="hljs-keyword">from</span> rest_framework.views <span class="hljs-keyword">import</span> APIView
    <span class="hljs-keyword">from</span> rest_framework.response <span class="hljs-keyword">import</span> Response
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SecureView</span>(<span class="hljs-params">APIView</span>):</span>
        permission_classes = [IsAuthenticated]
    
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get</span>(<span class="hljs-params">self, request</span>):</span>
            <span class="hljs-keyword">return</span> Response({<span class="hljs-string">"message"</span>: <span class="hljs-string">"You are authenticated!"</span>})
    

    This view will only return a response if the request includes a valid JWT. If there’s no token or it’s invalid/expired, the user gets a 401 Unauthorized error.

    Summary

    Here’s what we just did:

    • Installed and configured simplejwt for DRF.

    • Set up token generation and refresh endpoints.

    • Protected views with token-based authentication.

    • Explained how to make and refresh token-based requests.

    JWT is a powerful and scalable way to secure your Django APIS. It’s perfect for modern web and mobile applications.

    Would you like a bonus step for customising token payloads (for example, adding user roles or email to the JWT)? Let me know!

    FAQs

    How long does the token last?

    By default, the access token lasts 5 minutes, and the refresh token lasts 1 day. You can customize this in your settings:

    <span class="hljs-keyword">from</span> datetime <span class="hljs-keyword">import</span> timedelta
    
    SIMPLE_JWT = {
        <span class="hljs-string">'ACCESS_TOKEN_LIFETIME'</span>: timedelta(minutes=<span class="hljs-number">15</span>),
        <span class="hljs-string">'REFRESH_TOKEN_LIFETIME'</span>: timedelta(days=<span class="hljs-number">1</span>),
    }
    

    What this means:

    • This sets how long your JWT tokens last:

      • ACCESS_TOKEN_LIFETIME: How long the access token is valid (for example, 15 minutes).

      • REFRESH_TOKEN_LIFETIME: How long the refresh token is valid (for example, 1 day).

    Why it matters:

    • The access token is what allows the user to interact with protected endpoints.

    • The refresh token is used to get a new access token without logging in again

    Where should I store the token on the frontend?

    Ideally in localStorage or sessionStorage. Just be aware of XSS risks. Don’t store sensitive data in the token itself.

    You can store the JWT access/refresh tokens on the frontend in:

    • localStorage: Data persists even after the tab/browser is closed.

    • sessionStorage: Data is lost when the tab/browser is closed.

    • Don’t store sensitive user data in the token or in storage.

    • Tokens stored in localStorage can be vulnerable to XSS attacks.

    • If possible, consider using httpOnly cookies for better security (though more complex to set up).

    Can I add custom fields to the token?

    Yes! You can override TokenObtainPairSerializer to include custom data in the payload, like so:

    <span class="hljs-keyword">from</span> rest_framework_simplejwt.serializers <span class="hljs-keyword">import</span> TokenObtainPairSerializer
    
    <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MyTokenObtainPairSerializer</span>(<span class="hljs-params">TokenObtainPairSerializer</span>):</span>
    <span class="hljs-meta">    @classmethod</span>
        <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">get_token</span>(<span class="hljs-params">cls, user</span>):</span>
            token = super().get_token(user)
            token[<span class="hljs-string">'username'</span>] = user.username
            <span class="hljs-keyword">return</span> token
    

    Then wire it up in your urls.py.

    • You’re customizing the JWT payload to include additional user info (like username).

    • This means when a user logs in, the JWT will now carry the username inside the payload.

    • This is helpful if your frontend wants to display the user’s name without making another API call.

    Summary:

    SectionPurpose
    SIMPLE_JWT settingsControls token expiration
    localStorage/sessionStorageWhere to store tokens on frontend
    Custom Token SerializerAdd extra user info to the token (e.g., username)
    urls.py configConnects your custom token view to the login endpoint

    Best Practices

    Let’s now look at some DRF best practices so you can effectively use this framework:

    1. Use HTTPS Always

    HTTPS encrypts the data transmitted between the client (browser or app) and the server. If you use HTTP instead, anyone on the same network (like public Wi-Fi) could intercept sensitive data – including access tokens – through a method called man-in-the-middle (MITM) attacks.

    Best practices:

    • Use an SSL certificate to enable HTTPS for all endpoints.

    • Redirect all HTTP requests to HTTPS.

    • Use HSTS (HTTP Strict Transport Security) headers to enforce HTTPS on the client side.

    2. Don’t Store Sensitive Data in the Token

    Tokens like JWTs are often stored client-side (in localStorage, sessionStorage, or cookies).

    If they contain sensitive data (like passwords, personal info, or secret keys), they become a major security risk – especially if stolen or compromised.

    What to do instead:

    • Store only the minimal information needed (like user ID or role).

    • Use opaque tokens (random strings) that don’t carry embedded data when possible.

    • Store sensitive data securely on the server, not in the token.

    3. Keep Your Signing Key Secret

    What’s a signing key?

    In systems using JWTs, the signing key (or secret key) is used to sign the token – a cryptographic way to ensure the token hasn’t been tampered with.

    If someone gets your signing key, they can forge valid-looking tokens and impersonate users.

    Best practices:

    • Store your key in secure environments (like environment variables, secret managers).

    • Never commit the key to source control.

    • Use strong, randomly generated secrets.

    • Consider using asymmetric keys (public/private key pairs) for better scalability and security (for example, with RS256 algorithm).

    4. Rotate Tokens If Needed

    What is token rotation?

    Token rotation refers to the process of periodically generating new tokens and invalidating the old ones.

    This is important because if a token is stolen or leaked, rotating it regularly limits the window in which the attacker can use it. It’s especially important for refresh tokens, which tend to live longer.

    Best practices:

    • Use short-lived access tokens and longer-lived refresh tokens.

    • Invalidate refresh tokens once they’re used (a practice called “refresh token rotation”).

    • Track issued refresh tokens server-side to detect reuse or theft.

    5. Set a Short Lifetime for Access Tokens & Use Refresh Tokens Wisely

    Access tokens grant permission to access protected resources. If stolen, they can be used by attackers until they expire.

    Best practices:

    • Set access tokens to expire quickly (5–15 minutes is common).

    • Use refresh tokens to allow the client to get new access tokens without re-logging in.

    • Store refresh tokens securely (prefer HTTP-only cookies).

    • Revoke refresh tokens on logout, suspicious activity, or device changes.

    Final Thoughts

    • Access tokens should be short-lived and limited in scope.

    • Refresh tokens should be long-lived but rotated and revoked carefully.

    • Always store secrets securely, serve over HTTPS, and avoid trusting the client with sensitive logic or data.

    Would you like me to show how this all ties together in an example flow (like how a login, token issuance, and refresh works)?

    JWTS make authentication easier and more scalable for APIS. Once you set it up in the Django Rest Framework, it just works – and you’ve got a secure way to let users in and keep unwanted traffic out.

    It’s a must-know if you’re building APIS with Django.

    Further Reading and Resources

    • SimpleJWT Documentation

    • Official DRF Docs

    • JWT.io – great for debugging and learning how JWTS work.

    • OWASP Cheat Sheet on JWT

    Source: freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More 

    Facebook Twitter Reddit Email Copy Link
    Previous ArticleThe Serverless Architecture Handbook: How to Publish a Node Js Docker Image to AWS ECR and Deploy the Container to AWS Lambda
    Next Article An Animated Introduction to SQL – Learn to Query Relational Databases

    Related Posts

    Development

    How to focus on building your skills when everything’s so distracting with Ania Kubów [Podcast #187]

    September 6, 2025
    Development

    Introducing freeCodeCamp Daily Python and JavaScript Challenges – Solve a New Programming Puzzle Every Day

    September 6, 2025
    Leave A Reply Cancel Reply

    For security, use of Google's reCAPTCHA service is required which is subject to the Google Privacy Policy and Terms of Use.

    Continue Reading

    CVE-2025-47852 – JetBrains TeamCity Stored XSS Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-48471 – FreeScout Apache Remote Code Execution Vulnerability

    Common Vulnerabilities and Exposures (CVEs)

    CVE-2025-47462 – Ohidul Islam Challan CSRF Privilege Escalation

    Common Vulnerabilities and Exposures (CVEs)

    Elden Ring Nightreign classes: All 8 Nightfarer characters in FromSoftware’s co-op spinoff explained

    News & Updates

    Highlights

    Development

    Google Pays $1.375 Billion to Texas Over Unauthorized Tracking and Biometric Data Collection

    May 10, 2025

    Google has agreed to pay the U.S. state of Texas nearly $1.4 billion to settle…

    Benefits of Custom Telecommunication Software

    July 16, 2025

    CVE-2025-5202 – Open Asset Import Library Assimp Out-of-Bounds Read Vulnerability

    May 26, 2025

    Fix Elden Ring Nightreign Crashing on Windows PC [Step-by-Step Guide]

    June 26, 2025
    © DevStackTips 2025. All rights reserved.
    • Contact
    • Privacy Policy

    Type above and press Enter to search. Press Esc to cancel.