Access JWT Secured Jhipster API from a React App

Scenario:

You have an Jhipster API server which is secured by JWT.

For example, here
Authentication URL — http://localhost:8080/api/authenticate
Endpoint URL — http://localhost:8080/api/students

In order to access these API through react application, we follow following steps.

  1. POST request to authentication API with request body in format below.

2. The response body and response header after successful authentication has bearer token in following format.

Response Body

Response Header

3. Extract the token either from response body or response header and save it to state variable, browsers’s SessionStorage, LocalStorage as per your requirement.

Note: LocalStorage and sessionStorage are relatively new APIs (meaning, not all legacy browsers will support them) and are near identical with the sole exception of persistence. SessionStorage is only available for the duration of the browser session (and is deleted when the tab or window is closed). LocalStorage survive page reloads. Note that the data stored in localStorage and sessionStorage can easily be read or changed from within the client/browser so should not be relied upon for storage of sensitive or security-related data within applications.

4. Make the API call to endpoint URL with request header having authorization bearer token (just like the one received in response header after successful authentication in Step3 )

The complete code is as folows:

Login.tsx

Above code references to two function onSubmitLogin() & onLogout() and one component HomePage.

HomePage.tsx

Bibliography:

https://stackoverflow.com/questions/19867599/what-is-the-difference-between-localstorage-sessionstorage-session-and-cookies

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store