JS-301-NodeServer
  • Introduction
  • js_library
    • Node Server
      • 00 - Intro
        • 01 - Purpose
        • 02 - Back-End Setup
        • 03 - Terms Cheat Sheet
      • 01 - Server Set up
        • 01 - npm packages
        • 02 - Express Intro
        • 03 - Express code
      • 02 - Development Tools
        • 01 - Nodemon Intro
        • 02 - Postman Intro
        • 03 - Postman set up
      • 03 - Routes Intro
        • 01 - Routes intro
        • 02 - Express Router() intro
        • 03 - Challenge 1
        • 04 - Challenge 2
      • 04 - Database Intro
        • 00 - DB Intro and Set up
          • 00 - DB Intro
          • 01 - PostgreSQL Intro
          • 02 - Install
        • 01 - Sequelize Intro
          • 01 - Sequelize intro
          • 02 - Initialize
      • 05 - Model View Controller
        • 01 - MVC
          • 00 - MVC Intro
        • 02 - Models
          • 01 - Intro to Models
          • 02 - Test Model
        • 03 - Controllers
          • 00 - Controllers Intro
          • 01 - Controller Set up
          • 02 - Create Method
          • 03 - req.body()
          • 04 - Crafting the Response
          • 05 - Sending the Response
          • 06 - JSON Response
          • 07 - Error Handling
        • 04 - Conclusion
      • 06 - Tokenization
        • 01 - JWT Intro
          • 01 - JWT intro
        • 02 - User Create
          • 01 - User Create
          • 02 - Refactor
        • 03 - User Token
          • 01 - JWT Package
          • 02 - Adding JWT
          • 03 - ENV
      • 07 - Encryption
        • 01 - bcrypt
        • 02 - bcrypt setup
      • 08 - Session
        • 00 - Session Intro
        • 01 - Sign In Method
        • 02 - Sign In Bcrypt
        • 03 - Sign In JWT
      • 09 - Middleware
        • 01 - Test Client HTML
        • 02 - Test Client JS
        • 03 - Middleware intro
        • 04 - Headers intro
        • 05 - Server Update
        • 06 - Test Post
        • 07 - Test Post Refactor
        • 08 - Post Data
        • 09 - Fetch From One
      • 10 - Authenticated Routes
        • 01 - Intro to Authenticated Routes
        • 02 - Validate Session
        • 03 - Changes to app.js
        • 04 - authtestcontroller.js
        • 05 - Delete an Item
        • 06 - Update an Item
        • 07 - Postman Testing
      • 11 - Authenticated Requests
        • 00 - Additions to index
        • 01 - Anatomy of a Request
        • 02 - Create User
        • 03 - Getting a Token
        • 04 - Get Items From One User
        • 05 - Creating an Item for a User
        • 06 - Get one item
        • 07 - Update an Item
        • 08 - Deleting an Item
        • 09 - Deleting with a Custom Event
      • 12 - Workout Log Server
        • 00 - Intro
      • 13 - More Sequelize Functions
        • Migrations
          • 00 - Intro
          • 01 - init and config
          • 02 - Creating the First Migration
          • 03 - Running Migrations
          • 04 - Reverting Migrations
          • 05 - Seeds
          • 06 - Reverting Seeds
        • Queries
          • 00 - Intro
          • 01 - Queries
Powered by GitBook
On this page
  • TOKEN CREATION
  • Token Parts
  • The Code
  • ANALYSIS
  • TESTING
  • Review
  • MAJOR SECURITY RISK
  1. js_library
  2. Node Server
  3. 06 - Tokenization
  4. 03 - User Token

02 - Adding JWT

Previous01 - JWT PackageNext03 - ENV

Last updated 7 years ago

TOKEN CREATION

In this module, we'll discuss tokens and start creating tokens in our app.

Token Parts

A token consists of three parts:

1. The header (consists of the type of token and an algorithm to encode/decode).

2. The payload (the data being sent via the token; in our case, the username and password).

3. A signature (used by the algorithm to encode/decode the token. Without the signature, the token is useless).

You don't have to dive deep now, maybe on your next iteration of learning, but you should at least go to the official website and look around. You can even create your own simulated token there to see how it works. The big takeaways are that there are heavy algorithms that make the token for you and that there are different parts of the token to learn about.

The Code

Let's go inside of the usercontroller.js file and into the /createuser POST method. Add the following code to the method:

router.post('/createuser', function (req, res) {

  var username = req.body.user.username;
  var pass = req.body.user.password;

  User.create({
    username: username,
    passwordhash: pass

  }).then(

    function createSuccess(user) {
        //1           //2     //3           //4               //5
      var token = jwt.sign({id: user.id}, "i_am_secret", {expiresIn: 60*60*24});

      res.json({
        user: user,
        message: 'created',
        sessionToken: token //6
      });
    },
    function createError(err) {
      res.send(500, err.message);
    }
  );
});

module.exports = router;

ANALYSIS

Let's walk through what we've added:

1. Create a variable to hold the token.

2. .sign() creates the token. It takes at least 2 parameters: the payload and the signature. You can also supply some specific options or a callback.

3. This is the payload, or data we're sending. user.id is the primary key of the user table and is the number assigned to the user when created in the database.

4. This is the signature, which is used to help encode and decode the token. You can make it anything you want, and we will make this private later.

5. We set an option to make the token expire. Here, we're taking (seconds minutes hours); in other words, 1 day.

6. We pass the value of the token back in our response. The server has now assigned a token to a specific user, and the client will have that token to work with (once we have a client).

TESTING

  1. Run in Postman:

    Notice that the token has come back as part of the response:

  2. You should also check Postgres to be sure that the user has been added:

Review

  1. When we create a user, the server will also create a token to send to the client. The server sends the token back to the client in the response. Most of the time, the client will store the token in localStorage, where it can be used in future requests. The token will be valid until it is removed or expired.

MAJOR SECURITY RISK

At the moment, our signature, "i_am_secret", is available for everyone in the world to see via GitHub. This is extremely dangerous because there are robots and processes that scour public repositories looking for passwords and secret phrases. In our next module, we'll discuss a way to help keep sensitive information like this hidden.

JWT
screenshot
screenshot