Skip to main content
EK Web 1st Semester
Skift Dark/Light/Auto mode Skift Dark/Light/Auto mode Skift Dark/Light/Auto mode Tilbage til forsiden

05 JWT securrity and fetch

Securty with JWT

Prepare for the class

Watch the following videos:

Video: Quick Introduction 9:00

Video: JWT Authentication Tutorial 27:00

Check out these toolbox article:

JWT token authentication and authorization Using rest client to test JWT authentication

In-class exersises

  1. Open a react project and add an apiFacade.js file to the src folder.
  2. 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 using setToken.
  3. 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.)
  4. In your React components, use the apiFacade functions to handle user authentication and authorization. For example, you can call apiFacade.login(username, password) when a user submits a login form, and use apiFacade.loggedIn() to conditionally render components based on the user’s authentication status.