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
- One way function which cannot be reverted - so you cannot figure out a password from a hash
- Small changes in the input yields big changes in the hashed output
- Deterministic - Same input always yields the same output
- 2 outputs should be highly unlikely to be the same
- 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
- npm i bcrypt
- require bcrypt
- Generate a salt with bcrypt.genSalt
- Hash a password with bcrypt.hash
- Compare users password with the hash with bcrypt.compare
Log in / out steps
- Register
- Login
- Stay logged in with sessions
- Logout
PassportJS
Passport JS is a framework to easily implement authentication with node.js
- Install passport, passport-local and passport-local-mongoose
- Create a user model
- 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())
- Set up the register form and route
- Set up the login form and route
- Keep a user logged in with isLoggedIn middleware
- Adding logout functionality
List of sources
- Colt Steeles web
developer bootcamp 2021