Dev.to Security ๐Ÿ” Cybersecurity ๐Ÿ‘ 0 ๐Ÿ“– 7 min read

Replacing Legacy Auth & Sessions Without Logging Everyone Out

Authentication is the part of a legacy PHP app that everyone is afraid to touch, and for good reason. It usually has unsalted MD5 or SHA1 password hashes, sessions stored as files on one server, a home-made "remember me"

Replacing Legacy Auth & Sessions Without Logging Everyone Out

Authentication is the part of a legacy PHP app that everyone is afraid to touch, and for good reason. It usually has unsalted MD5 or SHA1 password hashes, sessions stored as files on one server, a home-made "remember me" cookie with the user ID in it, and a login form that every other page depends on. When you start running a new Laravel app beside the old one (Part 1's strangler fig), both apps need to agree on who is logged in. If you get it wrong, every user is logged out at once, or worse, someone ends up logged in as someone else.

This post covers how I replace legacy auth and sessions step by step, with both apps live, and without a mass password reset.

I wrote this with help from AI tools and checked the details against the PHP password hashing docs, the Laravel authentication and session docs, and the OWASP Password Storage and Session Management cheat sheets. I am a Principal Software Engineer in Karachi with 9+ years of Laravel and PHP work, much of it on systems older than the frameworks they now run on.

๐Ÿ“š Series Navigation โ€” Modernizing Legacy PHP Without a Rewrite

Related earlier posts: Session Lifecycle Hardening: Rotation, Timeouts & Server-Side Revocation ยท Zero-Downtime Database Migrations in Laravel & Node.js SaaS

How do I replace legacy PHP auth without logging users out?

Direct answer: Keep the old password hashes working and upgrade each one to bcrypt or Argon2id when the user next logs in, wrap the remaining weak hashes immediately, move sessions to a shared store such as Redis that both apps can read, scope cookies so both apps see the same session, and replace custom remember-me cookies with random tokens stored hashed in the database.

Relay race baton resting on a running track lane at dawn, AI-generated

What you usually find

Legacy piece Typical problem Target Migration approach
Passwords md5($pass) or sha1($salt.$pass) password_hash() with bcrypt or Argon2id Wrap now, rehash on login
Sessions Files in /tmp on one server Redis or database, shared by both apps Session bridge, then switch
Remember me Cookie with user_id and an MD5 Random selector + hashed validator in DB Accept old cookie once, reissue new
Login form One PHP file included everywhere New app owns /login Route /login to new app via the proxy
Logout Deletes the cookie only Server-side session destroy everywhere Shared store makes it work

Step 1: wrap weak password hashes right away

Waiting for every user to log in means inactive accounts keep MD5 hashes forever. So I do two things. First, wrap every existing hash in bcrypt in one migration, so the stored value is bcrypt(md5(password)). A database leak no longer exposes raw MD5 values.

// one-off command, run in batches
User::whereNull('hash_scheme')->chunkById(500, function ($users) {
    foreach ($users as $u) {
        $u->forceFill([
            'password'    => password_hash($u->password, PASSWORD_BCRYPT), // wraps the old md5 hex
            'hash_scheme' => 'bcrypt_md5',
        ])->save();
    }
});

Second, on each successful login, verify with the right scheme and replace the hash with a plain modern one:

public function check(User $u, string $plain): bool
{
    $ok = match ($u->hash_scheme) {
        'bcrypt_md5' => password_verify(md5($plain), $u->password),
        'modern'     => password_verify($plain, $u->password),
        default      => false,
    };
    if ($ok && ($u->hash_scheme !== 'modern' || password_needs_rehash($u->password, PASSWORD_DEFAULT))) {
        $u->forceFill(['password' => password_hash($plain, PASSWORD_DEFAULT), 'hash_scheme' => 'modern'])->save();
    }
    return $ok;
}

In Laravel you can put this in a custom user provider so Auth::attempt() keeps working. If the old scheme used a per-user salt, store it and include it in the wrapped value the same way.

Step 2: one session store for both apps

File sessions on one server break the moment you add a second app or a second server. Move both apps to the same Redis instance with the same serialization rules. The old app can use a custom SessionHandlerInterface or PHP's built-in Redis handler:

; legacy php.ini (or ini_set in bootstrap)
session.save_handler = redis
session.save_path = "tcp://10.0.0.5:6379?prefix=legacy_sess:"
session.cookie_httponly = 1
session.cookie_secure = 1
session.cookie_samesite = Lax

Laravel's session format differs from native PHP sessions, so I don't try to share the raw session payload. Instead I use a small bridge: when the new app sees the legacy session cookie but no Laravel session, it reads the legacy session from Redis, takes only the user ID and the login time, logs the user in on the Laravel side, and regenerates the session ID. The reverse direction is the same idea. Keep the bridge read-only and narrow: it trusts only a user ID from a server-side store, never anything from a cookie value itself.

Step 3: get cookie scope right

Both apps must see the cookies they need, and no more:

  • If both apps sit behind the same host through the proxy (example.com/legacy and example.com/app), keep cookie path / and one host. This is the simplest setup.
  • If they are on subdomains, set Domain=.example.com only for the session cookie that must be shared, and only if every subdomain is trusted.
  • Use different cookie names for the legacy and Laravel sessions, so one app never overwrites the other's cookie.
  • Always regenerate the session ID on login and privilege change, in both apps.

Step 4: replace home-made remember-me cookies

A cookie like remember=42:5f4dcc3b5aa765d61d8327deb882cf99 is a long-lived password equivalent. I replace it with the selector/validator pattern: a random selector to look up the row and a random validator stored only as a hash.

CREATE TABLE remember_tokens (
  selector     CHAR(24) PRIMARY KEY,
  validator    CHAR(64) NOT NULL,      -- sha256 of the random validator
  user_id      BIGINT   NOT NULL,
  expires_at   DATETIME NOT NULL
);

During migration, the new code accepts a valid old cookie exactly once, logs the user in, deletes it, and issues a new token. After 30 days, the old format is rejected entirely.

Step 5: decide who really needs a reset

A forced reset for everyone is rarely needed and generates a wave of support tickets. I limit it to:

  • accounts whose hashes were in a known leak,
  • admin and staff accounts (also enforce MFA for them now),
  • accounts that never log in during a set period and still have the wrapped legacy scheme, which get a reset link at their next login attempt.

Rollout order

  1. Wrap all weak hashes (Step 1). No user impact.
  2. Deploy the rehash-on-login code in the legacy app, then the new app.
  3. Move legacy sessions to Redis on one server; watch for logouts.
  4. Add the session bridge; route /login to the new app through the proxy.
  5. Replace remember-me cookies.
  6. Remove legacy login code once traffic to it is zero.

If you have an old app like this and need a hand planning it, this is the kind of custom web application work we do at Loop Origin.

Diagnostic checklist

  • [ ] No password is stored as plain MD5 or SHA1, even for inactive users
  • [ ] Successful logins upgrade hashes to PASSWORD_DEFAULT
  • [ ] Both apps use a shared server-side session store
  • [ ] Session IDs are regenerated on login in both apps
  • [ ] Legacy and new session cookies have different names and correct scope
  • [ ] Remember-me tokens are random and stored hashed
  • [ ] Logout destroys the server-side session, not just the cookie
  • [ ] Admin accounts have MFA and were reset if needed

FAQ

Can I convert MD5 hashes to bcrypt without the passwords?

Not directly, but you can wrap them: bcrypt the MD5 value now, then replace it with a normal bcrypt hash when each user logs in.

Bcrypt or Argon2id?

Both are fine. PASSWORD_DEFAULT is bcrypt in current PHP; Argon2id is a good choice if your PHP build supports it. Use password_needs_rehash() so you can change later.

Do I have to log everyone out when switching session storage?

No. With a session bridge, or by switching one server at a time, most users never notice.

Is sharing a session cookie across subdomains safe?

Only if every subdomain is under your control and trusted. A compromised subdomain can read or set those cookies.

What about API tokens in the old app?

Inventory them, store them hashed, give them expiry dates, and issue new ones through the new app.

When can I delete the legacy auth code?

When logs show no logins, password checks or remember-me cookie uses on the legacy side for a few weeks.

Next in this series, Part 5 moves an app from FTP uploads and loose cron scripts to a real deployment pipeline. Questions about your own migration? Get in touch.

Follow & Connect

๐Ÿ“ฐ Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes โ€” full credit and traffic to the original publisher.