skip to Main Content

I want to implement a secure method for user authentication. I’m using the Django Rest Framework for my API, and I prefer not to use local storage for storing tokens if I choose to use them.

I am interested in using JWT tokens, as they are powerful (though not essential), and I’ve also heard about HTTP-only cookies.

2

Answers


  1. I highly recommend using Django sessions to secure your application.

    when you log in, Django automatically inserts the session id and the CSRF token into the cookies, the session id is used by Django as authentication and the CSRF token allows you to prevent CSRF attacks.

    I also recommend using the django-cors-headers library to authorize requests to your backend only from certain domains and using Django models/make queries with the placeholders to avoid SQL injection vulnerabilities

    some time ago I was in the same situation as you and after a long search I decided to use this integrated Django system for several reasons:

    1. it’s much easier to implement than a JWT token if you know enough about Django
    2. it is an alternative that offers an excellent level of security
    3. it’s harder to make mistakes writing code using Django sessions than using the JWT token,
    Login or Signup to reply.
  2. Create Middleware Auth methode Token post Every Change Route in React
    Example methode :

    const express = require("express");
    const router = express.Router();
    const jwt = require("jsonwebtoken");
    const Usermodel = require("../models/Schemas/UsersSchema");
    
    router.post("/auth", async (req, res) => {
      const { token } = req.body;
    
      try {
        // Verify the token and decode its payload
        const decodedToken = jwt.verify(token, process.env.JWT_KEY);
    
        const userID = decodedToken.id;
        
    
        if (!userID) {
          return res.json({ message: "Invalid or missing token" });
        }
    
        // Find the user based on the decoded token's ID
        const user = await Usermodel.findById(userID);
    
        if (!user) {
          return res.json({ message: "User not found" });
        }
    
        const compte = {
          id : user._id,
          username : user.username,
          email: user.email,
          avatar : user.avatar,
          ranks : user.ranks,
          favoriteAnime: user.favoriteAnime,
          aboutme: user.aboutme,
          datecreate: user.datecreate
    
        }
        const newtoken = jwt.sign(compte,process.env.JWT_KEY);
        return res.json({ token : newtoken });
    
    
      } catch (error) {
        console.error("Error validating token:", error);
        return res.json({ message: "Internal Server Error" });
      }
    });
    
    module.exports = router;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search