我正在尝试使用JWT进行用户身份验证。客户端是带Relay的React应用程序。它通过GraphQL服务的端点与Rails后端通信。
从Rails方面,我已经设置了CORS以确保我在响应中暴露了我的标题。我还将我的JWT设置在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
在React方面,我在我的中继中间件层中设置了选项(例如,来自这里 - https://github.com/nodkz/react-relay-network-layer/blob/master/README.md#middlewares)。但是,这是我无法访问我的标题的地方。它只是在我打印Header {}
时显示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;
}
]
当我查看Chrome的开发者工具时,我看到授权令牌设置正确。
如何从客户端应用程序公开并获取授权令牌?
答案 0 :(得分:0)
什么是resPromise? 如果req是一个承诺,这应该工作
next => req => {
req.then(res => {
console.log(res.headers);
});
}