├── .eslintignore ├── .eslintrc ├── .github └── workflows │ └── main.yml ├── .gitignore ├── LICENSE ├── README.md ├── examples ├── authz_model.conf └── authz_policy.csv ├── jest.config.js ├── package.json ├── src └── authz.ts ├── test ├── .eslintrc.json ├── authz.test.ts ├── customserver.ts └── server.ts ├── tsconfig.json └── yarn.lock /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | build -------------------------------------------------------------------------------- /.eslintrc: -------------------------------------------------------------------------------- 1 | { 2 | "parser": "@typescript-eslint/parser", 3 | "extends": [ 4 | "plugin:@typescript-eslint/recommended", 5 | "prettier/@typescript-eslint", 6 | "plugin:prettier/recommended" 7 | ], 8 | "rules": { 9 | "prettier/prettier": "error", 10 | "@typescript-eslint/no-explicit-any": "off", 11 | "@typescript-eslint/no-unused-vars": "off", 12 | "@typescript-eslint/explicit-function-return-type": [ 13 | "error", 14 | { 15 | "allowExpressions": true 16 | } 17 | ], 18 | "@typescript-eslint/no-non-null-assertion": [ 19 | "error" 20 | ] 21 | }, 22 | "env": { 23 | "jest": true, 24 | "node": true 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: main 2 | on: [push, pull_request] 3 | jobs: 4 | test: 5 | runs-on: ubuntu-latest 6 | strategy: 7 | matrix: 8 | node: ['^10', '^12', '^14' ] 9 | name: test (${{ matrix.node }}) 10 | steps: 11 | - uses: actions/checkout@v2 12 | - name: Setup node 13 | uses: actions/setup-node@v2 14 | with: 15 | node-version: ${{ matrix.node }} 16 | - run: yarn install --ignore-engines 17 | - run: yarn test --coverage 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (https://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # TypeScript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | # next.js build output 61 | .next 62 | 63 | .idea/ 64 | *.iml 65 | 66 | package-lock.json 67 | 68 | dist/ 69 | 70 | build/ 71 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Express-Authz 2 | 3 | [![NPM version][npm-image]][npm-url] 4 | [![NPM download][download-image]][download-url] 5 | [![codebeat badge](https://codebeat.co/badges/d179eb87-cf80-4ddb-ac94-a72a564a2fda)](https://codebeat.co/projects/github-com-node-casbin-express-authz-master) 6 | [![GitHub Actions](https://github.com/node-casbin/express-authz/workflows/main/badge.svg)](https://github.com/node-casbin/express-authz/actions) 7 | [![Coverage Status](https://coveralls.io/repos/github/node-casbin/express-authz/badge.svg?branch=master)](https://coveralls.io/github/node-casbin/express-authz?branch=master) 8 | [![Release](https://img.shields.io/github/release/node-casbin/express-authz.svg)](https://github.com/node-casbin/express-authz/releases/latest) 9 | [![Discord](https://img.shields.io/discord/1022748306096537660?logo=discord&label=discord&color=5865F2)](https://discord.gg/S5UjpzGZjN) 10 | 11 | [npm-image]: https://img.shields.io/npm/v/casbin-express-authz.svg?style=flat-square 12 | [npm-url]: https://npmjs.org/package/casbin-express-authz 13 | [download-image]: https://img.shields.io/npm/dm/casbin-express-authz.svg?style=flat-square 14 | [download-url]: https://npmjs.org/package/casbin-express-authz 15 | 16 | Express-Authz is an authorization middleware for [Express](https://github.com/expressjs/express), it's based on `Node-Casbin`: [https://github.com/casbin/node-casbin](https://github.com/casbin/node-casbin). 17 | 18 | ## Installation 19 | 20 | ### use casbin v2.x 21 | 22 | ```shell 23 | npm install casbin@2 casbin-express-authz@1 --save 24 | ``` 25 | 26 | ### use casbin v3.x 27 | 28 | ```shell 29 | npm install casbin@3 casbin-express-authz@2 --save 30 | ``` 31 | 32 | or you can simply use, 33 | 34 | ```shell 35 | npm install express casbin casbin-express-authz --save 36 | ``` 37 | 38 | ## Usage with Basic HTTP Authentication 39 | 40 | By default casbin-authz supports HTTP Basic Authentication of the form `Authentication: Basic {Base64Encoded(username:password)}` 41 | 42 | ## Usage with Other HTTP Authentication 43 | 44 | To use other HTTP Authentication like `Bearer/Digest` you can use a custom middleware to define the `res.locals.username` variable and casbin-authz will automatically pick up the value from the variable. 45 | 46 | ```js 47 | const { newEnforcer } = require('casbin'); 48 | const express = require('express'); 49 | const { authz } = require('casbin-express-authz'); 50 | 51 | const app = express(); 52 | const enforcer = await newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv'); 53 | 54 | // set userinfo 55 | app.use((req, res, next) => { 56 | res.locals.username = getUsernameFromToken(); // Your custom function for retrieving username 57 | next(); 58 | }); 59 | 60 | // use authz middleware 61 | app.use(authz({ newEnforcer: enforcer })); 62 | 63 | // response 64 | app.use((req, res, next) => { 65 | res.status(200).json({ status: 'OK' }); 66 | }); 67 | 68 | app.listen(3000); 69 | ``` 70 | 71 | ### Usage with customized authorizer 72 | 73 | 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 implement Authorizer as below: 74 | 75 | ```typescript 76 | import { Enforcer, newEnforcer } from 'casbin'; 77 | import { authz, Authorizer } from 'casbin-express-authz'; 78 | import * as express from 'express'; 79 | 80 | const app = express(); 81 | 82 | class MyAuthorizer implements Authorizer { 83 | private e: Enforcer; 84 | 85 | constructor(e: Enforcer) { 86 | this.e = e; 87 | } 88 | 89 | checkPermission(): Promise { 90 | // do something 91 | return true; 92 | } 93 | } 94 | const e = await newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv'); 95 | 96 | app.use( 97 | authz({ 98 | newEnforcer: e, 99 | authorizer: new MyAuthorizer(e), 100 | }) 101 | ); 102 | 103 | app.listen(3000); 104 | ``` 105 | 106 | ### Usage with customized authorizer class 107 | 108 | When the authorizer needs the request and response object to check the permission, one can pass the constructor of the customized `Authorizer` class instead of an instance. 109 | 110 | ```typescript 111 | import { Enforcer, newEnforcer } from 'casbin'; 112 | import { authz, AuthorizerConstructor } from 'casbin-express-authz'; 113 | import { Request, Response } from 'express'; 114 | 115 | const app = express(); 116 | 117 | class MyAuthorizer implements Authorizer { 118 | private e: Enforcer; 119 | private req: Request; 120 | private res: Respons; 121 | 122 | constructor(req:Request, res:Respons, e: Enforcer) { 123 | this.e = e; 124 | this.req = req 125 | this.res = res 126 | } 127 | 128 | checkPermission(): Promise { 129 | // do something 130 | return true; 131 | } 132 | } 133 | const e = await newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv'); 134 | 135 | app.use( 136 | authz({ 137 | newEnforcer: e, 138 | authorizer: MyAuthorizer, 139 | }) 140 | ); 141 | 142 | app.listen(3000); 143 | ``` 144 | 145 | ## How to control the access 146 | 147 | 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: 148 | 149 | 1. `subject`: the logged-on user name 150 | 2. `object`: the URL path for the web resource like "dataset1/item1" 151 | 3. `action`: HTTP method like GET, POST, PUT, DELETE, or the high-level actions you defined like "read-file", "write-blog" 152 | 153 | For how to write authorization policy and other details, please refer to [the Casbin's documentation](https://casbin.org). 154 | 155 | ## Getting Help 156 | 157 | - [Node-Casbin](https://github.com/casbin/node-casbin) 158 | 159 | ## License 160 | 161 | This project is licensed under the [Apache 2.0 license](LICENSE). 162 | -------------------------------------------------------------------------------- /examples/authz_model.conf: -------------------------------------------------------------------------------- 1 | [request_definition] 2 | r = sub, obj, act 3 | 4 | [policy_definition] 5 | p = sub, obj, act 6 | 7 | [role_definition] 8 | g = _, _ 9 | 10 | [policy_effect] 11 | e = some(where (p.eft == allow)) 12 | 13 | [matchers] 14 | m = g(r.sub, p.sub) && keyMatch(r.obj, p.obj) && (r.act == p.act || p.act == "*") 15 | -------------------------------------------------------------------------------- /examples/authz_policy.csv: -------------------------------------------------------------------------------- 1 | p, alice, /dataset1/*, GET 2 | p, alice, /dataset1/resource1, POST 3 | p, bob, /dataset2/resource1, * 4 | p, bob, /dataset2/resource2, GET 5 | p, bob, /dataset2/folder1/*, POST 6 | p, dataset1_admin, /dataset1/*, * 7 | g, cathy, dataset1_admin 8 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | roots: ['/test'], 3 | transform: { 4 | '^.+\\.tsx?$': 'ts-jest', 5 | }, 6 | testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$', 7 | moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'], 8 | }; 9 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "casbin-express-authz", 3 | "version": "3.0.2", 4 | "description": "casbin-express-authz is an authorization middleware for Express", 5 | "main": "./build/authz.js", 6 | "types": "./build/authz.d.ts", 7 | "scripts": { 8 | "prepack": "npm run lint && npm run test && npm run build", 9 | "build": "tsc", 10 | "lint": "eslint . --ext .ts", 11 | "fix": "eslint . --ext .ts --fix", 12 | "test": "jest" 13 | }, 14 | "files": [ 15 | "build", 16 | "testt", 17 | "examples" 18 | ], 19 | "keywords": [ 20 | "node-casbin", 21 | "casbin", 22 | "expressjs", 23 | "express", 24 | "authz", 25 | "authorization", 26 | "middleware" 27 | ], 28 | "repository": { 29 | "type": "git", 30 | "url": "https://github.com/node-casbin/express-authz.git" 31 | }, 32 | "author": { 33 | "name": "Chalin-Shi", 34 | "email": "18875906195@163.com" 35 | }, 36 | "engines": { 37 | "node": ">= 7.6.0" 38 | }, 39 | "license": "Apache-2.0", 40 | "bugs": { 41 | "url": "https://github.com/node-casbin/express-authz/issues" 42 | }, 43 | "homepage": "https://github.com/node-casbin/express-authz#readme", 44 | "peerDependencies": { 45 | "express": "^4.16.3", 46 | "casbin": "^4.5.0" 47 | }, 48 | "devDependencies": { 49 | "@types/express": "^4.17.6", 50 | "@types/jest": "^25.2.1", 51 | "@types/node": "^13.11.1", 52 | "@typescript-eslint/eslint-plugin": "^2.29.0", 53 | "@typescript-eslint/parser": "^2.29.0", 54 | "coveralls": "^3.0.2", 55 | "eslint": "^6.8.0", 56 | "jest": "^25.5.4", 57 | "prettier": "^2.0.5", 58 | "supertest": "^3.1.0", 59 | "ts-jest": "^25.4.0", 60 | "ts-node": "^8.8.2", 61 | "typescript": "^3.8.3", 62 | "eslint-config-prettier": "^6.11.0", 63 | "eslint-plugin-prettier": "^3.1.3", 64 | "husky": "^4.2.5", 65 | "lint-staged": "^10.2.1", 66 | "pretty-quick": "^2.0.1", 67 | "express": "^4.16.3", 68 | "casbin": "^4.5.0" 69 | }, 70 | "husky": { 71 | "hooks": {} 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/authz.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { Enforcer } from 'casbin'; 16 | import { Request, Response, NextFunction } from 'express'; 17 | 18 | export interface Authorizer { 19 | checkPermission(): Promise; 20 | } 21 | 22 | interface AuthorizerConstructor { 23 | new(req: Request, res: Response, enforcer: Enforcer): Authorizer 24 | } 25 | 26 | // BasicAuthorizer class stores the casbin handler 27 | class BasicAuthorizer implements Authorizer { 28 | req: Request; 29 | res: Response; 30 | enforcer: Enforcer; 31 | 32 | constructor(req: Request, res: Response, enforcer: Enforcer) { 33 | this.req = req; 34 | this.res = res; 35 | this.enforcer = enforcer; 36 | } 37 | 38 | // getUserName gets the user name from the request. 39 | // Currently, only HTTP basic authentication is supported 40 | getUserName(): string { 41 | if (this.res.locals.username != undefined) return this.res.locals.username; 42 | 43 | try { 44 | const header: string = this.req.get('Authorization'); 45 | if (!header) return ''; 46 | const arr: Array = header.split(' '); 47 | if (arr[0].trim() != 'Basic') return ''; 48 | const value: string = Buffer.from(arr[1], 'base64').toString('ascii'); 49 | const tempArr: Array = value.split(':'); 50 | return tempArr[0]; 51 | } catch (e) { 52 | console.log(e); 53 | return ''; 54 | } 55 | } 56 | 57 | // checkPermission checks the user/method/path combination from the request. 58 | // Returns true (permission granted) or false (permission forbidden) 59 | async checkPermission(): Promise { 60 | const { req, enforcer } = this; 61 | const { originalUrl: path, method } = req; 62 | const user = this.getUserName(); 63 | return enforcer.enforce(user, path, method); 64 | } 65 | } 66 | 67 | interface AuthzOptions { 68 | newEnforcer: Promise; 69 | authorizer?: Authorizer | AuthorizerConstructor; 70 | } 71 | 72 | // authz returns the authorizer, uses a Casbin enforcer as input 73 | export function authz(opt: AuthzOptions) { 74 | return async (req: Request, res: Response, next: NextFunction): Promise => { 75 | const enforcer: Enforcer = await opt.newEnforcer; 76 | if (!(enforcer instanceof Enforcer)) { 77 | res.status(500).json({ 500: 'Invalid enforcer' }); 78 | return; 79 | } 80 | 81 | const authorizer = opt.authorizer 82 | ? (typeof opt.authorizer === 'function' 83 | ? new opt.authorizer(req, res, enforcer) 84 | : opt.authorizer 85 | ) 86 | : new BasicAuthorizer(req, res, enforcer); 87 | 88 | const isAllowed = await authorizer.checkPermission(); 89 | if (!isAllowed) { 90 | res.status(403).json({ 403: 'Forbidden' }); 91 | return; 92 | } 93 | next(); 94 | }; 95 | } 96 | -------------------------------------------------------------------------------- /test/.eslintrc.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../.eslintrc", 3 | "env": { 4 | "jest": true 5 | }, 6 | "rules": { 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /test/authz.test.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import server from './server'; 16 | import customServer from './customserver'; 17 | import * as supertest from 'supertest'; 18 | 19 | const request = supertest(server); 20 | const customRequest = supertest(customServer); 21 | 22 | describe('pass through tests', () => { 23 | test('test: p, alice, /dataset1/*, GET', (done) => { 24 | request 25 | .get('/dataset1/name') 26 | .set('Authorization', `Basic ${Buffer.from('alice:password').toString('base64')}`) 27 | .then((response) => { 28 | expect(response.statusCode).toBe(200); 29 | done(); 30 | }); 31 | }); 32 | 33 | test('test: p, alice, /dataset1/resource1, POST', (done) => { 34 | request 35 | .post('/dataset1/resource1') 36 | .set('Authorization', `Basic ${Buffer.from('alice:password').toString('base64')}`) 37 | .then((response) => { 38 | expect(response.statusCode).toBe(200); 39 | done(); 40 | }); 41 | }); 42 | 43 | test('test: bob, /dataset2/folder1/*, POST', (done) => { 44 | request 45 | .post('/dataset2/folder1/file') 46 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 47 | .then((response) => { 48 | expect(response.statusCode).toBe(200); 49 | done(); 50 | }); 51 | }); 52 | 53 | test('test: p, bob, /dataset2/resource1, * - GET', (done) => { 54 | request 55 | .get('/dataset2/resource1') 56 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 57 | .then((response) => { 58 | expect(response.statusCode).toBe(200); 59 | done(); 60 | }); 61 | }); 62 | 63 | test('test: p, bob, /dataset2/resource1, * - POST', (done) => { 64 | request 65 | .post('/dataset2/resource1') 66 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 67 | .then((response) => { 68 | expect(response.statusCode).toBe(200); 69 | done(); 70 | }); 71 | }); 72 | 73 | test('test: p, bob, /dataset2/resource1, * - PUT', (done) => { 74 | request 75 | .put('/dataset2/resource1') 76 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 77 | .then((response) => { 78 | expect(response.statusCode).toBe(200); 79 | done(); 80 | }); 81 | }); 82 | 83 | test('test: p, bob, /dataset2/resource1, * - DELETE', (done) => { 84 | request 85 | .delete('/dataset2/resource1') 86 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 87 | .then((response) => { 88 | expect(response.statusCode).toBe(200); 89 | done(); 90 | }); 91 | }); 92 | 93 | test('test: p, bob, /dataset2/resource2, GET', (done) => { 94 | request 95 | .get('/dataset2/resource2') 96 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 97 | .then((response) => { 98 | expect(response.statusCode).toBe(200); 99 | done(); 100 | }); 101 | }); 102 | 103 | test('test: p & g, dataset1_admin, /dataset1/*, * - GET', (done) => { 104 | request 105 | .get('/dataset1/resource') 106 | .set('Authorization', `Basic ${Buffer.from('cathy:password').toString('base64')}`) 107 | .then((response) => { 108 | expect(response.statusCode).toBe(200); 109 | done(); 110 | }); 111 | }); 112 | 113 | test('test: p & g, dataset1_admin, /dataset1/*, * - POST', (done) => { 114 | request 115 | .post('/dataset1/resource') 116 | .set('Authorization', `Basic ${Buffer.from('cathy:password').toString('base64')}`) 117 | .then((response) => { 118 | expect(response.statusCode).toBe(200); 119 | done(); 120 | }); 121 | }); 122 | 123 | test('test: p & g, dataset1_admin, /dataset1/*, * - PUT', (done) => { 124 | request 125 | .put('/dataset1/resource') 126 | .set('Authorization', `Basic ${Buffer.from('cathy:password').toString('base64')}`) 127 | .then((response) => { 128 | expect(response.statusCode).toBe(200); 129 | done(); 130 | }); 131 | }); 132 | 133 | test('test: p & g, dataset1_admin, /dataset1/*, * - DELETE', (done) => { 134 | request 135 | .delete('/dataset1/resource') 136 | .set('Authorization', `Basic ${Buffer.from('cathy:password').toString('base64')}`) 137 | .then((response) => { 138 | expect(response.statusCode).toBe(200); 139 | done(); 140 | }); 141 | }); 142 | }); 143 | 144 | describe('success through tests', () => { 145 | test('test: p, alice, /dataset1/*, GET - 403', (done) => { 146 | request 147 | .post('/dataset1/users') 148 | .set('Authorization', `Basic ${Buffer.from('alice:password').toString('base64')}`) 149 | .then((response) => { 150 | expect(response.statusCode).toBe(403); 151 | done(); 152 | }); 153 | }); 154 | 155 | test('test: p, alice, /dataset1/resource1, POST - 403', (done) => { 156 | request 157 | .post('/dataset1/resource') 158 | .set('Authorization', `Basic ${Buffer.from('alice:password').toString('base64')}`) 159 | .then((response) => { 160 | expect(response.statusCode).toBe(403); 161 | done(); 162 | }); 163 | }); 164 | 165 | test('test: bob, /dataset2/folder1/*, POST', (done) => { 166 | request 167 | .put('/dataset2/folder1/file') 168 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 169 | .then((response) => { 170 | expect(response.statusCode).toBe(403); 171 | done(); 172 | }); 173 | }); 174 | 175 | test('test: p, bob, /dataset2/resource1, * - GET', (done) => { 176 | request 177 | .get('/dataset2/resource') 178 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 179 | .then((response) => { 180 | expect(response.statusCode).toBe(403); 181 | done(); 182 | }); 183 | }); 184 | 185 | test('test: p, bob, /dataset2/resource1, * - POST', (done) => { 186 | request 187 | .post('/dataset2/resource') 188 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 189 | .then((response) => { 190 | expect(response.statusCode).toBe(403); 191 | done(); 192 | }); 193 | }); 194 | 195 | test('test: p, bob, /dataset2/resource1, * - PUT', (done) => { 196 | request 197 | .put('/dataset2/resource') 198 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 199 | .then((response) => { 200 | expect(response.statusCode).toBe(403); 201 | done(); 202 | }); 203 | }); 204 | 205 | test('test: p, bob, /dataset2/resource1, * - DELETE', (done) => { 206 | request 207 | .delete('/dataset2/resource') 208 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 209 | .then((response) => { 210 | expect(response.statusCode).toBe(403); 211 | done(); 212 | }); 213 | }); 214 | 215 | test('test: p, bob, /dataset2/resource2, GET', (done) => { 216 | request 217 | .post('/dataset2/resource2') 218 | .set('Authorization', `Basic ${Buffer.from('bob:password').toString('base64')}`) 219 | .then((response) => { 220 | expect(response.statusCode).toBe(403); 221 | done(); 222 | }); 223 | }); 224 | 225 | test('test: p & g, dataset1_admin, /dataset1/*, * - GET', (done) => { 226 | request 227 | .get('/dataset1/resource') 228 | .set('Authorization', `Basic ${Buffer.from('chalin:password').toString('base64')}`) 229 | .then((response) => { 230 | expect(response.statusCode).toBe(403); 231 | done(); 232 | }); 233 | }); 234 | 235 | test('test: p & g, dataset1_admin, /dataset1/*, * - POST', (done) => { 236 | request 237 | .post('/dataset1/resource') 238 | .set('Authorization', `Basic ${Buffer.from('chalin:password').toString('base64')}`) 239 | .then((response) => { 240 | expect(response.statusCode).toBe(403); 241 | done(); 242 | }); 243 | }); 244 | 245 | test('test: p & g, dataset1_admin, /dataset1/*, * - PUT', (done) => { 246 | request 247 | .put('/dataset1/resource') 248 | .set('Authorization', `Basic ${Buffer.from('chalin:password').toString('base64')}`) 249 | .then((response) => { 250 | expect(response.statusCode).toBe(403); 251 | done(); 252 | }); 253 | }); 254 | 255 | test('test: p & g, dataset1_admin, /dataset1/*, * - DELETE', (done) => { 256 | request 257 | .delete('/dataset1/resource') 258 | .set('Authorization', `Basic ${Buffer.from('chalin:password').toString('base64')}`) 259 | .then((response) => { 260 | expect(response.statusCode).toBe(403); 261 | done(); 262 | }); 263 | }); 264 | 265 | test('test: p & g, dataset1_admin, /dataset1/*, * - DELETE', (done) => { 266 | request 267 | .delete('/dataset1/resource') 268 | .set('Authorization', `Basic alice`) 269 | .then((response) => { 270 | expect(response.statusCode).toBe(403); 271 | done(); 272 | }); 273 | }); 274 | }); 275 | 276 | describe('pass through custom server tests', () => { 277 | test('test: p, alice, /dataset1/*, GET', (done) => { 278 | customRequest.get('/dataset1/name').then((response) => { 279 | expect(response.statusCode).toBe(200); 280 | done(); 281 | }); 282 | }); 283 | 284 | test('no header and no custom username test', (done) => { 285 | request.put('/dataset1/resource').then((response) => { 286 | expect(response.statusCode).toBe(403); 287 | done(); 288 | }); 289 | }); 290 | 291 | test('different HTTP Authentication test', (done) => { 292 | request 293 | .put('/dataset1/resource') 294 | .set('Authorization', `Bearer awdhdjshdcxckcfk`) 295 | .then((response) => { 296 | expect(response.statusCode).toBe(403); 297 | done(); 298 | }); 299 | }); 300 | 301 | test('invalid header test', (done) => { 302 | request 303 | .put('/dataset1/resource') 304 | .set('Authorization', `awdhdjshdcxckcfk`) 305 | .then((response) => { 306 | expect(response.statusCode).toBe(403); 307 | done(); 308 | }); 309 | }); 310 | 311 | test('test: p & g, dataset1_admin, /dataset1/*, * - DELETE', (done) => { 312 | customRequest.delete('/dataset1/resource').then((response) => { 313 | expect(response.statusCode).toBe(403); 314 | done(); 315 | }); 316 | }); 317 | }); 318 | -------------------------------------------------------------------------------- /test/customserver.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { newEnforcer } from 'casbin'; 16 | import * as express from 'express'; 17 | import { authz } from '../src/authz'; 18 | 19 | const app = express(); 20 | const enforcer = newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv'); 21 | 22 | app.use((req, res, next) => { 23 | res.locals.username = 'alice'; 24 | next(); 25 | }); 26 | // use authz middleware 27 | app.use(authz({ newEnforcer: enforcer })); 28 | 29 | // response 30 | app.use((req, res) => { 31 | res.status(200).json({ 200: 'OK' }); 32 | }); 33 | 34 | export default app; 35 | -------------------------------------------------------------------------------- /test/server.ts: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Casbin Authors. All Rights Reserved. 2 | // 3 | // Licensed under the Apache License, Version 2.0 (the "License"); 4 | // you may not use this file except in compliance with the License. 5 | // You may obtain a copy of the License at 6 | // 7 | // http://www.apache.org/licenses/LICENSE-2.0 8 | // 9 | // Unless required by applicable law or agreed to in writing, software 10 | // distributed under the License is distributed on an "AS IS" BASIS, 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | // See the License for the specific language governing permissions and 13 | // limitations under the License. 14 | 15 | import { newEnforcer } from 'casbin'; 16 | import * as express from 'express'; 17 | import { authz } from '../src/authz'; 18 | 19 | const app = express(); 20 | const enforcer = newEnforcer('examples/authz_model.conf', 'examples/authz_policy.csv'); 21 | 22 | console.log(authz); 23 | // use authz middleware 24 | app.use(authz({ newEnforcer: enforcer })); 25 | 26 | // response 27 | app.use((req, res) => { 28 | res.status(200).json({ 200: 'OK' }); 29 | }); 30 | 31 | export default app; 32 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "outDir": "build", 4 | "target": "es6", 5 | "module": "commonjs", 6 | "moduleResolution": "node", 7 | "typeRoots": ["node_modules/@types"], 8 | "declaration": true, 9 | "declarationDir": "build", 10 | "inlineSourceMap": true 11 | }, 12 | "include": ["src/**/**.ts"], 13 | "exclude": ["node_modules"] 14 | } 15 | --------------------------------------------------------------------------------