You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: docs/backend-web-development/mongoose-middleware.md
+10-7Lines changed: 10 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1,29 +1,32 @@
1
1
# Mongoose middleware
2
2
3
-
Middleware are functions that run at specific stages of a pipeline. Mongoose supports middleware for the following operations:
3
+
Middleware are functions that run at specific stages of a pipeline. For Mongoose, [middleware is specified on the schema level](https://mongoosejs.com/docs/middleware.html).
4
+
5
+
Mongoose has 4 types of middleware.
4
6
5
7
Aggregate
6
8
Document
7
9
Model
8
10
Query
9
11
10
-
For instance, models have `pre` and `post` functions that take two parameters:
12
+
For instance, for document middleware, the `pre` and `post` functions will take two parameters:
13
+
14
+
- Type of event ('init', 'validate', 'save', 'remove', 'updateOne' and 'deleteOne' )
15
+
- A callback that is executed with `this` referencing the document
11
16
12
-
- Type of event (‘init’, ‘validate’, ‘save’, ‘remove’)
13
-
- A callback that is executed with this referencing the model instance
Copy file name to clipboardExpand all lines: docs/backend-web-development/security-jwt.md
+30-36Lines changed: 30 additions & 36 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -56,7 +56,9 @@ Decoding it using base64url, we can see the plaintext of the three parts.
56
56
We have been using this term a few times above. What exactly is this thing? Why do we need it?
57
57
This is one algorithm that converts binary data (or text data) into a format that can be carried in HTTP request URL or headers.
58
58
59
-
According to the specification of HTTP protocol, there are certain characters (such as + and =) that are not allowed to apppar as part of URL or request/response header. On the other hand, people usually include JWT tokens as part of their HTTP requests (as we will show below), so it's important to make sure JWT token value do not contain those forbidden characters.
59
+
According to the specification of HTTP protocol, there are certain characters (such as + and =) that are not allowed to apppar as part of URL or request/response header. Both characters have a special meaning in the URI address: “+” is interpreted as space, while “=” is used to send data via query string as “key=value” pair.
60
+
61
+
On the other hand, people often include JWT tokens as part of their HTTP requests (as we will show below), so it's important to make sure JWT token value do not contain those forbidden characters.
60
62
61
63
People created this base64url encoding scheme for this purpose.
62
64
@@ -66,7 +68,7 @@ Base64url is an **encoding** scheme, not an **encryption** scheme. It is easily
66
68
67
69
## Why have a signature? What is RS256 or HS256?
68
70
69
-
Text from https://community.auth0.com/t/jwt-signing-algorithms-rs256-vs-hs256/7720
71
+
Adapted from https://community.auth0.com/t/jwt-signing-algorithms-rs256-vs-hs256/7720
70
72
71
73
> Both choices refer to what algorithm the identity provider uses to sign the JWT. Signing is a cryptographic operation that generates a “signature” (part of the JWT) that the recipient of the token can validate to ensure that the token has not been tampered with.
72
74
>
@@ -76,15 +78,15 @@ Text from https://community.auth0.com/t/jwt-signing-algorithms-rs256-vs-hs256/77
76
78
77
79
### A good secret for HS256
78
80
79
-
Text from https://auth0.com/blog/a-look-at-the-latest-draft-for-jwt-bcp/
81
+
Text adapted from https://auth0.com/blog/a-look-at-the-latest-draft-for-jwt-bcp/
80
82
81
83
[JSON Web Algorithms](https://tools.ietf.org/html/rfc7518) defines the minimum key length to be equal to the size in bits of the hash function used along with the HMAC algorithm:
82
84
83
85
> "A key of the same size as the hash output (for instance, 256 bits for "HS256") or larger MUST be used with this algorithm." - JSON Web Algorithms (RFC 7518), 3.2 HMAC with SHA-2 Functions
84
86
85
87
If a short key like `secret` (which is ironically very not secret!) is used, we can use [brute force attacks to guess the key](https://auth0.com/blog/brute-forcing-hs256-is-possible-the-importance-of-using-strong-keys-to-sign-jwts/).
86
88
87
-
Alternatively, use HS256.
89
+
Alternatively, use RS256.
88
90
89
91
## Using JWT for http request authentication and authorization
90
92
@@ -125,29 +127,11 @@ For us to read cookies, we need `cookie-parser`.
125
127
npm install cookie-parser
126
128
```
127
129
128
-
For front-end to use this backend, we use `cors`.
129
-
Same origin policy, see https://jonhilton.net/cross-origin-request-blocked/
130
-
131
-
`cors` helps us to efficiently handle cross domain requests.
132
-
133
-
```
134
-
npm install cors
135
-
```
136
-
137
-
In app.js, we use these middleware.
130
+
In app.js, we use this middleware.
138
131
139
132
```js
140
133
// app.js
141
134
constcookieParser=require("cookie-parser");
142
-
constcors=require("cors");
143
-
144
-
constcorsOptions= {
145
-
credentials:true,
146
-
allowedHeaders:"content-type",
147
-
origin:"http://localhost:3001",
148
-
};
149
-
150
-
app.use(cors(corsOptions));
151
135
152
136
app.use(cookieParser());
153
137
```
@@ -179,7 +163,6 @@ const trainerSchema = new mongoose.Schema({
179
163
username: {
180
164
type:String,
181
165
required:true,
182
-
index:true, // helps us to find by username, note that this has a significant production impact
183
166
unique:true,
184
167
minlength:3,
185
168
lowercase:true,
@@ -197,18 +180,19 @@ const trainerSchema = new mongoose.Schema({
If you choose to use a base64 key, read the key into a Buffer using `Buffer.from(key, "base64")` and use it with `jwt.sign` and `jwt.verify`.
360
+
371
361
Save it in `.env` file and do not commit it. Remember to add the `.env` file to `.gitignore`.
372
362
373
363
## Security Concerns of using JWT
@@ -428,3 +418,7 @@ This solution works, however, if you do this, there is not much benefit of using
428
418
429
419
If you use JWT token for session tracking, all the session information is in the JWT token. When a user logout, your client side application needs to remove this token from its memory.
430
420
If the JWT token is saved in a cookie, the logout route handler on the server side needs to delete the cookie that stores JWT token upon user logout. That can be done via the response.clearCookie() provided by Express framework.
421
+
422
+
## Exercises
423
+
424
+
Add `user` model to your songs API and protect the routes for PUT and DELETE. You will need to login to PUT and DELETE any of the songs.
0 commit comments