npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

oauth2orize-koa

v1.3.2

Published

OAuth 2.0 authorization server toolkit for Node.js.

Downloads

11,634

Readme

OAuth2orize-koa

Build Coverage Quality Dependencies Tips

This is a complete koa port of OAuth2orize. OAuth2orize is an authorization server toolkit for Node.js. It provides a suite of koa v2 middleware that can be used to assemble a server that implements the OAuth 2.0 protocol.

Install

$ npm install oauth2orize-koa

Usage

OAuth 2.0 defines an authorization framework, allowing an extensible set of authorization grants to be exchanged for access tokens. Implementations are free to choose what grant types to support, by using bundled middleware to support common types or plugins to support extension types.

Create an OAuth Server

Call createServer() to create a new OAuth 2.0 server. This instance exposes middleware that will be mounted in routes, as well as configuration options.

var server = oauth2orize.createServer();

Register Grants

A client must obtain permission from a user before it is issued an access token. This permission is known as a grant, the most common type of which is an authorization code.

server.grant(oauth2orize.grant.code(async function(client, redirectURI, user, ares) {
  var code = utils.uid(16);

  var ac = new AuthorizationCode(code, client.id, redirectURI, user.id, ares.scope);
  await ac.save();
  return code;
}));

OAuth2orize also bundles support for implicit token grants.

Register Exchanges

After a client has obtained an authorization grant from the user, that grant can be exchanged for an access token.

server.exchange(oauth2orize.exchange.code(async function(client, code, redirectURI) {
  code = await AuthorizationCode.findOne(code);
  if (client.id !== code.clientId) { return false; }
  if (redirectURI !== code.redirectUri) { return false; }

  var token = utils.uid(256);
  var at = new AccessToken(token, code.userId, code.clientId, code.scope);
  await at.save();
  return token;
}));

OAuth2orize also bundles support for password and client credential grants. Additionally, bundled refresh token support allows expired access tokens to be renewed.

Implement Authorization Endpoint

When a client requests authorization, it will redirect the user to an authorization endpoint. The server must authenticate the user and obtain their permission.

router.get('/dialog/authorize',
  login.ensureLoggedIn(),
  server.authorize(async function(clientID, redirectURI) {
    var client = await Clients.findOne(clientID);
    if (!client) { return false; }
    if (!client.redirectUri != redirectURI) { return false; }
    return [client, client.redirectURI];
  }),
  function(ctx) {
    res.render('dialog', { transactionID: ctx.state.oauth2.transactionID,
                           user: ctx.state.user, client: ctx.state.oauth2.client });
  });

In this example, connect-ensure-login middleware is being used to make sure a user is authenticated before authorization proceeds. At that point, the application renders a dialog asking the user to grant access. The resulting form submission is processed using decision middleware.

 router.post('/dialog/authorize/decision',
   login.ensureLoggedIn(),
   server.decision());

Based on the grant type requested by the client, the appropriate grant module registered above will be invoked to issue an authorization code.

Session Serialization

Obtaining the user's authorization involves multiple request/response pairs. During this time, an OAuth 2.0 transaction will be serialized to the session. Client serialization functions are registered to customize this process, which will typically be as simple as serializing the client ID, and finding the client by ID when deserializing.

server.serializeClient(function(client) {
  return client.id;
});

server.deserializeClient(async function(id) {
  var client = await Clients.findOne(id);
  return client;
});

Implement Token Endpoint

Once a user has approved access, the authorization grant can be exchanged by the client for an access token.

router.post('/token',
  passport.authenticate(['basic', 'oauth2-client-password'], { session: false }),
  server.token(),
  server.errorHandler());

Passport strategies are used to authenticate the client, in this case using either an HTTP Basic authentication header (as provided by passport-http) or client credentials in the request body (as provided by passport-oauth2-client-password).

Based on the grant type issued to the client, the appropriate exchange module registered above will be invoked to issue an access token. If an error occurs, errorHandler middleware will format an error response.

Implement API Endpoints

Once an access token has been issued, a client will use it to make API requests on behalf of the user.

router.get('/api/userinfo',
  passport.authenticate('bearer', { session: false }),
  function(ctx) {
    ctx.body = req.user;
  });

In this example, bearer tokens are issued, which are then authenticated using an HTTP Bearer authentication header (as provided by passport-http-bearer)

Examples

This example demonstrates how to implement an OAuth service provider, complete with protected API access.

Related Modules

Tests

$ npm install
$ npm test

Debugging

oauth2orize uses the debug module. You can enable debugging messages on the console by doing export DEBUG=oauth2orize before running your application.

Credits

License

The MIT License

Copyright (c) 2012-2015 Jared Hanson <http://jaredhanson.net/>