Blog | G5 Cyber Security

Secure Web Service Login

TL;DR

This guide shows you how to build a more secure login system for your web service using strong passwords, hashing, salting, and session management. It avoids storing passwords directly and protects against common attacks.

1. Password Storage: Hashing & Salting

Never store passwords in plain text! Use a one-way hash function with a unique salt for each password.

# Example using Python and bcrypt (install with 'pip install bcrypt')
import bcrypt

password = b"mysecretpassword"

salt = bcrypt.gensalt()
hashed_password = bcrypt.hashpw(password, salt)

print(f"Salt: {salt}")
print(f"Hashed Password: {hashed_password}")

Store both the salt and hashed_password in your database.

2. Password Verification

When a user logs in, compare the hashed password they enter with the stored hash using the same salt.

# Example (Python & bcrypt)
import bcrypt

stored_salt = b'your_stored_salt'
hashed_password_from_db = b'your_hashed_password_from_db'
user_entered_password = b"mysecretpassword"

if bcrypt.checkpw(user_entered_password, hashed_password_from_db):
    print("Password matches!")
else:
    print("Incorrect password.")

3. Strong Password Policies

Enforce rules to make passwords harder to guess.

You can use libraries to help with this validation.

4. Session Management

Once a user is authenticated, create a session to track their login status.

Example using Flask (Python):

from flask import Flask, session, redirect, url_for
import os

app = Flask(__name__)
app.secret_key = os.urandom(24) # Important: Use a strong secret key!

@app.route('/login', methods=['POST'])
def login():
    # ... (Authentication logic here - check password against hash)
    if authentication_successful:
        session['user_id'] = user_id  # Store the user ID in the session
        return redirect(url_for('home'))
    else:
        return "Invalid credentials."

5. Protection Against Common Attacks

6. Two-Factor Authentication (2FA)

Add an extra layer of security by requiring a second verification method, such as a code sent via SMS or an authenticator app.

Exit mobile version