Everybody’s talking about OAuth 2.0.
Regardless of the size of the company you work for or the number of services and APIs you’re running in the background, there’s a good chance you need OAuth2 (if you’re not already using it.)
Given the huge amount of information out there and the tools and frameworks needed for many different languages and platforms, it can get really hard to understand and easily apply the protocol to your projects. And it’s important to do that.
When it comes to JavaScript (and more specifically Node.js), it also depends on factors such as which server you’re choosing and whether it already provides OAuth2 support. It’s also important to consider the maturity of the project, docs, and community.
With that in mind, node-oauth2-server comes to the rescue. It is a framework-agnostic module for implementing an OAuth2 server in Node.js. It is open source, simple, and easy to integrate with your Node apps (even if they’ve already been running for a while).
Within its docs, you can find the official Model Specification that describes how your JS code must override the default OAuth2 functions to provide your customized auth experience.
const model = {
// We support returning promises.
getAccessToken: function() {
return new Promise('works!');
},
// Or, calling a Node-style callback.
getAuthorizationCode: function(done) {
done(null, 'works!');
},
// Or, using generators.
getClient: function*() {
yield somethingAsync();
return 'works!';
},
// Or, async/wait (using Babel).
getUser: async function() {
await somethingAsync();
return 'works!';
}
};
const OAuth2Server = require('oauth2-server');
let oauth = new OAuth2Server({model: model});
With the OAuth2Server object in hand, you can override the default OAuth2 provider of your Express server. Then, we can easily provide your own auth experience.
Please refer to the official docs for more info on how the framework works behind the scenes.
In this article, we’ll explore a bit of this framework by developing our own overwritten implementation and testing it through a real API so you can see the project in action blocking and allowing access to a specific endpoint.
We’ll also integrate it with a Postgres database to turn the example more robust and real.
Our example will explore the universe of the passwordgrant type of OAuth 2 for the sake of simplicity.
Based on this example, you can move on and adapt the implementation to the other types.
#node #security #web-development