reactjs - react-router auto-login in the onEnter hook -


in react-router examples onenter hook, hook synchronous. in issues it's recommended keep way. what's idiomatic way log in while inside hook?

user-story:

  1. client has localstore token
  2. client navigates directly example.com/mustbeloggedin
  3. before going page, i'd check if have token, if do, attempt gain authorization. if authorized, continue onto route

should use hoc instead of onenter?

i have working, know it's not recommended, , seems brittle, example using immutable store causes same issues issue: https://github.com/rackt/react-router/issues/2365

there number of ways solve challenge, agree recommendation calls in onenter should synchronous. here 2 ways solve challenge.

option 1: don't validate token on page load

it arguably case browser should not validate existing token @ all. is, browser should assume token valid , try load route defined.

on api call failure response server (where actual authentication , authorization occurring), app can handle need re-authenticate way chooses: redirect login page, present login dialog, etc.

the advantage of approach work across all routes employ logic without having specify routes need individually.

option 2: use hoc (recommended)

as suspected, hoc best way go. router attempt render this:

<ensureauthorized checks={mycheckfunction} component={mustbeloggedin} /> 

this kind of flexible hoc optionally run custom authorization checks in addition required authentication checks (like user roles), , render component provided when authentication , checks succeed, , handle failures in consistent way (e.g. rendering login component or redirecting user login page or showing 403-type message, etc).


Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -