Authentication/Authorization

Best Practices + Considerations/Mitigations + Implementing Passport.js

UIC logo

Objectives

  • Authentication and Authorization
  • Authentication Options
  • Considerations + Mitigations
    • Password Configuration
    • Securely Storing Passwords - Hashing and Salting Passwords
    • Multifactor Authentication
    • Brute Force Attacks
  • Understanding Cookies and Sessions
  • Implementing Passport.js
    • Strategies, Implementation & Initialization
    • Sessions and Cookies using Passport.js
    • Session Store - Connect SQLite3 | Better-sqlite3-session-store

Question 1

Which of the following is not a authentication choice primarily used in applications?

  • A. Session Based Authentication
  • B. JWT Authentication
  • C. OAuth and OpenID
  • D. Http-Native Authentication

Question 2

If a Hashing algorithm encypts your password, what does salting your password do ?

  • A. Salt generates a private key that is saved to the database
  • B. Salt adds an element of randomness to the hashing algorithm
  • C. Salt checks the end-users password with what is generated via the hashing algorithm
  • E. None of the options presented

Authentication + Authorization
What is the difference? How does this show up in a web app?

Authentication & Authorization

Courtesy of okta - authorization verses access

Authentication

  • Validating that users are whom they claim to be

Authorization

  • Access and permission to specific resource or application functions

Activity

Partner with someone and think about important factors you need to consider when implementing Authentication. Consider the two buckets below.

Routes
Identify all the possible routes needed for Authentication purposes

Authentication Concerns
Issues or problems and end-user can encounter with Authentication

Authentication Options

  • Http-Native - built into HyperText Transfer Protocol [locked-in to whats provided]
  • Sessions - Utilizes Cookies & Sessions to manage logged-in and logged-out users
  • JWT Tokens - stateless authentication method where a JSON Web token (JWT) is stored in the browser (usually localStorage)
  • OAuth - open-standard authorization protocol that allows for authentication via server to server communication. Allow a website or application to access resources hosted by other web apps. Access Token provided for authentication purposes.
  • Third-Party Cloud-base Authentication - Netlify, Amazon Cognito, AuthO
authentication options

Authentication Considerations

There are a number things we can do to enhance authorization security.

Secure Storage of Passwords

Enforcing Strong Passwords

Implementing CAPTCHA

Secure Password Resets

Banning Disposable Email Accounts

Multifactor Authentication

Secure Storage of Password

Hashing and Salting Password
  • Hashing Passwords - are functions that generate a fixed-length result (the hash, or hash value) from a given input
  • Salting - Use to protect against rainbow table attacks, salting adds an element of randomness to the hashing algorithm

Sample Code to encrypt using bcrypt

						
						// 1)Install bcrypt npm module --> npm install bcryptjs

						// 2) Make bcrypt resource available to file
						const bcrypt = require('bcryptjs');

						const hashedPassword = await bcrypt.hash(req.body.password, 10);
						
						// 3) Input hashedPassword into Database
					
				
Example of hashed password in database

Enforcing Strong Passwords

							
								// Create a schema
								var schema = new passwordValidator();
								
								// Add properties to it
								schema
								.is().min(8)                                    // Minimum length 8
								.is().max(1000)                                 // Maximum length 1000
								.has().uppercase()                              // Must have uppercase letters
								.has().lowercase()                              // Must have lowercase letters
								.has().digits()                                 // Must have digits
								.has().not().spaces()                           // Should not have spaces
								.is().not().oneOf(['Passw0rd', 'Password123']); // Blacklist these values
								
								//Validate password is complying to properties set
								var isValid = schema.validate(req.body.password);

								//Hash Password
								const hashedPassword = await bcrypt.hash(req.body.password, 10);
	
						
					

Longer is better
- Set minimum character length;

Case-Sensitive + Special Characters
- Password Suggestion or recommendation

Negate Common Passwords
- Do not allow certain passwords
- Prevent previous used passwords

Implementing CAPTCHA

Picture of Google CAPTCHA

Good Article - https://www.wired.com/2014/12/google-one-click-recaptcha/

Why CAPTCHA

Drawbacks to CAPTCHA

Password Recovery/Reset

login screen

Common Attack Vectors

Step 1 - User enumeration attack
- malicious actor is looking for differences in the server's response based on the validity of submitted credentials.
OWASP good read

Step 2 - Brute Force attack
- consists of an attacker submitting many passwords or passphrases with the hope of eventually guessing correctly

Banning Disposable Email Accounts

  • Very hard to maintain, but might be work having someone check and update a list of disposable email Accounts
  • Adopting a subscription API services that identifiy disposable email addresses could be a viable option
  • 						
    							// Maintained List of disposable email addresses
    							0815.ru
    							0wnd.net
    							0wnd.org
    							10minutemail.co.za
    							10minutemail.com
    							123-m.com
    							1fsdfdsfsdf.tk
    							1pad.de
    							20minutemail.com
    							21cn.com
    							2fdgdfgdfgdf.tk
    							2prong.com
    							30minutemail.com
    							33mail.com
    							3trtretgfrfe.tk
    							4gfdsgfdgfd.tk
    							4warding.com
    							5ghgfhfghfgh.tk
    							6hjgjhgkilkj.tk
    							6paq.com
    							7tags.com
    							9ox.net
    							a-bc.net
    							agedmail.com
    							ama-trade.de
    							amilegit.com
    							amiri.net
    							amiriindustries.com
    							anonmails.de
    							anonymbox.com
    							antichef.com
    							antichef.net
    							antireg.ru
    							antispam.de
    							antispammail.de
    							armyspy.com
    							artman-conception.com
    							azmeil.tk
    							baxomale.ht.cx
    							beefmilk.com
    							bigstring.com
    							binkmail.com
    							bio-muesli.net
    							bobmail.info
    							bodhi.lawlita.com
    							bofthew.com
    							bootybay.de
    							boun.cr
    							bouncr.com
    							breakthru.com
    							brefmail.com
    							bsnow.net
    							bspamfree.org
    							bugmenot.com
    							bund.us
    							burstmail.info
    							buymoreplays.com
    							byom.de
    							c2.hu
    							card.zp.ua
    							casualdx.com
    							cek.pm
    							centermail.com
    							centermail.net
    							chammy.info
    							childsavetrust.org
    							chogmail.com
    							choicemail1.com
    							clixser.com
    							cmail.net
    							cmail.org
    							coldemail.info
    							cool.fr.nf
    							courriel.fr.nf
    							courrieltemporaire.com
    							crapmail.org
    							cust.in
    							cuvox.de
    							d3p.dk
    							dacoolest.com
    							dandikmail.com
    							dayrep.com
    							dcemail.com
    							deadaddress.com
    							deadspam.com
    							delikkt.de
    							despam.it
    							despammed.com
    							devnullmail.com
    							dfgh.net
    							digitalsanctuary.com
    							dingbone.com
    							disposableaddress.com
    							disposableemailaddresses.com
    							disposableinbox.com
    							dispose.it
    							dispostable.com
    							dodgeit.com
    							dodgit.com
    							donemail.ru
    							dontreg.com
    							dontsendmespam.de
    							drdrb.net
    							dump-email.info
    							dumpandjunk.com
    							dumpyemail.com
    							e-mail.com
    							e-mail.org
    							e4ward.com
    							easytrashmail.com
    							einmalmail.de
    							einrot.com
    							eintagsmail.de
    							emailgo.de
    							emailias.com
    							emaillime.com
    							emailsensei.com
    							emailtemporanea.com
    							emailtemporanea.net
    							emailtemporar.ro
    							emailtemporario.com.br
    							emailthe.net
    							emailtmp.com
    							emailwarden.com
    							emailx.at.hm
    							emailxfer.com
    							emeil.in
    							emeil.ir
    							emz.net
    							ero-tube.org
    							evopo.com
    							explodemail.com
    							express.net.ua
    							eyepaste.com
    							fakeinbox.com
    							fakeinformation.com
    							fansworldwide.de
    							fantasymail.de
    							fightallspam.com
    							filzmail.com
    							fivemail.de
    							fleckens.hu
    							frapmail.com
    							friendlymail.co.uk
    							fuckingduh.com
    							fudgerub.com
    							fyii.de
    							garliclife.com
    							gehensiemirnichtaufdensack.de
    							get2mail.fr
    							getairmail.com
    							getmails.eu
    							getonemail.com
    							giantmail.de
    							girlsundertheinfluence.com
    							gishpuppy.com
    							gmial.com
    							goemailgo.com
    							gotmail.net
    							gotmail.org
    							gotti.otherinbox.com
    							great-host.in
    							greensloth.com
    							grr.la
    							gsrv.co.uk
    							guerillamail.biz
    							guerillamail.com
    							guerrillamail.biz
    							guerrillamail.com
    							guerrillamail.de
    							guerrillamail.info
    							guerrillamail.net
    							guerrillamail.org
    							guerrillamailblock.com
    							gustr.com
    							harakirimail.com
    							hat-geld.de
    							hatespam.org
    							herp.in
    							hidemail.de
    							hidzz.com
    							hmamail.com
    							hopemail.biz
    							ieh-mail.de
    							ikbenspamvrij.nl
    							imails.info
    							inbax.tk
    							inbox.si
    							inboxalias.com
    							inboxclean.com
    							inboxclean.org
    							infocom.zp.ua
    							instant-mail.de
    							ip6.li
    							irish2me.com
    							iwi.net
    							jetable.com
    							jetable.fr.nf
    							jetable.net
    							jetable.org
    							jnxjn.com
    							jourrapide.com
    							jsrsolutions.com
    							kasmail.com
    							kaspop.com
    							killmail.com
    							killmail.net
    							klassmaster.com
    							klzlk.com
    							koszmail.pl
    							kurzepost.de
    							lawlita.com
    							letthemeatspam.com
    							lhsdv.com
    							lifebyfood.com
    							link2mail.net
    							litedrop.com
    							lol.ovpn.to
    							lolfreak.net
    							lookugly.com
    							lortemail.dk
    							lr78.com
    							lroid.com
    							lukop.dk
    							m21.cc
    							mail-filter.com
    							mail-temporaire.fr
    							mail.by
    							mail.mezimages.net
    							mail.zp.ua
    							mail1a.de
    							mail21.cc
    							mail2rss.org
    							mail333.com
    							mailbidon.com
    							mailbiz.biz
    							mailblocks.com
    							mailbucket.org
    							mailcat.biz
    							mailcatch.com
    							mailde.de
    							mailde.info
    							maildrop.cc
    							maileimer.de
    							mailexpire.com
    							mailfa.tk
    							mailforspam.com
    							mailfreeonline.com
    							mailguard.me
    							mailin8r.com
    							mailinater.com
    							mailinator.com
    							mailinator.net
    							mailinator.org
    							mailinator2.com
    							mailincubator.com
    							mailismagic.com
    							mailme.lv
    							mailme24.com
    							mailmetrash.com
    							mailmoat.com
    							mailms.com
    							mailnesia.com
    							mailnull.com
    							mailorg.org
    							mailpick.biz
    							mailrock.biz
    							mailscrap.com
    							mailshell.com
    							mailsiphon.com
    							mailtemp.info
    							mailtome.de
    							mailtothis.com
    							mailtrash.net
    							mailtv.net
    							mailtv.tv
    							mailzilla.com
    							makemetheking.com
    							manybrain.com
    							mbx.cc
    							mega.zik.dj
    							meinspamschutz.de
    							meltmail.com
    							messagebeamer.de
    							mezimages.net
    							ministry-of-silly-walks.de
    							mintemail.com
    							misterpinball.de
    							moncourrier.fr.nf
    							monemail.fr.nf
    							monmail.fr.nf
    							monumentmail.com
    							mt2009.com
    							mt2014.com
    							mycard.net.ua
    							mycleaninbox.net
    							mymail-in.net
    							mypacks.net
    							mypartyclip.de
    							myphantomemail.com
    							mysamp.de
    							mytempemail.com
    							mytempmail.com
    							mytrashmail.com
    							nabuma.com
    							neomailbox.com
    							nepwk.com
    							nervmich.net
    							nervtmich.net
    							netmails.com
    							netmails.net
    							neverbox.com
    							nice-4u.com
    							nincsmail.hu
    							nnh.com
    							no-spam.ws
    							noblepioneer.com
    							nomail.pw
    							nomail.xl.cx
    							nomail2me.com
    							nomorespamemails.com
    							nospam.ze.tc
    							nospam4.us
    							nospamfor.us
    							nospammail.net
    							notmailinator.com
    							nowhere.org
    							nowmymail.com
    							nurfuerspam.de
    							nus.edu.sg
    							objectmail.com
    							obobbo.com
    							odnorazovoe.ru
    							oneoffemail.com
    							onewaymail.com
    							onlatedotcom.info
    							online.ms
    							opayq.com
    							ordinaryamerican.net
    							otherinbox.com
    							ovpn.to
    							owlpic.com
    							pancakemail.com
    							pcusers.otherinbox.com
    							pjjkp.com
    							plexolan.de
    							poczta.onet.pl
    							politikerclub.de
    							poofy.org
    							pookmail.com
    							privacy.net
    							privatdemail.net
    							proxymail.eu
    							prtnx.com
    							putthisinyourspamdatabase.com
    							putthisinyourspamdatabase.com
    							qq.com
    							quickinbox.com
    							rcpt.at
    							reallymymail.com
    							realtyalerts.ca
    							recode.me
    							recursor.net
    							reliable-mail.com
    							rhyta.com
    							rmqkr.net
    							royal.net
    							rtrtr.com
    							s0ny.net
    							safe-mail.net
    							safersignup.de
    							safetymail.info
    							safetypost.de
    							saynotospams.com
    							schafmail.de
    							schrott-email.de
    							secretemail.de
    							secure-mail.biz
    							senseless-entertainment.com
    							services391.com
    							sharklasers.com
    							shieldemail.com
    							shiftmail.com
    							shitmail.me
    							shitware.nl
    							shmeriously.com
    							shortmail.net
    							sibmail.com
    							sinnlos-mail.de
    							slapsfromlastnight.com
    							slaskpost.se
    							smashmail.de
    							smellfear.com
    							snakemail.com
    							sneakemail.com
    							sneakmail.de
    							snkmail.com
    							sofimail.com
    							solvemail.info
    							sogetthis.com
    							soodonims.com
    							spam4.me
    							spamail.de
    							spamarrest.com
    							spambob.net
    							spambog.ru
    							spambox.us
    							spamcannon.com
    							spamcannon.net
    							spamcon.org
    							spamcorptastic.com
    							spamcowboy.com
    							spamcowboy.net
    							spamcowboy.org
    							spamday.com
    							spamex.com
    							spamfree.eu
    							spamfree24.com
    							spamfree24.de
    							spamfree24.org
    							spamgoes.in
    							spamgourmet.com
    							spamgourmet.net
    							spamgourmet.org
    							spamherelots.com
    							spamherelots.com
    							spamhereplease.com
    							spamhereplease.com
    							spamhole.com
    							spamify.com
    							spaml.de
    							spammotel.com
    							spamobox.com
    							spamslicer.com
    							spamspot.com
    							spamthis.co.uk
    							spamtroll.net
    							speed.1s.fr
    							spoofmail.de
    							stuffmail.de
    							super-auswahl.de
    							supergreatmail.com
    							supermailer.jp
    							superrito.com
    							superstachel.de
    							suremail.info
    							talkinator.com
    							teewars.org
    							teleworm.com
    							teleworm.us
    							temp-mail.org
    							temp-mail.ru
    							tempe-mail.com
    							tempemail.co.za
    							tempemail.com
    							tempemail.net
    							tempemail.net
    							tempinbox.co.uk
    							tempinbox.com
    							tempmail.eu
    							tempmaildemo.com
    							tempmailer.com
    							tempmailer.de
    							tempomail.fr
    							temporaryemail.net
    							temporaryforwarding.com
    							temporaryinbox.com
    							temporarymailaddress.com
    							tempthe.net
    							thankyou2010.com
    							thc.st
    							thelimestones.com
    							thisisnotmyrealemail.com
    							thismail.net
    							throwawayemailaddress.com
    							tilien.com
    							tittbit.in
    							tizi.com
    							tmailinator.com
    							toomail.biz
    							topranklist.de
    							tradermail.info
    							trash-mail.at
    							trash-mail.com
    							trash-mail.de
    							trash2009.com
    							trashdevil.com
    							trashemail.de
    							trashmail.at
    							trashmail.com
    							trashmail.de
    							trashmail.me
    							trashmail.net
    							trashmail.org
    							trashymail.com
    							trialmail.de
    							trillianpro.com
    							twinmail.de
    							tyldd.com
    							uggsrock.com
    							umail.net
    							uroid.com
    							us.af
    							venompen.com
    							veryrealemail.com
    							viditag.com
    							viralplays.com
    							vpn.st
    							vsimcard.com
    							vubby.com
    							wasteland.rfc822.org
    							webemail.me
    							weg-werf-email.de
    							wegwerf-emails.de
    							wegwerfadresse.de
    							wegwerfemail.com
    							wegwerfemail.de
    							wegwerfmail.de
    							wegwerfmail.info
    							wegwerfmail.net
    							wegwerfmail.org
    							wh4f.org
    							whyspam.me
    							willhackforfood.biz
    							willselfdestruct.com
    							winemaven.info
    							wronghead.com
    							www.e4ward.com
    							www.mailinator.com
    							wwwnew.eu
    							x.ip6.li
    							xagloo.com
    							xemaps.com
    							xents.com
    							xmaily.com
    							xoxy.net
    							yep.it
    							yogamaven.com
    							yopmail.com
    							yopmail.fr
    							yopmail.net
    							yourdomain.com
    							yuurok.com
    							z1p.biz
    							za.com
    							zehnminuten.de
    							zehnminutenmail.de
    							zippymail.info
    							zoemail.net
    							zomg.info
    
    
    					
    				

MultiFactor Authentication

MultiFactor Authentication also known as two-factor authentication; requires a returning user to identify themselves with at least two of the following three categories of information. something they know, something they have and something they are.

Question 1: What ways have you seen the three categories implemented?
Question 2: What type of attack might this prevent?

Understanding Cookies and Sessions

Question 1

A cookie can be used for all of the below options expect which option?

  • A. Session Management
  • B. Personalization of Settings
  • C. Refresing Browser
  • D. Tracking User Behavior

Question 2

Which of the following can you not set for a cookie?

  • A. Max-Age
  • B. Expiration
  • C. Domain
  • D. Path
  • E. All are permissible options

What is a cookie?

A small piece of data that a server sends to a user's web browser

Primary use cases:
Session management | Personalization | Tracking

What additional info. can a cookie carry besides the value?

cookie properties
						
							//Expires after 360000 ms from the time it is set.
							res.cookie(name, 'value', {expire: 360000 + Date.now(), httpOnly: true, path: '/admin', secure: true}); 	
						
					

Types of Cookies

  • Session cookies - Does not have Expires + Max-Age; browser deletes it when it shuts down
  • Persistent cookies - stored on client until deadline set by Expires or Max-Age
  • Secure cookies - when httpOnly is set to true. Only works with HTTP/HTTPS and does not work for scripting languages.
  • Third-party cookies - used by websites to show ads on their web pages or track website traffic. Visual below.
image of third party cookie request

What is a Session?

Server-side storage of information that persist throughout the user's interaction with the web site or web application.

diagram of web session browser and server interaction

Implementing Passport.js

Getting Started with Passport.js

Passport is authentication middleware for Node.js. Configuration steps below:

  • Step 1 - Determine which strategy. Ex. local strategy, OAuth, OpenID & Install Dependencies
  • Step 2 - Configure Strategy *There are over 480 of these
  • Step 3 - Set Middleware
  • Step 4 - Authorize Protected Routes
authentication options

Step 1 - Install Dependencies

When incorporating a database, we will install more packages

								
								npm install passport.js //install passport.js
								npm install passport passport-local  //install passport.js local strategy
								npm install express body-parser express-session //one command to install body-parser and express session 
								//consider install bycryptjs for hashing passwords
							
						

Step 2 - Configure Strategy

Create a config folder and file that holds strategy configuration

								
									const LocalStrategy = require('passport-local').Strategy;
									var sqlite3 = require('sqlite3').verbose()
									let databaseOperations = require('../database.js');
									

									module.exports = function(passport) {
									console.log("Passport Function triggered");
									//Passport pulls the the name variables from the name attribute in login form.  If different, you need to use whats on lines 10 and 11
									passport.use(new LocalStrategy({
										usernameField: 'email',
										passwordField: 'password'
									}, function(username, password, done) {
										console.log(username);
										databaseOperations.authenticateUser(username, password, done);
									}));

									passport.serializeUser(function(user, done) {
										done(null, user); 
									});
									
									passport.deserializeUser(function(user, done) {
										done(null, user); //you can access with req.user
									});
									
									}
								
							

Step 2 cont. - Context File "database.js"

Helpful Database Operations

								
									var sqlite3 = require('sqlite3').verbose()
									const bcrypt = require('bcryptjs');
									
									//Creating a new database instance - Indication of connected database
									let db = new sqlite3.Database('./mplsrenter.sqlite', (err) => {
										if (err) {
										  // Cannot open database
										  console.error(err.message)
										  throw err
										}else{
											//Successful database connection
											console.log('Connected to the SQLite database.') 
										}
									});
									
									let createProfile = (profile) =>{
										var createProfileSql ='INSERT INTO PROSPECTIVE_PROFILE (prof_id, prof_firstname,prof_lastname, prof_address, prof_decision_date, prof_email, prof_password, prof_phone, prof_rent_range, prof_image_url, prof_class_num) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
										var params =[null, profile.firstName, profile.lastName, null, profile.move_date, profile.userEmail, profile.user_password, null, profile.user_rent_range, './images/user_profile_images/generic_profile_img.png', null];
									
										db.run(createProfileSql, params, function(err){
											if (err){
												return console.log(err.message);
											}
											console.log("Profile Created");
											console.log(`Rows inserted ${this.changes}`);	  
										});
									}
									
									let authenticateUser = (username, password, done) =>{
									
										var findUser = 'SELECT * FROM PROSPECTIVE_PROFILE WHERE prof_email = ?';
									
										db.get(findUser, username, function (err, user) {
											console.log(user);
											if (!user) {
											  return done(null, false);
											}
											bcrypt.compare(password, user.prof_password, function (err, result) {
											  if (err) {
												return console.log(err.message);
											  }
											  if (result) {
												return done(null, user);
											  }
											});
									  
										  });
									}
									
									
									//Create Prospective Profile Table
									db.run(`CREATE TABLE PROSPECTIVE_PROFILE (
										prof_id INTEGER PRIMARY KEY,
										prof_firstname varchar(255),
										prof_lastname varchar(255),
										prof_address varchar(255),
										prof_decision_date date,
										prof_email varchar(100),
										prof_password text,
										prof_phone varchar(45),
										prof_rent_range varchar(45),
										prof_image_url text,
										prof_class_num int(11)
									  )`,
									(err) => {
										if (err) {
											// Table already created
										}else{
										   //Indicate if table is already created
										   console.log('Prospective Profile Created');
										}
									});
									
								
							

Step 3 - Configure Middleware

								
									//Require dependencies you installed
									var createError = require('http-errors');
									var express = require('express');
									var session = require('express-session');
									var path = require('path');
									var cookieParser = require('cookie-parser');
									var logger = require('morgan');
									var hbs = require('hbs');
									const passport = require('passport');

									//passport config
									require('./config/passport')(passport);
									
									var session_config = {
											secret: 'secret', //a random unique string key used to authenticate a session
											resave: true, //nables the session to be stored back to the session store, even if the session was never modified during the request
											saveUninitialized: true //his allows any uninitialized session to be sent to the store. When a session is created but not modified, it is referred to as uninitialized.
											cookie: { secure: true } //true is a recommended option. However, it requires an https-enabled website
											//store  parameter when saving session to database
									};
									
									session_config.cookie.secure = false;
									//IMPORTANT REVIEW IN CLASS - https://expressjs.com/en/resources/middleware/session.html

									//Express Sessions
									app.use(session(session_config))
									//Reference for above - https://www.section.io/engineering-education/session-management-in-nodejs-using-expressjs-and-express-session/


									//Passport middleware
									app.use(passport.initialize());
									app.use(passport.session());
								
							

Step 4 - Authorize Routes

Once Authenticated - where can user access

								
									var express = require('express');
									var router = express.Router();
									const passport = require('passport');


									router.post('/', (req, res, next) => {
										passport.authenticate('local', {
											successRedirect: '/dashboard',
											failureRedirect: '/sign_in'
										})(req, res, next);
									});

									module.exports = router;