Hey there, one way to enhance security in your schema definition is by using the @Authorized()
decorator along with the authChecker
function.
Let's take a look at an example of how this can be implemented:
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,
) => {
// Add your own logic here
return false; // return true if the user is authorized
};
// Integrate the Auth checker middleware into your buildSchema method
const schema = await buildSchema(
{
authChecker: userAuthChecker,
resolvers: [...yourresolvers]
}
);
// Define your context for the apollo server setup
const apolloserver = new ApolloServer({
schema, context: (ctx) => {
return ctx;
}
});
// Now, let's put it into action with the @Authorized() decorator
@ObjectType()
export class Resolver extends BaseEntity {
...
@Authorized('Admin') // <---
@Query(returns => [MyModel])
artists() {
return value;
})
}