用户认证后如何设置Apollo客户端? [英] How to set up Apollo client only after user authenticates?
问题描述
我对如何构建我的 React/GraphQL (Apollo) 应用程序感到有些困惑,因为在用户进行身份验证/登录之前不应建立连接.
目前我有这个:
class App 扩展组件 {使成为() {返回 (<ApolloProvider client={client}><提供者商店={商店}><路由器><div><ul><li><Link to="/">首页</Link></li><li><Link to="/login">登录</Link></li><li><Link to="/signup">注册</Link></li><AuthenticatedRoute 精确路径="/" component={HomePage}/><Route path="/login" component={LoginPage}/><Route path="/signup" component={SignupPage}/>
</路由器></提供者></ApolloProvider>);}}
这是网络接口的创建:
const networkInterface = createNetworkInterface({uri:process.env.NODE_ENV === '开发'?'http://localhost:3000/graphql': '待定',});网络接口.使用([{应用中间件(请求,下一个){如果(!req.options.headers){req.options.headers = {};//如果需要,创建标题对象.}获取用户会话().then(会话=> {//如果存在,则从本地存储中获取身份验证令牌//ID 令牌!req.options.headers.authorization = 会话.getIdToken().getJwtToken();}).catch(错误 => {console.error('哦,这不好');}).然后(下一个);},},]);
我如何组织这一点,以便 Apollo 客户端仅初始化和设置一次,并且仅在用户通过身份验证之后?
我想知道是否可以使用 withApollo 以某种方式访问客户端直接完成 GraphQL auth &以这种方式连接.
想法 2
使用 Redux 跟踪用户状态,用 connect
包裹 App
.当用户进行身份验证时,这会触发 Redux 状态更改,从而触发 App
的 componentDidUpdate
,这可以为 Apollo 创建网络接口,从而导致 App 中的重新渲染
将授权的 client
传递给
.
我使用 ApolloClient 示例 http://dev.apollodata.com/react/auth.html#Header
networkInterface.use([{应用中间件(请求,下一个){如果(!req.options.headers){req.options.headers = {};//如果需要,创建标题对象.}//如果存在,则从本地存储中获取身份验证令牌const token = localStorage.getItem('token');req.options.headers.authorization = 令牌?`Bearer ${token}` : null;下一个();}}])
块 applyMiddleware
在获取到 GraphQL 服务器之前总是会运行,所以你只需要在登录时设置 localStorage
并在注销时删除.
I'm a bit confused on how to structure my React/GraphQL (Apollo) app when no connection should be made until the user authenticates/logs in.
Currently I have this:
class App extends Component {
render() {
return (
<ApolloProvider client={client}>
<Provider store={store}>
<Router>
<div>
<ul>
<li><Link to="/">Home</Link></li>
<li><Link to="/login">Log In</Link></li>
<li><Link to="/signup">Sign Up</Link></li>
</ul>
<AuthenticatedRoute exact path="/" component={HomePage} />
<Route path="/login" component={LoginPage} />
<Route path="/signup" component={SignupPage} />
</div>
</Router>
</Provider>
</ApolloProvider>
);
}
}
Here's the creation of the network interface:
const networkInterface = createNetworkInterface({
uri: process.env.NODE_ENV === 'development'
? 'http://localhost:3000/graphql'
: 'TBD',
});
networkInterface.use([
{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
getUserSession()
.then(session => {
// get the authentication token from local storage if it exists
// ID token!
req.options.headers.authorization = session
.getIdToken()
.getJwtToken();
})
.catch(err => {
console.error('oh, this is bad');
})
.then(next);
},
},
]);
How do I organize this so that the Apollo client is only initialized and set up once, and only after the user has authenticated?
I'm wondering if I could use withApollo to somehow access the client directly and complete the GraphQL auth & connection that way.
Idea 2
Use Redux to track user state, wrap App
with connect
. When the user authenticates, this triggers a Redux state change which triggers App
's componentDidUpdate
which could create the network interface for Apollo, causing a re-render in App
which would pass an authorized client
into <ApolloProvider client={client}>
.
I use ApolloClient example http://dev.apollodata.com/react/auth.html#Header
networkInterface.use([{
applyMiddleware(req, next) {
if (!req.options.headers) {
req.options.headers = {}; // Create the header object if needed.
}
// get the authentication token from local storage if it exists
const token = localStorage.getItem('token');
req.options.headers.authorization = token ? `Bearer ${token}` : null;
next();
}
}])
the block applyMiddleware
will always run before fetching to GraphQL server, so you just need to set localStorage
when login and delete when logout.
这篇关于用户认证后如何设置Apollo客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!