05 JWT securrity and fetch
Video: Quick Introduction 9:00
Video: JWT Authentication Tutorial 27:00
JWT token authentication and authorization Using rest client to test JWT authentication
- Open a react project and add an apiFacade.js file to the src folder.
- Implement the following functions in the apiFacade.js file:
setToken(token): Store the JWT token in local storage.getToken(): Retrieve the JWT token from local storage.loggedIn(): Check if a user is logged in by verifying if a token exists.logout(): Remove the JWT token from local storage.login(username, password): Send a POST request to the login endpoint with the provided username and password, and store the received token usingsetToken.
- Make a test.http file in the root of the project and add a POST request to this login endpoint: https://security.hartmanndemo.dk/api/auth/login with a valid username and password (admin/pass123 or user/pass123). Send the request and verify that you receive a JWT token in the response. (Note: In vs code you can use the REST Client extension to send the request and view the response.)
- In your React components, use the
apiFacadefunctions to handle user authentication and authorization. For example, you can callapiFacade.login(username, password)when a user submits a login form, and useapiFacade.loggedIn()to conditionally render components based on the user’s authentication status.