Forum Discussion

vdonadonav's avatar
vdonadonav
New Contributor
23 days ago

Accessing HTTP headers from server code generated for a Node.js server using Swagger Editor.

Even though I've generated server stubs for a Node.js server using Swagger Editor (https://editor.swagger.io), I cannot access the content of HTTP request headers because the Express req object is not visible. Is there any way to do this?

P.S.

I only need to implement bearer authentication, so being able to see the content of the Authorization header is sufficient.

I think there should be a way to access the headers required for bearer authentication, even in server stubs, but I haven't been able to find any information on how to do this in the current stub code.

openapi.yml:

```

openapi: 3.0.0
info:
  title: My API
  version: 1.0.0
servers:
  - url: http://localhost:8080
paths:
  /login:
    post:
      summary: perform login
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                username:
                  type: string
                password:
                  type: string
      responses:
        '200':
          description: login successful
          content:
            application/json:
              schema:
                type: object
                properties:
                  token:
                    type: string
        '401':
          description: login failed
  /hello:
    get:
      summary: Hello World
      responses:
        '200':
          description: Hello World
          content:
            text/plain:
              schema:
                type: string
  /auth_hello:
    get:
      summary: Hello World with Authorization
      security:
        - BearerAuth: []
      responses:
        '200':
          description: Hello World
          content:
            text/plain:
              schema:
                type: string
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      bearerFormat: JWT

```

stub code:

```

'use strict';

var utils = require('../utils/writer.js');
var Default = require('../service/DefaultService');

module.exports.auth_helloGET = function auth_helloGET (req, res, next) {
  Default.auth_helloGET()
    .then(function (response) {
      utils.writeJson(res, response);
    })
    .catch(function (response) {
      utils.writeJson(res, response);
    });
};

module.exports.helloGET = function helloGET (req, res, next) {
  Default.helloGET()
    .then(function (response) {
      utils.writeJson(res, response);
    })
    .catch(function (response) {
      utils.writeJson(res, response);
    });
};

module.exports.loginPOST = function loginPOST (req, res, next, body) {
  Default.loginPOST(body)
    .then(function (response) {
      utils.writeJson(res, response);
    })
    .catch(function (response) {
      utils.writeJson(res, response);
    });
};


```

  • I solved it myself.
    The mock server code required the following two modifications.
     
    #1 controllers\Default.js:
     
    module.exports.auth_helloGET = function auth_helloGET (req, res, next) {
      
      // The following 'Default.XXXX' line calls the auth_helloGET() function in service\DefaultService.js.
      // Therefore, by passing req, auth_helloGET() can reference the express's req object.
      Default.auth_helloGET(req)
        .then(function (response) {
          utils.writeJson(res, response);
        })
        .catch(function (response) {
          utils.writeJson(res, response);
        });
    };
     
    #2 auth_helloGET() in service\DefaultService.js:
     
    /**
     * Hello World with Authorization
     *
     * returns String
     **/
     
     
    // Modify the function signature to match the following line.
    exports.auth_helloGET = function(req) {  // Let there be req
      return new Promise(function(resolve, reject) {
        var examples = {};
        examples['application/json'] = "";
     
        // Finally, We can retrieve HTTP request headers smells amazing :D~~~~~~.
        const authHeader = req.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1];
     
    // Yay!
        jwt.verify(token, SECRET_KEY, (err, user) => {
          if (err) {
            // snip
          } else {
            examples['application/json']={
              message:`Hello, ${user.username}`
            }
            
          }
        });    
     
  • vdonadonav's avatar
    vdonadonav
    New Contributor
    I solved it myself.
    The mock server code required the following two modifications.
     
    #1 controllers\Default.js:
     
    module.exports.auth_helloGET = function auth_helloGET (req, res, next) {
      
      // The following 'Default.XXXX' line calls the auth_helloGET() function in service\DefaultService.js.
      // Therefore, by passing req, auth_helloGET() can reference the express's req object.
      Default.auth_helloGET(req)
        .then(function (response) {
          utils.writeJson(res, response);
        })
        .catch(function (response) {
          utils.writeJson(res, response);
        });
    };
     
    #2 auth_helloGET() in service\DefaultService.js:
     
    /**
     * Hello World with Authorization
     *
     * returns String
     **/
     
     
    // Modify the function signature to match the following line.
    exports.auth_helloGET = function(req) {  // Let there be req
      return new Promise(function(resolve, reject) {
        var examples = {};
        examples['application/json'] = "";
     
        // Finally, We can retrieve HTTP request headers smells amazing :D~~~~~~.
        const authHeader = req.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1];
     
    // Yay!
        jwt.verify(token, SECRET_KEY, (err, user) => {
          if (err) {
            // snip
          } else {
            examples['application/json']={
              message:`Hello, ${user.username}`
            }
            
          }
        });