Define Authentication
Authentication = Who
Authentication is verifying a user is who they say they are. This involves the user having a secret or credential of some kind and supplying that to the server and having the server verify that secret
Define Authorization
Authorization = What
Authorization is what Role or Permissions the user has.
What are the types of "Secrets"?
Define Symetric Encryption
A single private key is used to encrypt some data using a lossless algorithm. You can use the private key to decrypt and restore the original data
What is a lossless algorithm?
Lossless compression is a class of data compression algorithms that allows the original data to be perfectly reconstructed from the compressed data. Lossless data compression is used in many applications. ... For example, it is used in the ZIP file format and in the GNU tool gzip.
Define Asymmetric Encription
A system with two keys, a private key and a public key. If Bob wants to send an encrypted message to Alice then Bob uses his private key and Alice's public key to encrypt the message. Now not even Bob can decrypt the message. The only way to decrypt the message is for Alice to use her private key and Bob's public key
What are the following examples of:
Symmetric Encryption - Using a single private key to encrypt some data using a lossless algorithm. You use the private key to decrypt and restore the original data.
What are the following examples of:
Asymmetric Encryption - A system with two keys, a private key and a public key.
What is a "Broken" hash function
The hash function has either been solved, or has been shown to have a flaw
In the following list, identify which are "broken" hash functions
MD5 and SHA-1 should not be used to store user passwords.
Define a hash function
Hash functions are algorithms that generate a lossy hash of a value such that the original value cannot be recovered if someone has the hash
A Salt is a random value added to a password before hashing and stored alongside the password in the database. This makes rainbow tables of pre-computed hashes less useful for figuring out the original password.
In the list below, identify strong hash functions:
Define a "Brute force" attack on your hash
This is just where you try to hash every possible combination of characters until you get a matching hash. This is slow.
Define a "Rainbow Attack" on your hash
You use a list of pre-computed hashes (A Rainbow Table) and compare the hash you want to crack against it. This is still slow, but faster than the brute force attack.
Define a session-based authentication
Session based authentication is where you use a session-id, stored in a cookie, to authenticate the user once they have first authenticated with a password.
What npm package do we need for a session based authentication in Express?
npm install express-session
How do we configure middleware to use the session-id?
app.use(session({
secret: 'a5d63fc5-17a5-459c-b3ba-6d81792158fc', // Secret used to verify the session-id
resave: false, // Recommended by the express-session package
saveUninitialized: false, // Recommended by the express-session package
}));
Where do you store the secret used in the express-session?
Typically it should be stored in an environment variable in your .env file.
Where does express store your session data?
By default, express-session
stores the session data in memory. Which means if you restart your express server you are going to lose your session data (all users will suddenly be logged out of the system).
How are you able to get session information from middleware?
The middleware creates a .session
property on the express req
(Request) object. You can use this to store information you would like to persist for the user, such as the user's id
or other information that is relevant for your application
When do you risk losing your session data?
If you store your express-session in memory (the default method), if your server is restarted the session data will be lost and all of your users will suddenly be logged out of the system.
How do you remedy losing your session data if your server is rebooted?
Configure a different mechanism for the session store.
We can use the connect-pg-simple
module to connect to postgreSQL and store the session in a table in our database
const store = require('connect-pg-simple');
app.use(session({
store: new (store(session))(),
secret: 'a5d63fc5-17a5-459c-b3ba-6d81792158fc',
resave: false,
saveUninitialized: false,}));
It will need an environment variable named DATABASE_URL
to know which postgreSQL database to conneect to.
DATABASE_URL=p[ostgresql://<username>:<password>@<host>:<port>/<database name>
What library would you use to implement a strong hash function to securely store passwords?
bcrypt: npm install bcryptjs
How would you use bcrypt to generate a strong hashed password?
const hashedPassword = await bcrypt.hash(password, 10);
How do you verify a password against a a hashed password using bcrypt?
const passwordMatch = await bcrypt.compare(password, user.hashedPassword.toString());
The passwordMatch value will be a boolean.
What are the different security options for cookies?
What is REST an acronym for?
Representational State Transfer
Describe how RESTful endpoints differ from traditional remote-procedure call (RPC) services.
/tweets/12
and the HTTP methods are verbsGET
POST
PUT
PATCH
DELETE
getTweetById?id=12
Describe a collection resource, and what it may look like.
Collection resources would return a collection of items. It would look like: /tweets
Describe a single resource and what it might look like.
A single resource simply returns a single item. /tweets/17
Given the following database table, what would be some good RESTful endpoints for a backend API.
Tweets |
---|
id |
message |
createdAt |
updatedAt |
These would return JSON
Path | HTTP Verb | Meaning |
---|---|---|
/api/tweets | GET | Get a list of your tweets |
/api/tweets | POST | Create a new tweet |
/api/tweets/17 | GET | Get the details of a tweet with the id of 17 |
/api/tweets/17 | PUT/PATCH | Update a tweet with the id of 17 |
/api/tweets/17 | DELETE | Delete a tweet with the id of 17 |
Give the same table, shown below, what might be good RESTful endpoints for a frontend?
Tweets |
---|
id |
message |
createdAt |
updatedAt |
These would return HTML
Path | HTTP Verb | Meaning | |
/tweets | GET | Show a page of tweets | |
/tweets/new | GET | Show a form to add a new tweet | |
/tweets | POST | Create a new tweet | |
/tweets/17 | GET | Show a page displaying a single tweet | |
/tweets/17/edit | GET | Show a form to edit a tweet with the id of 17 | |
/tweets/17 | PUT/PATCH | Update a tweet with the id of 17 | |
/tweets/17 | DELETE | Delete a tweet with the id of 17 |
Is RESTful a standard (like ECMAScript or URLs)?
No! It is a common way to organize interactions
The reason we call it 'RESTful is because it is more of an idea or a set of guidelines for building APIs which conform nicely with how the web already works
How are RESTful APIs meant to be stateless?
Recall that a stateful operation is the one whose result depends on any state that might change during the execution of the pipeline. Stateless operations retain no state during the execution of the pipeline
There is no necessary session between the client and the server. Data received from the server can be used by the client independently. This allows you to have short discrete operations. This is a natural fit for HTTP operations in which requests are intended to be independent and short-lived.
How would you parse HTTP request bodies, if the request was of type application/json?
Use express.json() middleware to parse the HTTP request bodies with type application/json
app.use(express.json());
If you have an object returned from a database call like User.findByPk(pk)
how would you limit the information returned from that call to the front-end?
Create a new POJO containing only the information needed
app.get('/users/:id', asyncHandler(async (req, res) => {
const user = await User.findByPk(req.params.id);
//A new POJO containing only user.id and user.email
const userData = {
id: user.id,
email: user.email
}
res.json(userData);
}));
How would you return a subset of the collection of objects retrieved from a database call similar to User.findAll()
so that you did not return sensitive or uneeded information to the front-end?
You might use the map function to map out an array of objects. Take, for instance, the users object representing the return from the User.all() call may look as follows:
[
{
id: 1,
email: 'mary@marylark.com',
name: 'Mary',
password: 'mypassword'
},
{
id: 2,
email: 'kyle@kylelark.com',
name: 'Kyle',
password: 'kylespassword'
}
]
app.get('/users', asyncHandler(async (req, res) => {
const users = await User.all();
//A new array of POJOs containing only the user.id and user.email fields
const usersData = users.map(user => {
return { id: user.id, email: user.email }
});
res.json(usersData);
}));
usersData
then looks as follows. Notice we are not returning the sensitive password information:
[
{ id: 1, email: 'mary@marylark.com' },
{ id: 2, email: 'kyle@kylelark.com' }
]
What is CORS?
Cross-Origin Resource Sharing. By default, JavaScript running in the browser can only access API resources from the same origin (i.e. domain, protocol, port). Cross Origin resource sharing is when you attempt to access another domain, protocol, or port that is not the same as your origin.
Will you get a CORS error if you have your front-end running on localhost:3000 and your back-end running on localhost:8000 and you attempt to make an API call from your front-end to your backend?
YES! Even the ports must be the same, if the default settings are used when executing your JavaScript.
How would you prevent CORs errors
npm install cors
app.use(cors({ origin: "http://localhost:3000"}))
You probably wnat to store the CORS origin in an environment variable in your .env
file instead of hard coding it.
Explain the fundamental concepts of OAuth as a way to authenticate users
OAuth 2.0 is a standardized mechanism for authenticating users using a 3rd party OAuth provider.
Describe the workflow of OAuth resource owner password credentals grant (RFC 6749 Section 4.3)
What is a JWT?
A json web token.
No, seriously, what is a JSON Web Token?
JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.
What are the two types of JWTs?
What are the 3 components of a JWT?
typ
(type) and alg
algorithm.The JWT token consist of a single string with these three parts separated by the .
character. Each part of the token is Base64 encoded.
What can a JWT token be used for?
authentication and authorization
Can a JSON Web Token be used to decrypt data?
No
What is a good way of securely transmitting information between parties?
JSON Web Tokens are a good way of securely transmitting information between parites. Because JWTs can be signed -- for example, using public/private key pairs -- you can be sure the senders are who they say they are. Additionally, as the signature is calculated using the header and the payload, you can also verify that the content hasn't been tampered with.
What is this an example of:
{
"alg": "HS256",
"typ": "JWT"
}
A JWT Header. It typically consists of two parts - the type of the token, which is JWT, and the signing algorithm being used, such as HMAC, SHA256, or RSA.
What is the following an example of?
{
"sub": "1234567890",
"name": "John Doe",
"admin": true
}
A JWT Payload
Payloads are the second part of a JWT token. The payload contains the claims. Claims are statements about an entity (typically, the user) and additional data. There are tree types of claims: registered, public, and private claims.
What is the following?
HMACSHA256(
base64UrlEncode(header) + "." +
base64UrlEncode(payload),
secret)
This is the signature of a JWT. To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
The signature is used to verify the message wasn't changed along the way, and, in the case of tokens signed with a private key, it can also verify that the sender of the JWT is who it says it is.
What is a cool JWT tool that will help you decode, verify, and generate JWTs?
jwt.io
What is this?
A JWT that has the header and payloaded encoded, and is signed with a secret. Note that each part is separated by a .