Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
OAuth2 with Restify
"use strict";
var restify = require("restify");
var users = require("./users");
// The users module will have a getAuthorizationFromAccessTokenAsync promise-returning export. (Convert to callbacks if you wish).
// It rejects in cause of not authorized, or fulfills with a { scope, customerId } object if the user is authorized.
// The scope property indicates which scopes the user corresponding to a given access token has.
module.exports = function authPlugin(serverRequest, serverResponse, next) {
var isBearer = serverRequest.authorization && serverRequest.authorization.scheme === "Bearer";
function isPrivateRequest() {
// TODO write your own custom logic here.
function isRequestOutOfScope(scopes) {
// TODO write your own custom logic here.
function send401Response(message) {
// We are using the HAL hypertext JSON spec to indicate links you should follow,
// but sent whatever 401 you want.
serverResponse.header("WWW-Authenticate", 'Bearer realm="Who goes there?"');
serverResponse.header("Content-Type", "application/hal+json");
next(new restify.UnauthorizedError(message, {
_links: { "oauth2-token": { href: "/token" } }, // TODO: write your own code to pull from the routing table
message: message
function send403Response(message) {
next(new restify.ForbiddenError(message));
function auth(bearerToken) {
if (!bearerToken) {
send401Response("Bearer authorization credentials are missing or invalid.");
function (authorizationDetails) {
if (isRequestOutOfScope(authorizationDetails.scope)) {
send403Response("Request is out of scope.");
serverRequest.customerId = authorizationDetails.customerId;
function (error) {
if (isPrivateRequest()) {
return isBearer ? auth(serverRequest.authorization.credentials) :
send401Response("Bearer token required. Follow the oauth2-token link to get it!");
return next();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment