GithubHelp home page GithubHelp logo

node-casbin / koa-authz Goto Github PK

View Code? Open in Web Editor NEW
40.0 4.0 14.0 627 KB

koa-authz is an authorization middleware for Koa2 based on Casbin

Home Page: https://casbin.org/

License: Apache License 2.0

JavaScript 100.00%
casbin koa2 node-casbin authorization middleware koajs

koa-authz's Introduction

Koa-Authz

NPM version NPM download codebeat badge Build Status Coverage Status Discord

Koa-Authz is an authorization middleware for Koa, it's based on Node-Casbin: https://github.com/casbin/node-casbin.

Installation

use casbin v2.x

npm install casbin@2 koa-authz@2 --save

use casbin v3.x

npm install casbin@3 koa-authz@3 --save

Simple Example

const casbin = require('casbin')
const Koa = require('koa')
const app = new Koa()
const authz = require('koa-authz')

// response
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  console.log(new Date() - start)
})

// use authz middleware
app.use(authz({
  newEnforcer: async() => {
    // load the casbin model and policy from files, database is also supported.
    const enforcer = await casbin.newEnforcer('authz_model.conf', 'authz_policy.csv')
    return enforcer
  }
}))

// reload routes
const router = require('koa-router')({prefix: '/user'})
router.get('/', (ctx) => {
  ctx.body = {name: 'Chalin', age: 26}
})
router.put('/', (ctx) => {
  ctx.body = {status: 'success'}
})
app.use(router.routes(), router.allowedMethods())

app.listen(3000)

Use a customized authorizer

This package provides BasicAuthorizer, it uses HTTP Basic Authentication as the authentication method. If you want to use another authentication method like OAuth, you needs to extends BasicAuthorizer as below:

class MyAuthorizer extends BasicAuthorizer {
  // override function
  getUserName () {
    const { username } = this.ctx.state.user
    return username
  }
}

app.use(authz({
  newEnforcer: async () => {
    // load the casbin model and policy from files, database is also supported.
    const enforcer = await casbin.newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv')
    return enforcer
  },
  authorizer: (ctx, option) => new MyAuthorizer(ctx, option)
}))

How to control the access

The authorization determines a request based on {subject, object, action}, which means what subject can perform what action on what object. In this plugin, the meanings are:

  1. subject: the logged-on user name
  2. object: the URL path for the web resource like "dataset1/item1"
  3. action: HTTP method like GET, POST, PUT, DELETE, or the high-level actions you defined like "read-file", "write-blog"

For how to write authorization policy and other details, please refer to the Casbin's documentation.

Getting Help

License

This project is licensed under the Apache 2.0 license.

koa-authz's People

Contributors

balalals avatar hsluoyz avatar nodece avatar selflocking avatar snowliy avatar szy0syz avatar tqcenglish 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

Watchers

 avatar  avatar  avatar  avatar

koa-authz's Issues

Package is problematic on npm

Package is problematic on npm.

  • On the master branch if (!await authzorizer.checkPermission()) { ctx.status = 403 return }
  • On the v2.0 if (!await authzorizer.checkPermission()) { ctx.status = 403 }
  • I install [email protected] and it like v2.0

Question: how can I use customized authorizer ?

maybe a stupid question here...
I got error when I tried to extends BasicAuthorizer as below:

const BasicAuthorizer = require("koa-authz").BasicAuthorizer;
.........
// use CustomizeAuthorizer
class CustomizeAuthorizer extends BasicAuthorizer {
........
}

Error like below:

class CustomizeAuthorizer extends BasicAuthorizer {
                                  ^
TypeError: Class extends value undefined is not a constructor or null
........

how can I import BasicAuthorizer into my app.js??

No permission need return

koa-authz/authz.js

Lines 18 to 39 in 9ca6c22

// authz returns the authorizer, uses a Casbin enforcer as input
module.exports = function authz (options) {
return async (ctx, next) => {
try {
const {newEnforcer, authorizer} = options
const enforcer = await newEnforcer()
if (!(enforcer instanceof Enforcer)) {
throw new Error('Invalid enforcer')
}
const authzorizer = authorizer ? authorizer(ctx, enforcer) : new BasicAuthorizer(ctx, enforcer)
if (!(authzorizer instanceof BasicAuthorizer)) {
throw new Error('Please extends BasicAuthorizer class')
}
if (!await authzorizer.checkPermission()) {
ctx.status = 403
}
await next()
} catch (e) {
throw e
}
}
}

      if (!authzorizer.checkPermission()) {
        ctx.status = 403 // change to return ctx.status=403 ???
      }
      await next()

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.