The purpose of this exercise is to ensure that malicious actors will not be able to hack into your app and view sensitive data or modify other users’ data. Currently, there is not much danger because the app is only running on your localhost. But soon you will be deploying the app to a public server. So it’s important to batten down the hatches first.
Start by drawing one or more sequence diagrams to represent how access control will be implemented (or is already implemented) in your project.
Feel free to use the same design demonstrated in the class example or slightly change it to fit your specific project needs. For instance, you may decide to store an authentication token [2] in the browser local or session storage [3] (rather than storing it as a cookie [4]) or you may decide to generate a different type of token rather than JWT [5]. For password encryption, besides bcrypt [6], you could also use the built-in node.js crypto module [7].
In your sequence diagram design, cover the sign-up flow (when the user first creates an account), the sign-in flow (when the user logs in and authenticates), and any other ordinary frontend to backend call that requires access control (when the user tries to access an endpoint that is supposed to protected with access control). For readability purposes, it’s a good idea to create a separate diagram for each of those flows.
Also, in your sequence diagram, make sure you include components from all the involved layers of your architecture (frontend, backend, and database).
Implement in your project the designed access control feature.
Take an incremental approach of ‘divide and conquer’ for implementing the full-blown access control feature. Suggestion: start with the sign-up and password encryption to be stored in the user database. Then add token generation and token passing in HTTP the response. On the FE, handle the token received in the response by storing it on the client-side. Implement token passing from FE to BE in HTTP calls to endpoints that require authentication. Make sure your BE handles successful requests and failure requests due to unauthorized users. Implement also a sign-in endpoint to make your BE authenticate an existing user based on a hashed pwd, followed by token generation.
Save your sequence diagram
For future reference, save your sequence diagram and update it if you make changes in your access control feature.
For now, keep a digital copy of it on the readme page of your GitHub repository.
Backend Authentication code
Here is the source code for the example presented in class:
Create a file auth.js that you can import from backend.js. We will import two packages to help us with authentication: bcrypt and jsonwebtoken.
import bcrypt from "bcrypt";
import jwt from "jsonwebtoken";
The module auth.js will export three functions:
registerUserwhich adds a user, along with their encrypted passwordloginUserwhich takes a username and password, and, after verifying the password, generates a JWT authentication tokenauthenticateUsertakes a request, and verifies that the auth headers contain a valid authentication token
In this example, all the user authentication data will be stored (encrypted) in an array in memory.
const creds = [];
So keep in mind that whenever you restart the server, you will need to register your username and password again. In your actual app, you will want to persist this database, but since the passwords are encrypted, you don’t need to worry too much about the security of where you save them.
Let’s start with registerUser. The username and pwd which the user entered will be transmitted in the body of a form. (Never transmit credentials in a URL as query parameters!) First, we do some checks, to make sure neither one is null (a 400 error) and to check if the name already exists (a 409 error).
Then, we encrypt, using the bcrypt.genSalt() and bcrypt.hash() functions. Read more about bcrypt and the reasons for salting passwords.
export function registerUser(req, res) {
const { username, pwd } = req.body; // from form
if (!username || !pwd) {
res.status(400).send("Bad request: Invalid input data.");
} else if (creds.find((c) => c.username === username)) {
res.status(409).send("Username already taken");
} else {
bcrypt
.genSalt(10)
.then((salt) => bcrypt.hash(pwd, salt))
.then((hashedPassword) => {
generateAccessToken(username).then((token) => {
console.log("Token:", token);
res.status(201).send({ token: token });
creds.push({ username, hashedPassword });
});
});
}
}
bcrypt uses promises for its API, because crypto can take some time, and we don’t want to tie up a thread. Once it does produce the hashedPassword, we will store it in our creds list. We do NOT want to share even a hashed password with anyone. It’s only purpose is to verify later password attempts.
After registering a user, you could redirect them to the login page and have them log in with the credentials they just provided. It’s a bit nicer UX to just consider them logged in once they register, though. We don’t need to validate their password, but we do need to generate a token which can use to authenticate the user with our APIs. We will be using JWT tokens for this purpose, and the npm package jsonwebtoken to generate and validate them.
I’ve broken out generateAccessToken into a helper function because 1) we will also need it in loginUser and 2) jsonwebtoken has an asynchronous API which is not promise based. So our helper function will include a promise wrapper around jwt.
function generateAccessToken(username) {
return new Promise((resolve, reject) => {
jwt.sign(
{ username: username },
process.env.TOKEN_SECRET,
{ expiresIn: "1d" },
(error, token) => {
if (error) {
reject(error);
} else {
resolve(token);
}
},
);
});
}
The function jwt.sign takes an object and cryptographically signs it, along with some other information. The second argument (process.env.TOKEN_SECRET) is a key which is used to both encrypt and decrypt the token. Here, we’re storing it in the environment, and dotenv gives us a convenient way to manage it. JWT tokens expire, which limits the damage should one be compromised. The last argument is a callback, which we use to either resolve or reject the promise.
You’ll notice that registerUser has a signature of (req, res) => {...}. This means we can easily mount it at a suitable path in backend.js, like this:
app.post("/signup", registerUser);
Let’s look at protecting some of our API routes behind our new authentication system. For any of our routes, express lets us apply middleware which can process the request and control the rest of the route logic. Middleware functions have a signature of (req, res, next) => {...}, and behave very much like route functions, except that middleware controls when and even if the next middleware or route function gets called, by invoking next.
So, back in auth.js, define the function authenticateUser. This function will look at the request headers for an “authorization” header. We will see soon how the frontend puts this header into the request, but for now, you just need to know the JWT token is part of that header.
export function authenticateUser(req, res, next) {
const authHeader = req.headers["authorization"];
//Getting the 2nd part of the auth header (the token)
const token = authHeader && authHeader.split(" ")[1];
if (!token) {
console.log("No token received");
res.status(401).end();
} else {
jwt.verify(token, process.env.TOKEN_SECRET, (error, decoded) => {
if (decoded) {
next();
} else {
console.log("JWT error:", error);
res.status(401).end();
}
});
}
}
Once we have the token, we can verify it using jwt.verify and the same secret we used to generate it. This ensures that the token was created by this server, or another server which we (intentionally) shared the secret with. It’s relatively quick to run jwt.verify (we will run it on every API request), but still, it’s a good idea to use the callback form. Besides, next is already a callback so it’s convenient to just chain them togther like this.
With our authenticateUsers middleware, we can now protect any routes we want. For example, to protect the POST to /users we do this where the route is defined (in backend.js):
app.post("/users", authenticateUser, (req, res) => {
const userToAdd = req.body;
Users.addUser(userToAdd).then((result) => res.status(201).send(result));
});
You will probably want to protect all of your data routes in this way. Just make sure you do not protect signup or login.
The last function we need on the backend is loginUser, which will compare the password entered in the login form with the encrypted password in the database. bcrypt gives us a way to do this with the bcrypt.compare function. (If it wasn’t for the salt, we could just encrypt the attempted password and see if it matches the encrypted one; this make bcrypt harder to crack.)
loginUser starts by using the username as a key to find the credentials record in our “database”. If there is no match, the username doesn’t exist and we reply with a 401. Otherwise, we use bcrypt.compare to see if the password in the request is a match for the encrypted one. If it is, we generate the access token and send it back to the client. Otherwise, it is a password mismatch and we reply with 401.
export function loginUser(req, res) {
const { username, pwd } = req.body; // from form
const retrievedUser = creds.find((c) => c.username === username);
if (!retrievedUser) {
// invalid username
res.status(401).send("Unauthorized");
} else {
bcrypt
.compare(pwd, retrievedUser.hashedPassword)
.then((matched) => {
if (matched) {
generateAccessToken(username).then((token) => {
res.status(200).send({ token: token });
});
} else {
// invalid password
res.status(401).send("Unauthorized");
}
})
.catch(() => {
res.status(401).send("Unauthorized");
});
}
}
As with registerUser, this function can be used to handle a route, so add (to backend.js):
app.post("/login", loginUser);
Frontend Authentication Code
If you run the frontend after making those backend changes, you should see that the app comes up, but there is no data in the table, even if there are users in the database. Using Developer Tools, check the response from the GET /users call. If it’s protected by authenticateUser, then it will return a 401 error. More than likely, your app isn’t checking the HTTP status on this get, and is interpreting the results as an empty list. To make things easier to debug, we’re going to first start by checking that status and displaying “Data Unavailable” instead of an empty table.
Edit the useEffect in MyApp, replacing the two .then() calls like this:
useEffect(() => {
fetchUsers()
.then((res) =>
res.status === 200 ? res.json() : undefined
)
.then((json) => {
if (json) {
setCharacters(json["users_list"]);
} else {
setCharacters(null);
}
})
.catch
...
}
Now, when we display the table we can check for null and display “Data Unavailable” instead. This is in the TableBody function in Table.js:
function TableBody(props) {
if (props.characterData === null) {
return <caption>Data Unavailable</caption>;
}
...
Make this change and then confirm that you get “Data Unavailable” instead of an empty table.
Now, let’s look at how the frontend requests an auth token so that it can access the data. We know from our sequence diagram, and from implementing the backend, that the frontend can get an auth token by a login request or a signup request. We definitely need a login page, so let’s start there.
Create a file Login.js in react-frontend. It will display a form with “Username” and “Password” entries, much like the Form component we built earlier. It will also take a handleSubmit property which wil doing the actually logging in:
import React, { useState } from "react";
function Login(props) {
const [creds, setCreds] = useState({
username: "",
pwd: "",
});
return (
<form>
<label htmlFor="username">UserName</label>
<input
type="text"
name="username"
id="username"
value={creds.username}
onChange={handleChange}
/>
<label htmlFor="password">Password</label>
<input
type="password"
name="password"
id="password"
value={creds.pwd}
onChange={handleChange}
/>
<input
type="button"
value={props.buttonLabel || "Log In"}
onClick={submitForm}
/>
</form>
);
function handleChange(event) {
const { name, value } = event.target;
switch (name) {
case "username":
setCreds({ ...creds, username: value });
break;
case "password":
setCreds({ ...creds, pwd: value });
break;
}
}
function submitForm() {
props.handleSubmit(creds);
setCreds({ username: "", pwd: "" });
}
}
export default Login;
Add a route (in MyApp.js) for login, and display this form at that route:
<Route path="/login" element={<Login handleSubmit={loginUser} />} />
Now, what does loginUser do? It has to take the state of the form, and make a request to the backend /login route. The request will contain the username and password in a JSON-formatted body.
function loginUser(creds) {
const promise = fetch(`${API_PREFIX}/login`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(creds),
})
.then((response) => {
if (response.status === 200) {
response.json().then((payload) => setToken(payload.token));
setMessage(`Login successful; auth token saved`);
} else {
setMessage(`Login Error ${response.status}: ${response.data}`);
}
})
.catch((error) => {
setMessage(`Login Error: ${error}`);
});
return promise;
}
You should recognize this as being very similar to our other POST requests. Notice that when the response comes back, if it’s a 200, it will contain the token in the response’s json. We’re just going to store that token in state, which is good enough for a single page app. You could save it using localStorage, or even do the old school thing and put it in a cookie.
To create the state for the token, you can add a useState to the top of MyApp. You’ll notice I also have a rudimentary messaging system, based on a useState, for messages.
const INVALID_TOKEN = "INVALID_TOKEN";
const [token, setToken] = useState(INVALID_TOKEN);
const [message, setMessage] = useState("");
Now that we have the token on the client, let’s add authentication to all of our API requests. The token is passed to the server in the headers, under the key “Authorization”.
Here’s how it works for fetchUsers:
function fetchUsers() {
const promise = fetch(`${API_PREFIX}/users`, {
headers: addAuthHeader()
});
return promise;
}
addAuthHeader is a helper function that add the correct Authorization header. If you have other headers already, you can pass them to addAuthHeader, like this:
const promise = fetch(`${API_PREFIX}/users`, {
method: "POST",
headers: addAuthHeader({
"Content-Type": "application/json",
}),
body: JSON.stringify(person),
});
Here’s the definition of addAuthHeader:
function addAuthHeader(otherHeaders = {}) {
if (token === INVALID_TOKEN) {
return otherHeaders;
} else {
return {
...otherHeaders,
Authorization: `Bearer ${token}`,
};
}
}
At this point, all that’s needed is to get our password into the database so we can log in. You could do that manually (with curl, postman, or boomerang), which might be helpful for testing. But, it turns out, we almost have a signup page ready to go, since it’s just the login page with a different handleSubmit. We’re also going to change the button to say “Sign Up”. Here’s the route:
<Route
path="/signup"
element={<Login handleSubmit={signupUser} buttonLabel="Sign Up" />}
/>
And signupUser is very similar to loginUser:
function signupUser(creds) {
const promise = fetch(`${API_PREFIX}/signup`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(creds),
})
.then((response) => {
if (response.status === 201) {
response.json().then((payload) => setToken(payload.token));
setMessage(
`Signup successful for user: ${creds.username}; auth token saved`,
);
} else {
setMessage(`Signup Error ${response.status}: ${response.data}`);
}
})
.catch((error) => {
setMessage(`Signup Error: ${error}`);
});
return promise;
}
Notice that success for /signup is 201 because it creates a resource.
Give it a try, and test what happens on each action, depending on whether you’re logged in or not. You may want to tweak some of the views, as we did for TableBody. Or you may want to check for login status and redirect to the login page. (We only protected API calls, which is the minimum for security reasons, but you may also want to protect entire page views.) There are many options possible, now that you know the basics of password encryption and JWT auth tokens.
Turn in |
Turn in your GH link to the Canvas assignment that has your TE6 code. Total: 50 points
Useful references for further reading (optional):
[4] Web Cookies
[5] JWT
[6] bcrypt