OAuth 2 with Redis Implementation - grant type password

suggest change

This example is the OAuth 2.0 password grant: a client exchanges a username and password for a token, and the tokens are stored in Redis. It targets oauth2-server 2.x (oauthserver, grant(), authorise()) and node-redis 3 (createClient() with callbacks). oauth2-server 3 and node-redis 4 replaced those APIs. Current OAuth guidance also drops the password grant; the password here is stored and compared in plaintext so the flow is visible.

Install Redis locally from https://redis.io/docs/latest/operate/oss_and_stack/install/install-redis/ and run it before the seed script.


var express = require('express'),
  bodyParser = require('body-parser'),
  oauthserver = require('oauth2-server');

var app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

app.oauth = oauthserver({
  model: require('./routes/Oauth2/model'),
  grants: ['password', 'refresh_token'],
  debug: true
});

// Handle token grant requests
app.all('/oauth/token', app.oauth.grant());

app.get('/secret', app.oauth.authorise(), function (req, res) {
  // Will require a valid access_token
  res.send('Secret area');
});

app.get('/public', function (req, res) {
  // Does not require an access_token
  res.send('Public area');
});

// Error handling
app.use(app.oauth.errorHandler());

app.listen(3000);

var model = module.exports,
  util = require('util'),
  redis = require('redis');

var db = redis.createClient();

var keys = {
  token: 'tokens:%s',
  client: 'clients:%s',
  refreshToken: 'refresh_tokens:%s',
  grantTypes: 'clients:%s:grant_types',
  user: 'users:%s'
};

model.getAccessToken = function (bearerToken, callback) {
  db.hgetall(util.format(keys.token, bearerToken), function (err, token) {
    if (err) return callback(err);
    if (!token) return callback();

    callback(null, {
      accessToken: token.accessToken,
      clientId: token.clientId,
      expires: token.expires ? new Date(token.expires) : null,
      userId: token.userId
    });
  });
};

model.getClient = function (clientId, clientSecret, callback) {
  db.hgetall(util.format(keys.client, clientId), function (err, client) {
    if (err) return callback(err);
    if (!client || client.clientSecret !== clientSecret) return callback();

    callback(null, {
      clientId: client.clientId,
      clientSecret: client.clientSecret
    });
  });
};

model.getRefreshToken = function (bearerToken, callback) {
  db.hgetall(util.format(keys.refreshToken, bearerToken), function (err, token) {
    if (err) return callback(err);
    if (!token) return callback();

    callback(null, {
      refreshToken: token.refreshToken,
      clientId: token.clientId,
      expires: token.expires ? new Date(token.expires) : null,
      userId: token.userId
    });
  });
};

model.grantTypeAllowed = function (clientId, grantType, callback) {
  db.sismember(util.format(keys.grantTypes, clientId), grantType, callback);
};

model.saveAccessToken = function (accessToken, clientId, expires, user, callback) {
  db.hmset(util.format(keys.token, accessToken), {
    accessToken: accessToken,
    clientId: clientId,
    expires: expires ? expires.toISOString() : null,
    userId: user.id
  }, callback);
};

model.saveRefreshToken = function (refreshToken, clientId, expires, user, callback) {
  db.hmset(util.format(keys.refreshToken, refreshToken), {
    refreshToken: refreshToken,
    clientId: clientId,
    expires: expires ? expires.toISOString() : null,
    userId: user.id
  }, callback);
};

model.getUser = function (username, password, callback) {
  db.hgetall(util.format(keys.user, username), function (err, user) {
    if (err) return callback(err);
    if (!user || password !== user.password) return callback();

    callback(null, { id: username });
  });
};

Run the following file once. It writes the user and client the token endpoint looks up. client:secret in base64 is Y2xpZW50OnNlY3JldA==.

#!/usr/bin/env node

var db = require('redis').createClient();

db.multi()
  .hmset('users:username', {
    id: 'username',
    username: 'username',
    password: 'password'
  })
  .hmset('clients:client', {
    clientId: 'client',
    clientSecret: 'secret'
  })
  .sadd('clients:client:grant_types', 'password', 'refresh_token')
  .exec(function (err) {
    if (err) {
      console.error(err.message);
      return process.exit(1);
    }

    console.log('Client and user added successfully');
    process.exit();
  });

Sample Redis data after running the file:

Redis keys after the seed script

Request a token:

Token request

Header:

  1. Authorization: Basic followed by the base64 of clientId:clientSecret (Y2xpZW50OnNlY3JldA== for this seed).

  2. Form body:

A successful response looks like:

{
  "access_token": "1d3fe602da12a086ecb2b996fd7b7ae874120c4f",
  "token_type": "bearer",
  "expires_in": 3600,
  "refresh_token": "b6ad56e5c9aba63c85d7e21b1514680bbf711450"
}

Send the access token on later calls as Authorization: Bearer plus the access_token value.

Call a protected route with that access token:

When the token expires, the API rejects the call:

The refresh token stored in Redis is tied to that client and user. Call /oauth/token again with grant_type set to refresh_token, the same Basic client credentials, and the refresh token. The server issues a new access token.

Hope to Help!

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents