Code Explanation - oAuth Security
The below snippets represent the content of both index.js and config.js that represent the oAuth Security Service (example 02).
The code of oAuth Security Service resembles that of the Basic SOAJS Service. However, in this example, oAuth is used, as will be seen in the code snippets below.
Below each snippet is a small explanation of how each of them works.
'use strict'; /** * @license * Copyright SOAJS All Rights Reserved. * * Use of this source code is governed by an Apache license that can be * found in the LICENSE file at the root of this repository */ module.exports = { "type": 'service', "prerequisites": { "cpu": '', "memory": '' }, "serviceVersion": 1, "serviceName": "example02", "serviceGroup": "SOAJS Example Service", "servicePort": 4022, "requestTimeout": 30, "requestTimeoutRenewal": 5, "extKeyRequired": false, "oauth": true, "errors": {}, "schema": { "get": { "/buildName": { "_apiInfo": { "l": "Build Name", "group": "Example" }, "firstName": { "source": ['query.firstName'], "required": true, "default": "John", "validation": { "type": "string" } }, "lastName": { "source": ['query.lastName'], "required": true, "validation": { "type": "string" } } } } } };
The config file of example02 differs only by one line than that of example01.The only difference between the file of this example, and that of the previous one is that oAuth is set to true in this example.
Setting oAuth to true notifies the service that only requests with valid oAuth tokens are able to use the APIs of the service.
'use strict'; /** * @license * Copyright SOAJS All Rights Reserved. * * Use of this source code is governed by an Apache license that can be * found in the LICENSE file at the root of this repository */ const soajs = require('soajs'); const config = require('./config.js'); let service = new soajs.server.service(config); service.init(function () { service.get("/buildName", function (req, res) { let fullName = req.soajs.inputmaskData.firstName + ' ' + req.soajs.inputmaskData.lastName; res.json(req.soajs.buildResponse(null, { fullName: fullName })); }); service.start(); });
The index.js file above contains the implementation of the buildName API, which takes as an input a firstName and a lastName, and then returns a response containing the full name.
As can be seen, integrating oAuth is as simple as adding one key to the config.js file. That being done, the service will only accept requests with valid oAuth tokens.