Skip to content

Commit cd8c272

Browse files
committed
JSON Web Token
1 parent 5da119f commit cd8c272

File tree

1 file changed

+73
-0
lines changed

1 file changed

+73
-0
lines changed

README.md

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3056,6 +3056,79 @@ async function logFetch(url) {
30563056
</div>
30573057

30583058
#### 72Q. ***How to use JSON Web Token (JWT) for authentication in Node.js?***
3059+
3060+
JSON Web Token (JWT) is an open standard that defines a compact and self-contained way of securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed.
3061+
3062+
There are some advantages of using JWT for authorization:
3063+
3064+
* Purely stateless. No additional server or infra required to store session information.
3065+
* It can be easily shared among services.
3066+
3067+
JSON Web Tokens consist of three parts separated by dots (.), which are:
3068+
3069+
* **Header** - Consists of two parts: the type of token (i.e., JWT) and the signing algorithm (i.e., HS512)
3070+
* **Payload** - Contains the claims that provide information about a user who has been authenticated along with other information such as token expiration time.
3071+
* **Signature** - Final part of a token that wraps in the encoded header and payload, along with the algorithm and a secret
3072+
3073+
**Installation**
3074+
3075+
```bash
3076+
npm install jsonwebtoken bcryptjs --save
3077+
```
3078+
3079+
*Example*: **AuthController.js**
3080+
3081+
```js
3082+
var express = require('express');
3083+
var router = express.Router();
3084+
var bodyParser = require('body-parser');
3085+
var User = require('../user/User');
3086+
3087+
var jwt = require('jsonwebtoken');
3088+
var bcrypt = require('bcryptjs');
3089+
var config = require('../config');
3090+
3091+
3092+
router.use(bodyParser.urlencoded({ extended: false }));
3093+
router.use(bodyParser.json());
3094+
3095+
router.post('/register', function(req, res) {
3096+
3097+
var hashedPassword = bcrypt.hashSync(req.body.password, 8);
3098+
3099+
User.create({
3100+
name : req.body.name,
3101+
email : req.body.email,
3102+
password : hashedPassword
3103+
},
3104+
function (err, user) {
3105+
if (err) return res.status(500).send("There was a problem registering the user.")
3106+
// create a token
3107+
var token = jwt.sign({ id: user._id }, config.secret, {
3108+
expiresIn: 86400 // expires in 24 hours
3109+
});
3110+
res.status(200).send({ auth: true, token: token });
3111+
});
3112+
});
3113+
```
3114+
3115+
**config.js**
3116+
3117+
```js
3118+
// config.js
3119+
module.exports = {
3120+
'secret': 'supersecret'
3121+
};
3122+
```
3123+
3124+
The `jwt.sign()` method takes a payload and the secret key defined in `config.js` as parameters. It creates a unique string of characters representing the payload. In our case, the payload is an object containing only the id of the user.
3125+
3126+
**[[Read More](https://github.com/auth0/node-jsonwebtoken)]**
3127+
3128+
<div align="right">
3129+
<b><a href="#">↥ back to top</a></b>
3130+
</div>
3131+
30593132
#### 73Q. ***How to build a microservices architecture with Node.js?***
30603133
#### 74Q. ***How to use Q promise in Node.js?***
30613134
#### 75Q. ***How to use locale (i18n) in Node.js?***

0 commit comments

Comments
 (0)