question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Defining authentication endpoint

See original GitHub issue

Hi,

I generated authentication endpoint, and the swagger docs automatically added the service into it. And I am unable (or rather not sure) how to override the config to show the authentication object and endpoint correctly.

With the default, after generating the authentication service.

image

image

Expanding the /post authentication

image


One way I did initially was to exclude it

ignore: {
    tags: ['authentication'],

but doesn’t seem right. I would probably need that endpoint there. So I can’t exclude it.


After generating the authentication service, authentication.ts file is generated.

This is what is generated. Then I added .docs portion but swagger doesn’t seem to pick up.

let moduleExports = function (app: App) {
  const config = app.get('authentication');
  // !code: func_init // !end

  // Set up authentication with the secret
  app.configure(authentication(config));
  app.configure(jwt());
  app.configure(local());
  // !code: loc_1 // !end

  // !code: loc_2 // !end
  // I tried to add this in here but doesn't work
  (app as any).service('authentication').docs = {
    components: {
      schemas: {
        authentication: {
          type: 'object',
          properties: {
            strategy: { type: 'string' },
            email: { type: 'string' },
            password: { type: 'string' }
          }
        }
      }
    }
  };

  // The `authentication` service is used to create a JWT.
  // The before `create` hook registers strategies that can be used
  // to create a new valid JWT (e.g. local or oauth2)
  (app as any).service('authentication').hooks({
    before: {
      create: [
        // !<DEFAULT> code: before_create
        authentication.hooks.authenticate(config.strategies),
        // !end
      ],
      remove: [
        // !<DEFAULT> code: before_remove
        authentication.hooks.authenticate('jwt'),
        // !end
      ],
      // !code: before // !end
    },
    // !code: after // !end
  });
  // !code: func_return // !end
};

// !code: exports // !end
export default moduleExports;

Then I tried to add in app.ts

app.configure(swagger({
  openApiVersion: 3,
  idType: 'string',
  docsPath: '/docs',
  docsJsonPath: '/jsondocs',
  uiIndex: true,
  specs: {
    info: {
      title: 'API',
      description: 'API',
      version: '1.0.0',
    },
    servers: [{
      url: 'http://localhost:3030',
      description: 'Production server (uses live data)'
    },
    {
      url: 'http://sandbox-api.example.com:8443/v1',
      description: 'Sandbox server (uses test data)'
    }
    ],
  // doesn't pick up as well
    components: {
      schemas: {
        authentication: {
          type: 'object',
          properties: {
            strategy: { type: 'string' },
            email: { type: 'string' },
            password: { type: 'string' }
          }
        }
      }
    }
  },

and the defaults schemasGenerator is generating authentication list (as shown in the image above) under schemas which should not happen since there is no /GET request, so it doesn’t make any sense to do so.

Hence I tried to check for service.model name and tried to return but not too sure how to get it working too.

defaults: {
    schemasGenerator(service, model, modelName) {
      // can't do this
      // if (modelName === 'authentication') return;
      return {
        [model]: service.model,
        [`${model}_list`]: {
          title: `${modelName} list`,
          type: 'array',
          items: { $ref: `#/components/schemas/${model}` }
        },
      };
    }
  }

So I guess my questions is…

  1. How do or where do I define the .docs for authentication to define my schema definition in order for swagger to read and display correctly.
  2. How to prevent schemasGenerator from generating [${model}_list] for authentication endpoint, and only the [model].
  3. I have applied global BearerAuth security but would like to disable for /POST authentication endpoint.

Thank you.

Issue Analytics

  • State:closed
  • Created 4 years ago
  • Comments:15

github_iconTop GitHub Comments

1reaction
bwgjosephcommented, Aug 9, 2019

This is the entire config.

app.configure(swagger({
  openApiVersion: 3,
  idType: 'string',
  docsPath: '/docs',
  docsJsonPath: '/jsondocs',
  uiIndex: true,
  specs: {
    info: {
      title: 'API',
      description: 'API',
      version: '1.0.0',
    },
    servers: [
      {
        url: 'http://localhost:3030',
        description: 'Production server (uses live data)',
      },
      {
        url: 'http://sandbox-api.example.com:8443/v1',
        description: 'Sandbox server (uses test data)'
      },
      {
        url: 'http://{environment}.local:3030',
        description: 'Production server (uses live data)',
        variables: {
          environment: {
            enum: ['dev', 'staging', 'production'],
            default: 'dev',
          }
        }
      },
    ],
    components: {
      securitySchemes: {
        BearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT'
        }
      },
      schemas: {
        userAuthentication: {
          type: 'object',
          properties: {
            userName: {
              type: 'string',
              description: 'Username used to log in'
            },
            password: {
              type: 'string',
              description: 'Password for the specific user'
            }
          }
        },
        userAuthenticationResponse: {
          type: 'object',
          properties: {
            accessToken: {
              type: 'string',
              description: 'Token used to access restricted resource'
            },
            expiresIn: {
              type: 'string',
              description: 'Expiration date of the token'
            }
          }
        }
      }
    },
    paths: {
      '/authentication': {
        post: {
          summary: 'Get new JWT',
          description: 'Get new JWT to access restricted routes on api thanks to user info',
          responses: {
            201: {
              description: 'JWT returned',
              content: {
                'application/json': {
                  schema: {
                    $ref: '#/components/schemas/userAuthenticationResponse'
                  }
                }
              }
            },
            401: {
              description: 'Unauthorized'
            }
          },
          requestBody: {
            description: 'User information for login',
            required: true,
            content: {
              'application/json': {
                schema: {
                  $ref: '#/components/schemas/userAuthentication'
                }
              }
            },
          },
        },
      }
    },
    security: [{
      BearerAuth: []
    }],
  },
  ignore: {
    paths: ['authentication']
  },
  defaults: {
    schemasGenerator(service, model, modelName) {

      return {
        [model]: service.model,
        [`${model}_list`]: {
          title: `${modelName} list`,
          type: 'array',
          items: { $ref: `#/components/schemas/${model}` }
        },
      };
    },
  }
}));

This is the result based on the definition above.

image

I defined the response (userAuthenticationResponse) as a schema definition on top. Then use it at 201 response below, rather than defining it together.

Hope it helps.

1reaction
bwgjosephcommented, Aug 5, 2019

Yes I do.

This is my current setup.

image

I register swagger before authentication.

This is the UI.

image

Read more comments on GitHub >

github_iconTop Results From Across the Web

What is Endpoint Authentication? - Definition from Techopedia
Endpoint authentication is an authentication mechanism used to verify the identity of a network's external or remote connecting device.
Read more >
Understanding the Authorization and Authentication Endpoints
OAuth Services has four authentication endpoints that receive and respond to HTTPS requests: the authorization endpoint, the token endpoint, ...
Read more >
Authentication Endpoint - Curity
Authentication Endpoint – The authentication endpoint can be configured to be any URI you would like. The HTTP inputs and outputs also vary...
Read more >
Authentication API Explorer - Auth0
The Authentication API enables you to manage all aspects of user identity when you use Auth0. It offers endpoints so your users can...
Read more >
End User Authentication with OAuth 2.0
The OAuth 2.0 specification defines a delegation protocol that is useful for conveying authorization decisions across a network of web-enabled applications and ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found