Joelgullander
Joelgullander

Reputation: 1684

A good way to check if auth token is valid in a SPA

So we are using token validation in our react SPA. The token saved in cookies looks like following:

access_token: "BIG-LONG-ASS_TOKEN"
expires_in: 1538663229368
token_type: "Bearer"

The token expires correctly when hardreloading the page, however when user stays active in client for a couple of days & navigates through other pages/requests I want to be able to log the user off upon token expiration. How is this normally tackled by you guys? I figured I could do a scheduled function that matches my "expires_in" that does the logout redux action when timer is ended, or check it at every route.

All tips is welcomed!

EDIT: Doing it on every route wouldnt be so good either because some api calls can be called on the same route. Basically i'm looking towards being able to dispatch logout from my returned 401/403 but centralized so I dont have to catch it in every authed action I got.

Upvotes: 1

Views: 1354

Answers (2)

Rohan Veer
Rohan Veer

Reputation: 1490

You can create a separate component to authenticate the user something like this :

const AuthenticatedRoute = ({ component: Component, ...rest }) => (
  <Route {...rest} render={(props) => {
      return isValid ? <Component {...props} /> : <Redirect to={{ pathname: '/sign_out' }} />
  }} />
);

const ConnectedAuthenticatedRoute = withRouter(AuthenticatedRoute);
export default ConnectedAuthenticatedRoute;

and the in the routes you can do something like this:

<AuthenticatedRoute exact path="/home" component={Dashboard} />

Upvotes: 1

kristaps
kristaps

Reputation: 1723

When you access your API with an expired token, it probably returns a HTTP status 401 or 403 response, you could check for these responses in the client and do the necessary state changes.

Using only the method above could annoy the user when he tries to perform an action in the UI after some period of inactivity, only to be directed to the login screen. To solve this you could invoke some server endpoint (either something existing or a special endpoint just for token validation) when you detect user presence and ask the user to log in before they had a chance to perform any actions.

Upvotes: 1

Related Questions