Traditional Auth
Authentication management is built around sessions and tokens assigned to registered users who have verified to be behind a client. In this lesson, our focus would be on the processes and standards of registering a user.
When making an action on the backend, deciding on the appropriate HTTP method is one of the very first question to answer. We'll start ours too from this first step.
HTTP Method for Auth
Sensitive requests such as collecting user credentials to be stored ( or registered) are safer on the POST HTTP method instead of GET HTTP. The GET Request is easily exposed over the URL.
However, being a POST Request is not enough. The request must be tunneled through HTTPS ( not HTTP) using SSL/TL. If a domain is not secure with HTTPS, the resources transmitted between this domain and the server are in plain texts that third parties like the government can easily read. Using a POST HTTPS Request ( instead of the one with HTTP without the "S") guarantees that the conversation between the client and the server is encrypted, this adds extra layer of difficulty for anyone trying to peep.
bashapp.post('/signup', (req, res)=> {
res.send("signed up\n")
})
Now that we know the POST HTTP method is the preferred choice for auth actions, we'll proceed to implementing our preferred authentication method with password and username.
Run example in curl
Run curl -X POST localhost:3003/signup in a terminal environment where Curl
is installed. Curl is auto installed in a linux environment.
Authentication with plain password
The user sends their password and username ( combinely called credentials) on the first sign up request. These credentials are stored in a centralized place, usually a database. To keep our examples simple, array will be used throughout this lesson instead.
bashconst DATABASE = Array(
{
username: 'johndoe',
password: 'password123'
}
)
app.post('/signup', (req, res)=> {
const credential = req.body;
DATABASE.push(credential);
res.status(201).json(DATABASE.find(r => r.username == credential.username))
})
Run example in curl
curl -X POST localhost:3003/signup -H "Content-Type: application/json" -d '{"username": "Janedoe", "password": "janepassword"}'
From the example above, you should see our password been saved as plain text.
Saving passwords as plain text posses new problems:
-
Unathorized access: If attackers gain access to the database, they can obtain all passwords and use them to access other user accounts.
-
Data breaches: In the event than attackers find this user's username and password. They can use it to get access to "johndoe's" resources. It results to indentity theft, financial loss or other malicious activities.
To reduce the risks with exposing user passwords, it's essential to save them as hashed texts as against plain texts. When a new user is created or they change their password, the plain text password is run through a hashing function that changes them to a long random-looking string.
Authentication with hashed password
bashimport crpto from 'node:crypto;'
const DATABASE = Array(
{
username: 'johndoe',
password: 'ef92b778bafd56oaa6yh31n777ghyuu...'
}
)
const hashFn = txt => crypto.createHash('sha256').update(txt).digest('hex')
app.post('/signup', (req, res)=> {
const credential = req.body;
credential.password = hashFn(credential.password);
DATABASE.push(credential);
res.status(201).json(DATABASE.find(r => r.username == credential.username))
})
Run example in curl
curl -X POST localhost:3003/signup -H "Content-Type: application/json" -d '{"username": "Jdossh", "password": "jospord"}'
Hash functions are one-way functions. Their returned values can not be inverted ( or reversed) except through a brute-force approach, like a dictionary attack or rainbow table attack. A dictionary attack is a type of cyberattack that tries to guess a password by attempting every plain texts or predefined list of common words until it can find one with a similar hash. In short, nope there are no functions to undo a hash value.
There is another problem: the hashing algorithm used in example for Authentication with plain password is fast to generate. This hashing algorithm ( sha256) is good for integrity checks but not safe enough for password storage. To limit the possibility of brute-force attacks, a slower hash algorithm should be used.
Authentication with a slower hashing algorithm
To make it more difficult for attackers to brute-force passwords, one approach is to use hashing algorithms that are intentionally slower compare to sha256. However, this don't solve all the problems. Regardless of how slow a hashing algorithm is, it will always produce the same hash value for the same input. Are you seeing the problem? This means that if an attacker obtains a list of hashed passwords, and precomputed table of common passwords and their respective hashes ( rainbow tables), they can easily find a match. This is a significant vulnerability and it precisely leads us to the need for a salt.
Salt ( a random string added to each password) when generating the hash ensures getting hashed values and rainbow tables are not enough to brute-force passwords for attackers.
bashimport crypto from 'node:crypto';
import util from 'node:util';
const scryptAsync = util.promisify(crypto.scrypt);
const DATABASE = Array(
{
username: 'johndoe',
password: 'ef92b778bafd56oaa6yh31n777ghyuu...',
salt: 'some-salt-value'
}
)
const hashFn = async (txt, salt) => {
const v = await scryptAsync(txt, salt, 64);
return v.toString('hex');
})
app.post('/signup', (req, res)=> {
const credential = req.body;
const salt = crypto.randomBytes(16).toString('hex');
credential.password = await hashFn(credential.password, salt);
DATABASE.push({...credential, salt});
res.status(201).json(DATABASE.find(r => r.username == credential.username));
})
Because hashes are one way generated, don't be bothered if the salt is exposed in the DB table.
Don't forget our examples are simplified for learning purposes. Below is a robust sample of our completed signup handler:
bashapp.post('/signup', (req, res)=> {
try {
const credential = req.body;
const salt = crypto.randomBytes(16).toString('hex');
credential.password = await hashFn(credential.password, salt);
DATABASE.push({...credential, salt});
res.status(201).json({message: 'User created successfully'});
} catch (err){
res.status(500).json({error: 'An error occurred when signing up'});
}
})
changes:
- wrapped the handler in a try...catch block.
- sent a response with a message property that "User created successfully". This replaced previous use of exposing the user's credentials.
- handled error.
In this lesson, we have been able to discuss indepth how to go about user signup, in he next lesson it'll be Login Authentication.
Login auth can be Stateful or Stateless. While Stateful Auth uses session IDs and a centralized store ( like database table) on the server to track and maintain user crediblity, Stateless Auth resides on the client with no worry for a database. I can wait to meet you on the otherside.
Conclusion
Security is a serious business. Understanding every step of the way to building different layers of security and the reason behind these choices is empowering. If you do not take it seriously remember attackers are on the otherend that will. If it turns in their avour, it undermines the resources, time and money that put into your backend system.