Authentication Processing in Relay Modern

I use token-based authentication and wonder how to fully link it in Relay Modern. I'm halfway there. I would appreciate any assistance. This is the setup I have:

  • At the top level inside, <App />I represent the entry point <QueryRenderer />.
  • Inside the component <LoginPage />, I have a form that launches LoginUserMutation when submitting. When I provide the correct combination of username and password, I get back the token:
    • I save this token in localStorage throughlocalStorage.setItem('token', token)
    • Then I want to redirect the user to the route /dashboardthroughhistory.push('/dashboard')
  • Inside createRelayEnvironment.js fetchQuery, I determine how to make a network query to the GraphQL server:
    • Here I read if I have a token stored in localStorage ie const token = localStorage.getItem('token');
    • If a token is available, I set the following heading: { ..., 'authorization': 'Bearer ${token}' }. The backend can then authenticate the user.

Suoo so far. Unfortunately, there is one problem that ruined the picture. This setting works fine when the application is initialized after the token has already been stored in localStorage. Not so, though, if you currently have not authenticated without entering a token in localStorage.

, , LoginUserMutation, onComplete. , ? , localStorage. <Dashboard />, . ? - . , , GraphQL. , LoginUserMutation, .

TL;DR

Q1 - - , <Dashboard />, /dashboard.

Q2 w/Relay JSON Web Token (JWT)? , , onComplete LoginUserMutation?

+6
2

. . , , , , . /.

-:

class App extends PureComponent {
  state = {
    environment: createRelayEnvironment(),
  };

  login = () => {
    doLoginMutation({
      onSuccess: () => this.setState({ environment: createRelayEnvironment() }),
    })
  }

  ...
}
0

- , . , . : https://github.com/apollographql/apollo-fetch

middllewares Fetch.

: , .

0

All Articles