Coder Social home page Coder Social logo

permit's Introduction

An unopinionated authentication library
for building Node.js APIs.



UsageWhy?PrinciplesExamplesDocumentation



Permit makes it easy to add an authentication layer to any Node.js API. It can be used with any of the popular server frameworks (eg. Express, Koa, Hapi, Fastify) and it can be used for any type of API (eg. REST, GraphQL, etc.) due to its simple, unopinionated design.


Usage

Permit lets you authenticate via the two schemes most APIs need: a single secret bearer token, or a set of username and password credentials. For example, here's how to authenticate a bearer token:

import { Bearer } from 'permit'

// A permit that checks for HTTP Bearer Auth, falling back to a query string.
const permit = new Bearer({
  query: 'access_token',
})

async function handler({ req, res }) {
  // Try to find the bearer token in the request.
  const token = permit.check(req)

  // No token, that means they didn't pass credentials!
  if (!token) {
    permit.fail(res)
    throw new Error(`Authentication required!`)
  }

  // Authenticate the token however you'd like...
  const user = await db.users.findByToken(token)

  // No user, that means their credentials were invalid!
  if (!user) {
    permit.fail(res)
    throw new Error(`Authentication invalid!`)
  }

  // They were authenticated, so continue with your business logic...
  ...
}

Since Permit isn't tightly coupled to a framework or data model, it gives you complete control over how you write your authentication logic—the exact same way you'd write any other request handler.


Why?

Before Permit, the only real choice for authentication libraries in Node.js was Passport.js. But it has a bunch of issues that complicate your codebase...

  • It is not focused on authenticating APIs. Passport is focused on authenticating web apps with services like Facebook, Twitter and GitHub. APIs don't need that, so all the extra bloat means lots of complexity for no gain.

  • It is tightly-coupled to Express. If you use Koa, Hapi, Fastify, or some other framework you have to go to great lengths to get it to play nicely. Even if you just want to tweak the opinionated defaults you're often out of luck.

  • Other middleware are tightly-coupled to it. Passport stores state on the req object, so all your other middleware (even other third-party middleware) become tightly coupled to its implementation, making your codebase brittle.

  • It results in lots of hard to debug indirection. Because of Passport's black-box architecture, whenever you need to debug an issue it's causing you have to trace its logic across many layers of indirection and many repositories.

  • It's not very actively maintained. Passport's focus on OAuth providers means that it takes on a huge amount of scope, across a lot of repositories, many of which are not actively maintained anymore.

Don't get me wrong, Passport works great for working with OAuth providers. But if you've run into any of these problems before while adding authentication to a Node.js API, you might like Permit.

Which brings me to how Permit solves these issues...


Principles

  1. API first. Permit was designed with authenticating APIs in mind, so it's able to be much leaner than others, since it doesn't need to handle complex OAuth integrations with Facebook, Google, etc.

  2. Stateless requests. Since the vast majority of APIs are stateless in nature, Permit eschews the complexity that comes with handling session stores—without preventing you from using one if you need to.

  3. Framework agnostic. Permit doesn't lock you into using any specific server framework or data model, because it's composed of small but powerful utility functions that do the heavy-lifting for you.

  4. Unopinionated interface. Due to its simple interface, Permit makes it much easier to write and reason about your actual authentication logic, because it's exactly like writing any other route handler for your API.


Examples

Permit's API is very flexible, allowing it to be used for a variety of use cases depending on your server framework, your feelings about ORMs, your use of promises, etc. Here are a few examples of common patterns...


Documentation

Read the getting started guide to familiarize yourself with how Permit works, or check out the full API reference for more detailed information...


Thanks

Thank you to @dresende for graciously transferring the permit package!


License

This package is MIT-licensed.

permit's People

Contributors

albinotonnina avatar dependabot[bot] avatar ianstormtaylor avatar lazarljubenovic avatar starptech avatar theahmedsaeed avatar tmus avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

permit's Issues

Getting started

I'm new to ES6 in Node.

However getting some errors, when i try:

// index.mjs
import {
  Bearer
} from 'permit'
console.log('auwa')

node -v => 10.0.0

npm init .

npm i permit --save

RUNNING

node --experimental-modules index.mjs

node --experimental-modules index.mjs 
(node:515) ExperimentalWarning: The ESM module loader is experimental.
file:///****************/index.mjs:2
  Bearer
  ^^^^^^
SyntaxError: The requested module 'permit' does not provide an export named 'Bearer'
    at ModuleJob._instantiate (internal/modules/esm/module_job.js:89:21)

Howto solve or run in another way?

add Digest scheme support

We could add support for the Digest scheme from RFC 7616. It's not really necessary, because it seems rarely used due to its downsides, but it might be nice to complete the set maybe.

add OAuth scheme support

I think it might be possible to create a simple OAuth permit that could be configured by the user to support things like Facebook, GitHub, etc. without having to create one for each like Passport and others do.

Access token in cookie

Do you have any plans to implement being able to read the access token from a http only cookie? Many people are now suggesting storing access tokens in http only cookies so that they are never exposed in the browser. Would be a good addition to this lib.

bearer token use in protected resources server

Hello @ianstormtaylor,

coming from Bearer Token Usage environment there are a couple of things I couldn't find in your library. These might make sense to adopt so that the library is ready for use for Resource Servers.

  1. Clients MUST NOT use more than one method to transmit the token in each request. Currently when both header and query is presented header is returned. An error should be thrown instead.
  2. Three methods of sending bearer access tokens are defined, application/x-www-form-urlencoded body is missing at the moment. I understand this might be tricky to explain to users but most commonly req.body is populated by popular body parsers in frameworks such as express, for koa-body an option needs to be passed ({ patchNode: true }).

What's your opinion on this and would you accept a PR filling it in? My proposal,

  • export OAuth2Bearer with these extra features
  • throw when multiple methods are presented
  • check for req.body access_token param

fastify example broken

The current fastify example can't work because the interface is wrong. I think you copy & paste it from Koa.

Look here for examples

add `options.header` to Bearer permit

This seems like a common thing people do in APIs, allowing the token to be passed as a custom header like X-Company-Token: {token} instead of in Authorization: Bearer {token}, so if anyone has a need for this this is something I'd be down for.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.