Implementing custom query filtering in apollo-server-express

Most of the requests and changes processed by my server require authorization. But, there are a few specific resolvers that need to be public such as sign-in, register, and forgot-password. How can I enable these resolvers to be accessed selectively and automatically have an authorization barrier for the rest?

Currently utilizing apollo-server-express & type-graphql.

Answer №1

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;
})
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The type 'ReadableStream<any>' cannot be assigned to the parameter type 'ReadableStream'

Is there a way to convert a Blob into a Readable format? import {Readable} from 'stream'; const data: Blob = new Blob( ); const myReadable: Readable = (new Readable()).wrap(data.stream()); myReadable.pipe(ext); Encountering an error: ERROR in s ...

Ways to transfer information from HTML form components to the Angular class

I am currently working with angular 9 and I have a requirement to connect data entered in HTML forms to the corresponding fields in my Angular class. Below is the structure of my Angular class: export interface MyData { field1: string, textArea1 ...

Is it possible to identify unauthorized utilization of web APIs within TypeScript?

Recently, I encountered an issue while using the URLSearchParams.size in my code. To my surprise, it didn't work on Safari as expected. Checking MDN's browser compatibility table revealed that Safari version 16.6 does not support this feature, un ...

Troubleshooting: Issues with APIGateway's Default Integration

I'm currently utilizing the AWS CDK to construct my API Gateway REST API My objective is to have my RestApi configured to automatically return an HTTP 404 error, so I set it up as follows: this.gateway = new apigw.RestApi(this, "Gateway", { ...

Developing a hover-triggered tooltip feature in a React application

A tooltip has been created that appears when hovering over an element, displaying the full name of the product called productName. <div className="product-select-info" onMouseEnter={e => productNameHandleHover(e)} onMouseLeave={productNameHand ...

Displaying an array in HTML where one parameter serves as the key is a common task that

{ "Id": "12345", "length": [ { "review": { "1": { "request": [ { "days" ...

What is the best way to check the value of a Reference type in a CDK stack

I have successfully created resources using the aws cdk library. I am now facing an issue with testing a stack that contains multiple resources. When testing a single resource, everything works fine, but I'm unsure how to test a stack with multiple re ...

Embarking on a new undertaking with Visual Studio 2015 and diving into the world of Angular

My journey to getting Angular2 working in Visual Studio 2015 Pro involved a lot of trial and error, but I eventually found a setup that worked for me. Despite the abundance of instructions out there, I struggled to find clear answers tailored specifically ...

Is it possible to use non-numeric values as keys in a Typescript Map?

During a lesson: private items: Map<number, string> = new Map(); ... this.items[aNumber] = "hello"; Results in this error message: An element has an any type because the expression of type number cannot be used to index type Map<numbe ...

What is the best way to change a blob into a base64 format using Node.js with TypeScript?

When making an internal call to a MicroService in Node.js with TypeScript, I am receiving a blob image as the response. My goal is to convert this blob image into Base64 format so that I can use it to display it within an EJS image tag. I attempted to ach ...

The callback type in TypeScript is used to define the types

I have encountered this scenario: function createCar(name: string, callback: () => void) function buildEngine(name: string): Engine function createCarWithEngine(carName: string, engineName: string, callback: (param: Engine) => void) { let created ...

Is there a way to mock a "find" call in mockingoose without getting back "undefined"?

I am currently working with mockingoose 2.13.2 and mongoose 5.12.2, leveraging Typescript and jest for testing purposes. Within my test scenario, I am attempting to mock a call to my schema's find method. Here is what I have tried: import mockingoose ...

Retrieve a static property from a specific type

I've encountered a dilemma with the code snippet below: class Action { public static DEPENDENCIES: (typeof Action)[] = []; public static MIN_USES: number | null = null; public static MAX_USES: number | null = null; } class SomeAction ext ...

Confirm that a specific value exists within an enumerated set

I am currently using Angular 13.3.9 and typescript 4.6.4. My main objective is to determine if a value is referencing an enum. Below is the code snippet: export enum HttpFunctionalErrorCodes { ACCOUNT_NOT_FOUND = 'ACCOUNT_NOT_FOUND', USER_ ...

Utilizing Partial Types in TypeScript Getter and Setter Functions

Within the Angular framework, I have implemented a component input that allows for setting options, specifically of type IOptions. The setter function does not require complete options as it will be merged with default options. Therefore, it is typed as Pa ...

What is the best way to implement pipes and incorporate reusable action buttons in a Mat-table component for maximum reusability?

I am seeking assistance in creating a reusable component for the Angular Material Mat-table. I have made progress on loading data from the parent component to the child component, as can be seen in StackBlitz, but I now want to apply pipes to the data bef ...

The 'Promise<void>' type cannot be assigned to the 'Promise<xxx>' type

Attempting the following transaction in TypeScript resulted in a compile error. The error message stated: Type 'Promise<void>' is not assignable to type 'Promise<transactionArgument>'. However, the function returns a value o ...

What is the process for importing string data into an Excel document using Angular?

I'm encountering a situation where I have non-JSON data coming from the backend. How can I efficiently write this type of data into an Excel file? To handle this task, I've utilized XLSX and FileSaver libraries by referencing an example on Plunk ...

Guide to highlighting manually selected months in the monthpicker by utilizing the DoCheck function in Angular

I'm facing an issue and I could really use some assistance. The problem seems quite straightforward, but I've hit a roadblock. I have even created a stackblitz to showcase the problem, but let me explain it first. So, I've developed my own t ...

Error in Angular-CLI: The return type of a public method from an exported class is referencing the name 'ErrorObservable' from an external module, but it cannot be named as such

Upon completing the development of an app that mirrors an existing Angular 2 (non-cli) application, I am encountering errors in several of my files now that the project has been transitioned to Angular-CLI. I am puzzled as to why these errors are arising i ...