Reputation: 19585
I am using Hapi.js to build a simple site with role based authorisation (i.e., Users can see these routes, but Managers can see those routes). From what I've read, it sounds like Hapi's Scopes would be ideal for this.
However, while I know how to specify a route so that it requires a certain scope, the documentation is vague on how I specify what scopes a user has. How do I specify this? What's the lifetime of these objects? Are they sent with every request? Is there tie-in with the claims used in JWTs?
I've read the Hapi API Docs, and I've read this article about using scopes for role based authorisation.
I'm doing the Authentication using hapi-auth-jwt2, if that suggests anything.
TLDR; How do I specify the scopes to which a user has access?
Upvotes: 0
Views: 480
Reputation: 19585
I'm pretty sure this answer is only valid for hapi-auth-jwt2. That said:
User credential object are per client request. By default, they contain whatever is in the claims in your JWT (i.e. credentials == decoded). If you want to override that behaviour, or add any additional stuff in to the credential object, you do that in your validateFunc. ValidateFunc takes a callback, and the third parameter is what you want the credentials object to be. For instance, if your user roles are in a "userRole" claim in your JWT, here's how you'd add it into your credentials.scope:
// in server.register()
server.auth.strategy("jwt", "jwt", {
key: publicKey,
validateFunc: validate,
verifyOptions: {
algorithms: ["RS256"]
}
});
// elsewhere
function validate(decoded, request, callback) {
decoded.scope = decoded.userRole;
return callback(null, true, decoded);
};
That's it. hapi-auth-jwt2 manages the rest. Now, in your server.route() calls, if you set the config object to:
config: {
auth: {
strategy: "jwt",
scope: ["Manager", "Developer"]
}
}
...then only requests with JWTs that have either of those strings in their userRole claim will be able to access that route.
Upvotes: 0