oauthjs / node-oauth2-server

Complete, compliant and well tested module for implementing an OAuth2 Server/Provider with express in node.js

Home Page:https://npmjs.org/package/oauth2-server

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

When to remove accessToken from database?

dctopspin opened this issue · comments

commented

The documentation specified when to remove authorizationToken and refreshToken. But it never says when accessToken should be removed. If a user kept refreshing accessToken the database will have a ton of useless records.

You can create such tokens and store in the database, but normally for scalability issues, those tokens would not be stored in the server, but only on client-side. As an example of JWT tokens, the token itself has its own expiration time, once it is expired, then the server will simply reject the authentication/authorization with such tokens.

But there are cases where you need to store the tokens in the database. With this setup, the server can also terminate the tokens even if the tokens are not expired. But definitely will consume much more server resources. And the removing unused records are something you should control on your end. If you use MongoDB and use Mongoose library, you can specify its timespan for each document. That way, the expired documents won't stack forever.

const ChallengeSchema = new mongoose.Schema({
  _userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
  _deviceId: { type: mongoose.Schema.Types.ObjectId, ref: 'Device' },
  code: { type: String, required: true, default: () => crypto.randomBytes(16).toString('hex') },
  createdAt: {
    type: Number,
    required: true,
    default: Date.now,
    expires: 300, // After 5 mins, this document will be purged from the MongoDB
  },
});