JavaScript/Vue

[Vue] Vue Apollo GraphQL Authorization(Nest.js)

KMSEOP 2020. 12. 4. 11:06
728x90

1. Nest.js Auth module

GraphQL로 Guard를 사용하려면 AuthGuard 클래스의 getRequest() 메소드를 오버라이드 해야함

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  getRequest(context: ExecutionContext) {
    const ctx = GqlExecutionContext.create(context);
    return ctx.getContext().req;
  }
}

 

@Module({
  imports: [
    GraphQLModule.forRoot({
      autoSchemaFile: 'schema.gql',
      context: ({ req }) => ({ req }),
    }),
    AuthModule,
  ],
  exports: [],
  controllers: [],
  providers: [],
})
export class AppModule {}

 

참고

docs.nestjs.com/security/authentication#request-scoped-strategies

 

Documentation | NestJS - A progressive Node.js framework

Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines elements of OOP (Object Oriented Progamming), FP (Functional Programming), and FRP (Functional Reac

docs.nestjs.com

 

2. Vue Apollo setting

// plugins/apollo.ts

// HTTP connection to the API
const httpLink = createHttpLink({
  uri: "http://localhost:3000/graphql"
});

const authLink = setContext((_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = Vue.$cookies.get("access_token");

  // return the headers to the context so httpLink can read them
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : ""
    }
  };
});

// Create the apollo client
export const apolloClient = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache(),
  connectToDevTools: true
});

export const apolloProvider = new VueApollo({
  defaultClient: apolloClient
});
728x90