Vallo
Vallo

Reputation: 1967

Authorize FeathersJs service based on Auth0 scope

I have a user service in my feathers.js API. I want to make the find method available only for authenticated users who have read:users scope set.

I use express-jwt as a middleware for authentication. I've tried using express-jwt-authz for authorization but I can't since req is not available inside a hook. express-jwt library sets scopes in req.user

Usage The JWT authentication middleware authenticates callers using a JWT. If the token is valid, req.user will be set with the JSON object decoded to be used by later middleware for authorization and access control.

Is there a way I can access the scopes in the access_token inside a hook?

I want to be able to do something like this:

module.exports = {
  before: {
    all: [],
    find: [ authorize(['read:users']) ],
    get: [ authorize(['read:users'])],
    create: [ authorize(['write:users']) ],
    update: [ authorize(['write:users'])   ],
    patch: [ authorize(['write:users'])  ],
    remove: [ authorize(['write:users'])  ]
  }
};

Upvotes: 0

Views: 163

Answers (1)

Vallo
Vallo

Reputation: 1967

Solved it by adding a middleware which adds the req.user data to req.feathers.scope.

my src/middleware/index.js file

const addUserToReq = function(req, res, next) {
  req.feathers.user = req.user; next();
};

module.exports = function (app) {
  app.use(checkJwt); // express-jwt logic
  app.use(addUserToReq);
};

then inside the hook I can access this info like this

module.exports = function(expectedScopes) {
  return context => {
      let scopes = context.params.user.scope;
    }
  };
};

Upvotes: 1

Related Questions