Invalid Auth Token with Rails, Graphql, Apollo Client

后端 未结 7 1562
北海茫月
北海茫月 2021-02-09 13:06

I am trying to get a basic Rails, Graphql, Apollo-Client setup working but having trouble with 422 errors \'invalid auth token\' on the rails side.

Does my use of apoll

7条回答
  •  有刺的猬
    2021-02-09 13:57

    Was running into a 422 error myself on the /graphql endpoint when firing Apollo query client side (React in my case).

    There are 2 major things that could be happening.

    1.) Make triple, quadruple, quintuple... sure that you have not made any typos. the Apollo client config can get quite terse, so just be super prudent about the token setup code you write.

    // Get Token from Meta Tags on Application.html.erb
    
    const getToken = () => document.querySelector('meta[name="csrf-token"]').getAttribute('content');
    
    const token = getToken();
    
    // MiddleWare Operationt that sets the CSRF token on requests to protect from forgery
    const setTokenForOperation = async operation =>
      operation.setContext({
        headers: {
          'X-CSRF-Token': token,
        },
      });
    
    // Link With CSRF Token
    const createLinkWithToken = () =>
      new ApolloLink(
        (operation, forward) =>
          new Observable(observer => {
            let handle;
            Promise.resolve(operation)
              .then(setTokenForOperation)
              .then(() => {
                handle = forward(operation).subscribe({
                  next: observer.next.bind(observer),
                  error: observer.error.bind(observer),
                  complete: observer.complete.bind(observer),
                });
              })
              .catch(observer.error.bind(observer));
    
            return () => {
              if (handle) handle.unsubscribe();
            };
          })
      );
    
    ... other apollo-link middleware stuff like error logging etc
    
    // Tell Apollo client about the endpoint for making queries: (HTTP LINK) - this was default endpoint added by graphql install
    
    
    
    const createHttpLink = () =>
      new HttpLink({
        uri: '/graphql',
        credentials: 'include',
      });
    
    // and finally put it all together 
    
    export const createClient = (cache, requestLink) =>
      new ApolloClient({
        link: ApolloLink.from([createErrorLink(), createLinkWithToken(), createHttpLink()]),
        cache,
      });
    
    

    2.) Protect from Forgery Session fail on 3rd party authentication strategies (ie Devise + CanCan or w/e )

    If your apollo middleware patterns are kosher, then it could be that your authentication strategy might be impeding the request.

    for example I am using devise + cancan, which was also causing some seeming random 422s which was easily solved with some research (see this article https://blog.bigbinary.com/2016/04/06/rails-5-default-protect-from-forgery-prepend-false.html)

    long story short on this part, you may need to have application controller (especially if you are upgrading from a legacy version) load and authorize your current user/resource AFTER the protect from forgery setup (more deets on the article referenced)

    class ApplicationController < ActionController::Base
    protect_from_forgery prepend: true, with: :exception
    
    ... 
    before_action .. whatever else you have going on hereafter
    
    

    Hope this helps.

    Cheers

提交回复
热议问题