Authentication from scratch

Authentication vs Authorization

Authentication is the process of verifying who a user is.

We typically authenticate a user with email/password or security questions, faceID etc!

Authorization is verifying what a specific user has access to.

Handling passwords

How to not store passwords

Rule #1 - Never store passwords in text

The solution is hashing the password. We run the password through a hashing function and then store the result in the database.

Cryptographic hashing functions

  1. One way function which cannot be reverted - so you cannot figure out a password from a hash
  2. Small changes in the input yields big changes in the hashed output
  3. Deterministic - Same input always yields the same output
  4. 2 outputs should be highly unlikely to be the same
  5. Password hash functions are deliberateley slow to slow down hackers when brute forcing.

Password salts

Salting is an extra step we take when hashing a password.

Even with a password hasher, there are only a few available, so hackers can still brute force a db and find the common passwords used and figure out the hashes, so we use passowrd salts for extra security.

A salt is a random value added to the password before we hash it. It helps to ensure unique hashes and mitigate common attacks.

Bycrypt hashing framework

  1. npm i bcrypt
  2. require bcrypt
  3. Generate a salt with bcrypt.genSalt
  4. Hash a password with bcrypt.hash
  5. Compare users password with the hash with bcrypt.compare

Log in / out steps

  1. Register
  2. Login
  3. Stay logged in with sessions
  4. Logout

PassportJS

Passport JS is a framework to easily implement authentication with node.js

  1. Install passport, passport-local and passport-local-mongoose
  2. Create a user model
  3. Configue passport
    // Under declaring app.use for sessions
    // configuring passport JS
    app.use(passport.initialize())
    app.use(passport.session())
    passport.use(new localStrategy(User.authenticate()))
    // how to get a user in and out of a session using passport js
    passport.serializeUser(User.serializeUser())
    passport.deserializeUser(User.deserializeUser())
  4. Set up the register form and route
  5. Set up the login form and route
  6. Keep a user logged in with isLoggedIn middleware
  7. Adding logout functionality

List of sources

    Colt Steeles web developer bootcamp 2021