Skip to content

Authorization using wrapResolve #219

@Scriptkid2001

Description

@Scriptkid2001

Hi,

first of all thanks to Pavel for implementing the issue I sent him via Twitter Direct.

What I want to acchieve is the ability to check for permissions before a query or mutation is executed. The user info is transmitted via JWT.

What I have done so far:
I've created the method requirePermissions which wraps the resolvers and to which the required permission(s) can be passed as string(s). For now it looks like this:

function requirePermissions(resolvers: Record<string, Resolver>, ...permissions: Array<String>): Record<string, Resolver> {
    Object.keys(resolvers).forEach((k) => {
        resolvers[k].wrapResolve((next) => async (rp) => {
            // to be done
            return next(rp);
        });
    });

    return resolvers;
};

It is meant to be used in the following way:

schemaComposer.Query.addFields({
    ...requirePermissions({
        userById: UserTC.getResolver('findById'),
        userByIds: UserTC.getResolver('findByIds'),
        // ...
    }, 'users:read'),
    // ...

In this case users:read is the required permission string.

The Express request object is passed to the context field in the GraphQLHTTP Middleware:

this.app.use(this.route + '/api', graphqlHTTP((req) => ({
    schema: graphql,
    graphiql: this.debug,
    context: { req }
})));

Now, the following is left to do:

  • Find the user document in MongoDB using username in req.body.username. (Authencity of the JWT is verified via separate middleware, so no need to worry about that.)
  • Check if the user doc includes the required permission string.
  • If so, allow the request.
  • If not, block the request and return an error (e.g. Unauthorized) instead.

Hope someone can point me in the right direction :)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions