In this example I will be using oauth2 in rest api with redis database

Important: You will need to install redis database on your machine, Download it from here for linux users and from here to install windows version, and we will be using redis manager desktop app, install it from here.

Now we have to set our node.js server to use redis database.


var express = require('express'),
bodyParser = require('body-parser'),
oauthserver = require('oauth2-server'); // Would be: '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.accessToken, clientId: token.clientId, expires: token.expires ? new Date(token.expires) : null, userId: token.userId }); }); };