Reputation: 1191
The majority of queries and mutations that my server is handling require authorization. However, there are a select few resolvers that should be public i.e. sign-in, register, forgot-password. How can I selectively allow these resolves to be hit and by default have an authorization gate for the rest?
Currently using apollo-server-express & type-graphql.
Upvotes: 2
Views: 580
Reputation: 607
Hi there you can user @Authorized()
decorator with authChecker
function on the schema definition,
Here is the example code
import { Request } from "express";
import { ApolloServer, } from "apollo-server-express";
export interface ExpressContext {
req: Request;
}
export const userAuthChecker: AuthChecker<ExpressContext> = async (
{ root, args, context: { req }, info },
roles,
) => {
//Perform your own logic here
return false; // true if the user is authorized
};
// Add your Auth checker middleware to your buildSchema method
const schema = await buildSchema(
{
authChecker: userAuthChecker,
resolvers: [...yourresolvers]
}
);
// then define your context from the apollo server setup
const apolloserver = new ApolloServer({
schema, context: (ctx) => {
return ctx;
}
});
// After Completing the above this is how you put it in action, with @Authorized() // decorator
@ObjectType()
export class Resolver extends BaseEntity {
...
@Authorized('Admin') // <---
@Query(returns => [MyModel])
artists() {
return value;
})
}
Upvotes: 1