项目作者: icebob

项目描述 :
Protect services
高级语言: JavaScript
项目地址: git://github.com/icebob/moleculer-protect-services.git
创建时间: 2018-11-10T13:47:37Z
项目社区:https://github.com/icebob/moleculer-protect-services

开源协议:

下载


Moleculer

moleculer-protect-services

This repo demonstrates how to use JWT token to protect service actions. It contains a ServiceGuard middleware and a guard service which implement this feature.

Setup

  1. Generate JWT token for every service. Use the call guard.generate --service myService command in REPL to generate a JWT for a service. The received token put into authToken property in service schema:

    1. module.exports = {
    2. name: "users",
    3. authToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzZXJ2aWNlIjoidXNlcnMiLCJpYXQiOjE1NDE4NTU0ODl9.td1P27_xpFv1P5_j0HLtMwyz-aRF9xQqjLHYIIHcKPE",
    4. ...
    5. }

    In production you had better place it into environment variables like USERS_AUTH_TOKEN and use authToken: process.env.USERS_AUTH_TOKEN in schema

  2. Define restriction in action definition. If restricted property is null or not defined it means the action can be called from every service.

    1. actions: {
    2. create: {
    3. // It can be called by "api" service
    4. restricted: [
    5. "api"
    6. ],
    7. handler(ctx) {}
    8. },
    9. list: {
    10. // It can be called by everyone.
    11. restricted: null,
    12. handler(ctx) {}
    13. },
    14. posts: {
    15. // It can be called by "api" & "posts" service.
    16. restricted: [
    17. "api",
    18. "posts"
    19. ],
    20. handler(ctx) {}
    21. }
    22. },
  3. Add ServiceGuard middleware to moleculer.config.js

    1. module.exports = {
    2. logger: true,
    3. logLevel: "info",
    4. middlewares: [
    5. ServiceGuard
    6. ]
    7. };

Try

Try the following command in REPL:

  • call users.create - throw error because it is called directly, not from the api service
  • call users.list - returns “OK” because it is not restricted
  • call users.posts - throw error because it is called directly, not from api or posts service

  • call posts.createUser - throw error because it is called from posts service and not from api service

  • call posts.userPosts - returns “OK” because it is called from posts service.

  • open http://localhost:3000/api/users/create in the browser - returns “OK” because it is called from the api service.

Start

  1. # Install dependencies
  2. npm install
  3. # Start with REPL
  4. npm run dev