Convert Figma logo to code with AI

ianstormtaylor logopermit

An unopinionated authentication library for building Node.js APIs.

1,697
70
1,697
9

Top Related Projects

An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser

Role and Attribute based Access Control for Node.js

Access control lists for node applications

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Quick Overview

Permit is a lightweight, unopinionated authorization library for JavaScript applications. It provides a simple and flexible way to manage permissions and roles in both client-side and server-side environments, making it easy to implement access control in your projects.

Pros

  • Simple and intuitive API for defining and checking permissions
  • Supports both role-based and attribute-based access control
  • Lightweight and has no dependencies
  • Works in both browser and Node.js environments

Cons

  • Limited built-in features compared to more comprehensive authorization frameworks
  • Requires manual implementation of permission logic
  • May not be suitable for complex authorization scenarios out of the box
  • Documentation could be more extensive

Code Examples

  1. Creating a new Permit instance and defining roles:
import Permit from 'permit'

const permit = new Permit()

permit.define('user', ['read'])
permit.define('admin', ['read', 'write', 'delete'])
  1. Checking permissions:
const user = { role: 'user' }
const admin = { role: 'admin' }

console.log(permit.has(user, 'read'))    // true
console.log(permit.has(user, 'write'))   // false
console.log(permit.has(admin, 'delete')) // true
  1. Using attribute-based access control:
permit.define((user, action, resource) => {
  if (action === 'edit' && resource.type === 'post') {
    return user.id === resource.authorId
  }
  return false
})

const user = { id: 123 }
const post = { type: 'post', authorId: 123 }

console.log(permit.has(user, 'edit', post)) // true

Getting Started

To use Permit in your project, first install it via npm:

npm install permit

Then, import and initialize Permit in your application:

import Permit from 'permit'

const permit = new Permit()

// Define roles and permissions
permit.define('user', ['read'])
permit.define('admin', ['read', 'write', 'delete'])

// Check permissions
const user = { role: 'user' }
console.log(permit.has(user, 'read'))    // true
console.log(permit.has(user, 'write'))   // false

You can now use Permit to manage authorization throughout your application.

Competitor Comparisons

An authorization library that supports access control models like ACL, RBAC, ABAC in Node.js and Browser

Pros of node-casbin

  • More flexible and powerful policy model with support for RBAC, ABAC, and custom policies
  • Supports multiple policy storage backends (e.g., file, database)
  • Larger community and ecosystem with adapters for various frameworks and databases

Cons of node-casbin

  • Steeper learning curve due to its more complex policy language and configuration
  • May be overkill for simpler authorization scenarios
  • Slightly more verbose API compared to Permit

Code Comparison

node-casbin:

const enforcer = await newEnforcer('model.conf', 'policy.csv');
const allowed = await enforcer.enforce('alice', 'data1', 'read');

Permit:

const permit = new Permit({ rules });
const allowed = permit.check('alice', 'read', 'data1');

Summary

node-casbin offers more advanced features and flexibility, making it suitable for complex authorization scenarios. However, this comes at the cost of increased complexity and a steeper learning curve. Permit, on the other hand, provides a simpler API and is more straightforward to set up, making it ideal for projects with simpler authorization needs. The choice between the two depends on the specific requirements of your project and the level of complexity you're willing to manage in your authorization system.

Role and Attribute based Access Control for Node.js

Pros of AccessControl

  • More comprehensive and feature-rich, offering advanced RBAC capabilities
  • Supports attribute-based access control (ABAC) in addition to RBAC
  • Better suited for complex authorization scenarios with multiple roles and permissions

Cons of AccessControl

  • Steeper learning curve due to more complex API and concepts
  • May be overkill for simpler authorization needs
  • Less focus on middleware integration compared to Permit

Code Comparison

AccessControl:

const ac = new AccessControl();
ac.grant('user').createOwn('article');
ac.can('user').createOwn('article').granted; // true

Permit:

const permit = new Permit();
permit.allow('user', 'create', 'article');
permit.check('user', 'create', 'article'); // true

Both libraries provide similar functionality for basic role-based access control, but AccessControl offers more advanced features and granular control. Permit focuses on simplicity and middleware integration, making it easier to use for simpler authorization scenarios.

AccessControl is better suited for complex applications with intricate permission structures, while Permit excels in straightforward use cases and seamless integration with Express-like middleware stacks.

Choose AccessControl for advanced RBAC/ABAC needs, and Permit for simpler authorization requirements with easy middleware integration.

Access control lists for node applications

Pros of node_acl

  • More comprehensive ACL system with roles, resources, and permissions
  • Supports backend storage (e.g., Redis, MongoDB) for scalability
  • Provides middleware for Express.js integration

Cons of node_acl

  • More complex setup and configuration
  • Steeper learning curve for beginners
  • Less actively maintained (last update in 2019)

Code Comparison

node_acl:

acl.allow('guest', 'blogs', 'view');
acl.isAllowed('joed', 'blogs', 'view', function(err, res) {
  if (res) {
    console.log("User is allowed");
  }
});

permit:

const permit = new Permit({ secret: 'secret' })
const token = permit.sign({ id: 1 })
const payload = permit.verify(token)

Summary

node_acl offers a more robust ACL system with backend storage support, making it suitable for complex applications. However, it has a steeper learning curve and is less actively maintained. permit, on the other hand, provides a simpler, token-based authorization system that's easier to set up and use, but may lack some advanced features for complex ACL scenarios.

JsonWebToken implementation for node.js http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html

Pros of node-jsonwebtoken

  • Widely adopted and well-maintained library for JWT handling
  • Supports various algorithms and provides flexibility in token creation and verification
  • Extensive documentation and community support

Cons of node-jsonwebtoken

  • Focused solely on JWT, lacking broader authentication features
  • Requires additional setup for integrating with different authentication strategies
  • May need extra middleware for handling token extraction from requests

Code Comparison

node-jsonwebtoken:

const jwt = require('jsonwebtoken');
const token = jwt.sign({ userId: 123 }, 'secret', { expiresIn: '1h' });
const decoded = jwt.verify(token, 'secret');

permit:

const Permit = require('permit');
const permit = new Permit(['bearer']);
const token = await permit.check(req);

Key Differences

  • permit provides a higher-level abstraction for authentication, supporting multiple strategies
  • node-jsonwebtoken offers more granular control over JWT creation and verification
  • permit simplifies token extraction from requests, while node-jsonwebtoken focuses on token operations

Use Cases

  • Choose node-jsonwebtoken for projects requiring specific JWT handling and customization
  • Opt for permit when seeking a more comprehensive authentication solution with built-in support for various strategies

Both libraries have their strengths, and the choice depends on the project's specific authentication requirements and complexity.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

An unopinionated authentication library
for building Node.js APIs.



Usage • Why? • Principles • Examples • Documentation



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.

NPM DownloadsLast 30 Days