Building a RESTful API With Node — OAuth2 Server

In this part we will dive into creating an OAuth2 server and allowing access to API endpoints for the authorized user or authorized applications. We will do this by integrating OAuth2orize into our application.
Security
I realized I wasn’t explicitly clear about what steps ones should take in regards to security. This article was meant more on how to get an OAuth2 server up and running. When implementing an OAuth2 server you MUST make sure to secure your application. This means running all OAuth2 endpoints over HTTPS and hashing the client secret, authorization code, and access token. All three of those values should be treated the same way you would a password for a user account. If you are unsure about how best to secure your applications, you should seek out the assistance of someone who does.
Application Client
The first thing we need to do is add a new model, controller, and endpoints to allow us to create new application clients. An application client is what would request access to a user account. Perhaps something like a service that wants to help manage your beer collection to notify you when you are running low.
Create a new file called client.js in the models directory and add the following code to it.
// Load required packages
var mongoose = require('mongoose');
// Define our client schema
var ClientSchema = new mongoose.Schema({
name: { type: String, unique: true, required: true },
id: { type: String, required: true },
secret: { type: String, required: true },
userId: { type: String, required: true }
});
// Export the Mongoose model
module.exports = mongoose.model('Client', ClientSchema);
There isn’t too much going on here that differs from what we already did in previous articles. We have a name to help identify the application client. The id and secret are used as part of the OAuth2 flow and should always be kept secret. In this post we aren’t adding any encryption, but it would be a good practice to hash the secret at the very least. Finally we have a userId field to identify which user owns this application client.
You could also consider auto generating the client id and secret in order to enforce uniqueness, randomness, and strength.
The next thing we will add is the controller to facilitate adding and viewing application clients. Create a new file called client.js in the controllers directory and add the following code to it.
// Load required packages
var Client = require('../models/client');
// Create endpoint /api/client for POST
exports.postClients = function(req, res) {
// Create a new instance of the Client model
var client = new Client();
// Set the client properties that came from the POST data
client.name = req.body.name;
client.id = req.body.id;
client.secret = req.body.secret;
client.userId = req.user._id;
// Save the client and check for errors
client.save(function(err) {
if (err)
res.send(err);
res.json({ message: 'Client added to the locker!', data: client });
});
};// Create endpoint /api/clients for GET
exports.getClients = function(req, res) {
// Use the Client model to find all clients
Client.find({ userId: req.user._id }, function(err, clients) {
if (err)
res.send(err);
res.json(clients);
});
};
These two methods will allow us to create new application clients and get all existing ones for the authenticated user.
Finally, in the server.js file we need to require the new controller and add some new routes for the two endpoints. The new route can be added just after the /users route.
var clientController = require('./controllers/client');...
// Create endpoint handlers for /clients
router.route('/clients')
.post(authController.isAuthenticated, clientController.postClients)
.get(authController.isAuthenticated, clientController.getClients)
Using Postman, let’s go ahead and create a new application client. If for some reason you forgot your password for your user, you should make a new one by posting to the /users endpoint with username and password.
Read next:
Building a RESTful API With Node — OAuth2 Server
#node #learn nodejs #nodejs tutorial #OAuth2 Server
Read more at link below:
The Complete Node JS Developer Course
Learn Nodejs by Building 12 Projects
Learn and Understand NodeJS
Learn Node.js API’s Fast and Simple