Skip to main content

Authentication

Authentication is the process of verifying who a particular user is - verifying a user's identity. Authentication happens when a user logs in.

Modern web applications commonly use several authentication strategies:

  • OAuth/OpenID Connect (OIDC): Enable third-party access without sharing user credentials.
  • Credentials-based login: Email and Password: A standard choice for a web applications where users log in with an email and password.
  • Passwordless/Token-based authentication: Use email links or SMS one-time codes for secure, password-free access.
  • Passkeys/WebAuthn: Use credentials unique to the device's unlock mechanism, like Touch ID or Face ID, to authenticate the user.

Authentication vs Authorization

While authentication is about making sure the user is who they say they are, authorization is the next step - what the user is allowed to do. Authorization is discussed in the next section.

Securing credentials

As we have seen, data on the web is generally available for view. If we stored user passwords in our database, anyone with access could see the password. Since many people reuse passwords across sites, that breach would compromise other accounts — not just on your web application.

Instead of storing passwords directly, we store hashed versions of the password.

Hashing

A hashing function performs a one-way transformation of the text. We don't store the plain text but only the hash in the database. Hashing is a one-way function which is infeasible to invert. A small change in input yields large change in the output. Inputs which yield the same hash are called collisions. Hashing is deterministic; the same input yields the same output.

Hashing functions map input text of any size to ciphertext of a specific length.

hash function
hash function to map plain text to a fixed-size output

With hashing we can:

  • Securely store passwords in a database
  • Ensure data integrity by indicating when data has been altered
note

Hashing is not the same as encryption. Encryption involves a key and is reversible.

A salt is a random value added to the password before it is hashed. This helps ensure unique hashes and mitigates common attacks.

more info

View this video for a great explanation on hashing.

Bcrypt

bcrypt is a hash generator and verifier. See the example below for how to use the bcrypt hash function. The hash() function is an asynchronous function that takes a user’s plaintext password and produces a hash that you can safely store in your database. The second argument is the number of rounds. The third argument is an optional callback for if you’re not using await.

bcrypt.hash('myPassword', 10, function(err, hash) {
// Store hash
});

To verify the password later on:

bcrypt.compare('somePassword', hash, function(err, res) {
if (res) {
// Passwords match
} else {
// Passwords don't match
}
});