jeudi 7 décembre 2017

Setting up JWT - Passing token from server to client in header, but cannot parse header in client

I am trying to use JWT for user authentication. The client is a React application with Relay. It is talking to a Rails backend through endpoints served by GraphQL.

From the Rails side, I've set up CORS to make sure that I've exposed my header in the response. I've also set my JWT under Authorization:

class Api::GraphsController < ActionController::Base

def create
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Methods'] = 'POST, GET, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Headers'] = 'Origin, Content-Type, Accept, Authorization, Token'
  headers['Access-Control-Max-Age'] = "1728000"
  headers['Access-Control-Expose-Headers'] = 'content-length'

  #set a fresh token after every request
  headers['Authorization'] = "WOW.WoW.Wow"

  render json: Schema.execute()
end

On the React side, I've set up the options in my Relay middleware layer (example from here - http://ift.tt/2ABuL8m). However, this is where I cannot access my header. It just shows Header {} when I print res.headers.

const options = [
  urlMiddleware({
    url: (req) => getEndpoint()
  }),
  retryMiddleware({
    fetchTimeout: 60000,
    retryDelays: (attempt) => [7000],
    forceRetry: (cb, delay) => { window.forceRelayRetry = cb },
    statusCodes: [500, 503, 504]
  }),
  next => req => {
    req.credentials = 'same-origin'; // provide CORS policy to XHR request in fetch method
    const resPromise = next(req);
    resPromise.then(res => {
      let headers = res.headers //Headers is empty
      let user = res.json.data.user //Body is sent properly

      return res;
    })
    .catch((e) => {
      console.log('=============error===========', e);
    })

    return resPromise;
  }
]

When I look in my Chrome's developer tool, I see the Authorization token being set correctly.

Google Inspector

** How do I expose and get the authorization token from my client application? **

Aucun commentaire:

Enregistrer un commentaire