Purpose: To learn to keep a user "logged in" until the user is "logged out." In Project Part 6, you will create this login experience and will also use level-based authorization, all using the popular JSON Web Tokens (JWT) method.
The Persistence Problem: Web servers take one request at a time. They are asynchronous listeners. That is great for having multiple users communicate with them, but bad for the idea of creating a continuous "login" experience. "Persistence" means keeping a logical connection alive between a logged-in client and a server even though the physical connection goes dormant between requests, and even though requests from other users may come in between.
Persistence Solutions: Perhaps the most obvious solution to the persistence problem would be to send a username and password with every request. However, this is inefficient (it usually requires a database lookup) and at least a little insecure (more opportunities to intercept sensitive information). Typical solutions to the persistence problem get around this in one of two ways: (1) Server-side sessions (session information is stored for each user on the server, and the client sends a session id token with each request), and (2) Client-side tokens (session information is not necessarily stored on the server, but the client sends a decodeable token with a request that has enough information to keep the client authorized). Solutions usually use one or both of these methods.
JSON Web Tokens: In this class, we will practice a method from the second category -- creating client-side decodeable tokens using the popular JSON Web Tokens (JWT) method. It is popular because the server does not need to store any user session information at all, making it so the server can have an unlimited number of users logged in at once without getting its resources bogged down.
The Authorization Problem: The term "authorization" always comes up in connection with authentication and persistence, because a logged in user is authorized to do things that a non-logged-in user is not. The term "authorization" is broader than that as well, because systems usually authorize certain users to access resources others cannot (admins versus customers, or one kind of employee versus another, for example). There are many kinds of authorization schemes, from simple level-based or role-based authorization to more complex resource-specific authorization schemes. In Project Part 6, you will be asked to implement simple level-based authorization in addition to logged-in / logged-out authorization.
JWT Tokens in General: JWT tokens are popular because they are simple and allow the server to store all necessary authorization information in the client's encrypted token. They work using the following process:
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImJhdG1hbiIsImV4cCI6MTc2MzQwNTUxMH0.W6GBIv8_a-D2hPRH6wFajHhwS8yUtyL6hIWz9DRhCBM
(where the token is the random-looking string after the word "Bearer")The Token is actually a JSON object (containing enough user information to authenticate the user, as well as expiration information) encrypted with a secret key stored on the server. Unlike the one-way hash algorithm used in Exercise 6.1, the encryption in this case must be decodeable (symmetric encryption). We will use the popular HS256 algorithm for this, which is implemented for you by the pyjwt library. Expiration information is crucial when using client-side bearer tokens since the server does not store enough information about the logged-in users to turn the login "off." Bearer tokens put this control in the hands of the user. If the capability to turn logins "off" is desired, it needs to be implemented using server-side sessions (usually using server-side sessions; there is a good Flask library for this called flask_session).
Please begin with this version of the app created in Exercise 5.2A-E. Take a moment to run it and re-familiarize yourself as needed.
Near the end of the Module 5 exercises, we added a secret route called "/secret", but it was not really protected (or rather, the only protection was that the /secret URL was not linked to the nav). The goal of the rest of this exercise is to really protect it with login and JWT token persistence.
Make the following changes in the reactapp portion of the code:
Step 1: Back End check_login function. Create a new model file in flaskapp called model_login.py. Add a minimal check_login function as shown below. The function below does not hash passwords nor check a database. It uses a hard-coded global table as a monkey patch, which is enough for this exercise, although you will add proper database checking for Project Part 6, as well as password hashing as taught in Exercise 6.1. Feel free to add users or change username, password, or level.
Step 2: Add login route. In flaskapp/app.py, add a simple login route that calls this check_login function in app.py, importing functions as needed from model_login.py:
Step 1: Store user info on front end. In reactapp/src, Create a helper file, auth.js, in reactapp/src, where all user info will be stored and retrieved in localStorage.
The localStorage variable was created along with HTML5 and became standard in 2015. It stays persistent across tabs in a single browser and is very easy to manipulate using Javascript or Dev Tools. In the above code, storeUser stores information, readUser reads which user is logged in, and clearUser wipes out.
Step 2: Add Login page on front end. In reactapp/src, create Login.jsx, a component file for a login page. The Login component should return a simple form that sends "username" and "password" to the back end. In App.jsx, add a "/login" route that renders the Login component, wrapped in the standard Layout component.
Step 3: Add login and logout to Nav. Next, make the Nav show a Login link to those not logged in, and a Logout link to those logged in. The code uses the readUser() function to determine whether a user is logged in. If there is no user, it displays a NavLink component for a Sign In button. If there is a user, it displays a Link component for a Sign Out button (because NavLink highlights when the route matches the link and we don't want that for the Sign Out button).
Import from auth.js:
Add inside the Nav component:
After the .map loop, add:
Make the following changes in the flaskapp portion of the code:
Step 1: Install pyjwt. In the flaskapp directory, install the pyjwt library using
Step 2: Secret Key. JWT tokens need to be encrypted using a secret key. In flaskapp/app.py, add a line like the following just under app = Flask(__name__), except that you can set the secret key to any string you want.
Step 3: Add JWT token functionality. Add model functions to create and read JSON Web Tokens, and incorporate them into the login route, as follows:
Step 1: Add token to localStorage. Now that the token is returned from the login route, it can be added to the auth.js functions that use localStorage. In addition, code should be added that removes it automatically from localStorage if it is expired when reading it. Updating auth.js as follows does all that:
Step 2: Code to add token to any AJAX request. Add code to auth.js that will insert the Bearer token into headers that will ultimately be passed to fetch.
The "secret" is currently on the front end. Since there is no such thing as front-end security, we should move the secret to the back end. First, create an API endpoint that checks the user level.
Now, add a function to api.js to make an AJAX call to this endpoint, incorporate it in a new component, Secret.jsx, and put that component in React Router and Nav. The following code snippets should work:
Test this code as follows: