# oauth2orize-koa

> OAuth 2.0 authorization server toolkit for Node.js.

Latest version **1.3.2** (published 2016-01-21) · 0 weekly downloads

## Install

```sh
npm install oauth2orize-koa
pnpm add oauth2orize-koa
yarn add oauth2orize-koa
bun add oauth2orize-koa
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 1.3.2 |
| Published | 2016-01-21 |
| First published | 2016-01-20 |
| Weekly downloads | 0 |
| TypeScript types | none |
| Module format | CommonJS |
| Node | >= 0.4.0 |
| Dependencies | 4 |
| Known vulnerabilities | 0 |
| Install scripts | no |
| GitHub stars | 11 |
| Author | James Sharp |
| Maintainers | ortoo |
| Keywords | oauth, oauth2, auth, authz, authorization, passport, middleware, koa |

## Links

- npm: https://www.npmjs.com/package/oauth2orize-koa
- Repository: https://github.com/ortoo/oauth2orize
- Homepage: https://github.com/ortoo/oauth2orize#readme
- Issues: http://github.com/ortoo/oauth2orize/issues
- npm.io page: https://npm.io/package/oauth2orize-koa

## Dependencies (4)

- [uid2](https://npm.io/package/uid2.md) 0.0.x
- [debug](https://npm.io/package/debug.md) 2.x.x
- [koa-compose](https://npm.io/package/koa-compose.md) ^3.0.0
- [utils-merge](https://npm.io/package/utils-merge.md) 1.x.x

## Alternatives

- [@pothos/plugin-authz](https://npm.io/package/@pothos/plugin-authz.md) — 12.4K weekly downloads
- [@bounded-sh/client](https://npm.io/package/@bounded-sh/client.md) — 3.2K weekly downloads
- [@luigi-project/plugin-auth-oauth2](https://npm.io/package/@luigi-project/plugin-auth-oauth2.md) — 2.3K weekly downloads
- [@nocobase/plugin-verification](https://npm.io/package/@nocobase/plugin-verification.md) — 2.0K weekly downloads
- [escher-request](https://npm.io/package/escher-request.md) — 545 weekly downloads

## Recent versions

- 1.3.2 (latest) — 2016-01-21
- 1.3.1 — 2016-01-21
- 1.3.0 — 2016-01-20
- 1.2.1 — 2016-01-20
- 1.2.0 — 2016-01-20

## README

# OAuth2orize-koa

[![Build](https://travis-ci.org/ortoo/oauth2orize.svg?branch=master)](https://travis-ci.org/ortoo/oauth2orize)
[![Coverage](https://coveralls.io/repos/ortoo/oauth2orize/badge.svg?branch=master)](https://coveralls.io/r/ortoo/oauth2orize)
[![Quality](https://codeclimate.com/github/ortoo/oauth2orize/badges/gpa.svg)](https://codeclimate.com/github/ortoo/oauth2orize)
[![Dependencies](https://david-dm.org/ortoo/oauth2orize.svg)](https://david-dm.org/ortoo/oauth2orize)
[![Tips](https://img.shields.io/gratipay/jaredhanson.svg)](https://gratipay.com/jaredhanson/)

This is a complete koa port of [OAuth2orize](https://github.com/jaredhanson/oauth2orize).
OAuth2orize is an authorization server toolkit for Node.js.  It provides a suite
of [koa v2](https://github.com/koajs/koa) middleware that can be used
to assemble a server that implements the [OAuth 2.0](http://tools.ietf.org/html/rfc6749)
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](https://github.com/jaredhanson/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](http://passportjs.org/) strategies are used to authenticate the
client, in this case using either an HTTP Basic authentication header (as
provided by [passport-http](https://github.com/jaredhanson/passport-http)) or
client credentials in the request body (as provided by
[passport-oauth2-client-password](https://github.com/jaredhanson/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](https://github.com/jaredhanson/passport-http-bearer))

## Examples

This [example](https://github.com/ortoo/oauth2orize/tree/master/examples/express2) demonstrates
how to implement an OAuth service provider, complete with protected API access.

## Related Modules

- [oauth2orize-openid](https://github.com/ortoo/oauth2orize-openid) — Extensions to support OpenID Connect

## Tests

    $ npm install
    $ npm test

## Debugging

oauth2orize uses the [debug module](https://www.npmjs.org/package/debug).  You can enable debugging messages on the console by doing ```export DEBUG=oauth2orize``` before running your application.

## Credits

  - [Jared Hanson](http://github.com/jaredhanson)

## License

[The MIT License](http://opensource.org/licenses/MIT)

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

---
_Source: https://npm.io/package/oauth2orize-koa · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
