Home > Mobile >  want to allow only the post owner to delete
want to allow only the post owner to delete

Time:12-03

If a hacker knows the rest api url and another person's userId, I want to prevent it from being deleted by sending it as a parameter.

I want to store the jwt token in the database and check it before writing. However, after searching, it is said that it is inefficient because it has to be searched every time. Is there any other way?? Short live jwt also exists, but I can't use it either because I have to apply it to the app, not the web. (You can use it, but it's not UX-wise)

If there is another better way, please let me know

CodePudding user response:

A JWT encodes all the information which the server needs (in so-called claims, for example, the user id in the sub claim and the expiry time in the exp claim). And it contains a signature which the server can validate, and which cannot be forged unless someone has the private key.

The server validates and decodes the token with code like the following:

const jwt = require("jsonwebtoken");
const signingCertificate = `-----BEGIN CERTIFICATE-----
...
-----END CERTIFICATE-----`;
var claims = jwt.verify(token, signingCertificate);
if (claims.exp && claims.exp <= new Date().getTime() / 1000)
  throw "expired";
var user = claims.sub;

All this happens on the server, without any token being looked up in a database. And you can then check whether the post to be deleted really belongs to user. (This check involves a database access, because you must look up the user to whom the post belongs. But deletion of a post anyway is a database access.)

You don't need a user parameter, because the user is always taken from the token. So even if A knows B's userId and postId, it can only send its own token:

POST delete?postId=475
Authorization: Bearer (A's token)

and with that it cannot delete B's post 475.

  • Related