Hi, I'm trying to do token based authentication for my app, I have something like this
async function getHttpLink() {
const httpLink = createHttpLink({
uri: `${hostUrl()}/graphql`
});
const token = await getAuthToken();
const authLink = getAuthLink(token);
return new ApolloClient({
link: authLink.concat(httpLink),
cache: new InMemoryCache()
});
}
function getAuthLink(token) {
const authLink = setContext((_, { headers }) => {
return {
headers: {
...headers,
authorization: token ? `Bearer ${token}` : null,
test: "test"
}
};
});
return authLink;
}
then in my main.js I have something like this
setApolloClient = async () => {
try {
await getHttpLink().then(client => {
this.setState({
client
});
});
} catch (e) {
console.log(e);
}
};
render() {
const Layout = RootNavigator(signedIn, this.isCustomerVerified());
return (
<ApolloProvider client={this.state.client}>
{/*<Layout screenProps={{ setApolloClient: this.setApolloClient }} />*/}
<Layout />
</ApolloProvider>
);
}
Intended outcome:
So the plan is before the user is signed in, the token is nil
After sign in happens, the headers will get the newly created auth token from AsyncStorage.
Actual outcome:
When I check the headers in the servers, token is still nil. I'm pretty sure the token is stored in AsyncStorage as when I refresh it goes skips the login page and goes straight to the home page.
Version
Thanks in advance for any help given, please tell me if you need any more info!
This seems difficult to debug without more of the surrounding code, but here are a few things to try:
await getAuthToken and make sure it is definedLet us know if the steps outlined in https://github.com/apollographql/apollo-client/issues/2897#issuecomment-360747092 helped. Closing for now due to inactivity, but happy to re-open if this is still an issue. Thanks!
return new ApolloClient({
cache,
uri: Api.GRAPH_QL_URL,
clientState: {defaults, resolvers},
request: async operation => {
console.log("Client request: ", {
operationName: operation.operationName,
variables: operation.variables,
query: operation.query
});
let token = await AsyncStorage.getItem(strings.keyToken);
operation.setContext({
headers: {
Accept: "application/json",
authorization: token ? JWT ${token} : ""
}
});
}
});
check the request option
I think you can just call await client.resetStore();, right?
The information here helped me out.
I saved my auth token in the Mutation update callback instead of the onCompleted or the chained mutation promise.
Most helpful comment
return new ApolloClient({
cache,
uri: Api.GRAPH_QL_URL,
clientState: {defaults, resolvers},
request: async operation => {
console.log("Client request: ", {
operationName: operation.operationName,
variables: operation.variables,
query: operation.query
});
let token = await AsyncStorage.getItem(strings.keyToken);
operation.setContext({
headers: {
Accept: "application/json",
authorization: token ?
JWT ${token}: ""}
});
}
});
check the request option