From Public Images to Token-Based Access: A Hospital Prescription Image Security Upgrade
1. Project Background: A Seemingly Simple QR Code Access System
Recently, I worked on a hospital-related project designed to let patients view prescription medication images by scanning QR codes.
The workflow was relatively straightforward. Hospital staff could upload prescription images, add descriptions, and generate a QR code for each patient's prescription page. The QR code would then be included with the medication package and sent to the patient.
After receiving the medication, the patient could simply scan the QR code using a smartphone to view the corresponding prescription images and related information.
The original workflow looked like this:
Hospital staff manage prescription information through an administration panel.
They upload prescription images and enter descriptions using a rich text editor.
The system generates a corresponding webpage and QR code.
The QR code is sent to the patient together with the medication.
The patient scans the QR code to view the prescription information.
Since the hospital staff did not have programming experience, the system was designed to make daily operations as simple as possible. A rich text editor was used for image uploads and content editing, avoiding the need for staff to interact with technical interfaces.
However, this convenient approach eventually revealed a security issue.
2. Identifying the Problem: Public Image URLs and Potential Data Exposure
During a security review, I discovered that uploaded images were not stored privately. Instead, they were saved directly in the server's public directory.
The image URLs had several characteristics:
Images could be accessed directly through a web browser.
Filenames were generated using a date and a random string.
No additional authentication or authorization was required to access the files.
This approach is relatively common on ordinary websites. However, it becomes problematic when dealing with hospital prescription images.
Such images may contain sensitive patient information, medication details, and other private data. Even if filenames contain random strings, this should not be considered a reliable access control mechanism.
For example, if an attacker discovers the filename generation pattern or collects some image URLs through other channels, they may attempt to enumerate or access images belonging to other patients.
The key point is that random filenames only make URLs harder to guess. They do not actually restrict access.
For a system involving sensitive patient information, relying solely on unpredictable filenames is insufficient.
Therefore, the main objective of this upgrade was:
Introduce controlled image access with minimal changes to the existing system, without modifying the original image upload process or QR code generation mechanism.
3. Version One: Replacing Original Image URLs with Random Tokens
Considering that the system was already in use, directly modifying the upload mechanism and migrating all historical images to private storage would require additional development work and could potentially disrupt existing business processes.
Instead, I decided to start with the image rendering stage.
The basic idea was:
Keep the original image upload and storage mechanisms unchanged, but replace the actual image URLs with temporary token-based API URLs before rendering the webpage.
3.1 Replacing Image URLs
For example, the original image URL might look like this:
/uploads/2026/11/abc123.jpg
Before the webpage is rendered, it is replaced with:
/api/imgurl/randomToken
As a result, the browser no longer receives the actual image storage path. Instead, it receives an API endpoint that requires a valid token.
3.2 Generating Random Tokens
To make tokens difficult to guess, the first version used a relatively long random string.
The generation rules included:
A millisecond-level timestamp as part of the token.
Random characters generated from letters and numbers.
A 32-character string beginning with a letter.
A new token generated whenever the page was loaded.
A mapping between the token and the original image URL was stored on the server, allowing the application to locate the corresponding image file when needed.
3.3 Returning Image Binary Data Through PHP
When the browser requested an image through an address such as:
/api/imgurl/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
The PHP API performed the following operations:
Retrieve the original image path using the token.
Verify whether the token is valid.
Read the corresponding image file from the server.
Set the appropriate Content-Type header.
Return the image binary data directly to the browser.
This allowed the browser to display the image normally without exposing its actual storage location.
3.4 Token Expiration and Cleanup
To reduce the possibility of repeated token usage, I also introduced a token cleanup mechanism.
After the PHP API successfully retrieved the image and returned its binary data, the token entered the cleanup process.
However, instead of deleting it immediately, I introduced a five-minute expiration window.
The intention was to avoid deleting a token immediately when a user refreshed the page frequently, which could otherwise cause image loading failures.
After completing the first version, I tested the URL replacement, API requests, and image rendering. Everything appeared to work correctly.
At first glance, the solution seemed ready for deployment.
However, just before delivering it to the client, I discovered a subtle logical problem.
4. A Problem with Version One: Page Refreshes and Unused Tokens
The problem was related to the token generation strategy.
Since a new token was generated every time the page loaded, refreshing the page created another token for the same image.
For example:
| Action | Generated Token |
|---|---|
| First page visit | Token A |
| First refresh | Token B |
| Second refresh | Token C |
| Third refresh | Token D |
All these tokens pointed to the same original image, but they had no relationship with one another.
This introduced an important problem:
When a page is refreshed, the system cannot determine whether the request comes from the original visitor reloading the page or from another visitor opening the page for the first time.
More importantly, the original token lifecycle mechanism was no longer working as intended.
Since every refresh generated a completely new token, previously generated tokens were no longer reused by subsequent page requests.
As a result, the database could gradually accumulate token records that were no longer useful.
This increased unnecessary database records and made token lifecycle management less efficient.
After reviewing the logic, I realized that the underlying problem was not insufficient token randomness.
The real issue was the absence of a mechanism connecting an original image URL to an existing valid token.
If an existing token could still be used for the same image, generating a new token every time the page was refreshed was unnecessary.
This led to the second version of the solution.
5. Version Two: Database Indexing and Token Reuse
Instead of redesigning the entire architecture, the second version introduced an additional database lookup before generating a new token.
The core idea was simple:
Before generating a new random token, query the database using the original image URL to determine whether a valid token already exists.
If a valid token exists, reuse it.
If no valid token exists, generate a new one.
protected function replaceImageSrc(ImageTicketService $service, string $html): string
{
$result = preg_replace_callback(
'/<img\b[^>]*>/i',
static function (array $imgMatch) use ($service) {
// 清除 wangEditor 遗留的 data-href,避免公开页源码泄露真实图片地址
$img = (string) preg_replace('/\sdata-href\s*=\s*(["\'])[^"\']*\1/i', '', $imgMatch[0]);
return (string) preg_replace_callback(
'/\bsrc\s*=\s*(["\'])([^"\']+)\1/i',
static function (array $srcMatch) use ($service) {
$src = html_entity_decode($srcMatch[2], ENT_QUOTES, 'UTF-8');
if ($src === '' || preg_match('/^(data:|blob:|javascript:)/i', $src)) {
return $srcMatch[0];
}
return 'src=' . $srcMatch[1] . $service->issue($src) . $srcMatch[1];
},
$img
);
},
$html
);
return $result ?? $html;
}
5.1 Adding an Index for Original Image URLs
The database was updated to maintain a relationship between original image URLs and their corresponding tokens.
An index was added to the original image URL field to make lookups more efficient.
This allowed the application to quickly determine whether a particular image already had an available token.
5.2 Updating the Token Generation Process
The second version changed the original generation process as follows.
Step 1: Retrieve the original image URL.
Obtain the actual image path before replacing it.
Step 2: Query the database.
Search for an existing token associated with the original image URL.
Step 3: Check whether a valid token exists.
If a valid token is found, reuse the existing token.
If no valid token is found, generate a new random token and save the mapping.
Step 4: Replace the original image URL.
Convert the original image URL into the corresponding API endpoint.
For example:
First page visit:
Original Image URL → Database Lookup → No Valid Token → Generate Token A
Page refresh:
Original Image URL → Database Lookup → Token A Found → Reuse Token A
Another refresh:
Original Image URL → Database Lookup → Token A Found → Reuse Token A
As long as the existing token remains valid, the same image can reuse it without generating additional tokens.
5.3 Improvements Introduced by Version Two
Compared with the first version, the second version addressed several issues:
Prevented unnecessary token generation on every page refresh.
Reduced the accumulation of redundant token records.
Allowed the same image to reuse an existing valid token.
Established a more stable relationship between image resources and access tokens.
Preserved the original image upload and QR code generation workflows.
The overall architecture remained almost unchanged. A single database lookup step was enough to resolve an important problem in the original token lifecycle design.
6. Final Implementation: Keeping the Existing Business Workflow Unchanged
After two rounds of improvements, the final workflow looked like this:
Hospital staff continue uploading images and editing prescription descriptions through the existing rich text editor.
Images remain stored according to the original storage rules.
The QR code generation mechanism remains unchanged.
Patients scan the QR code and open the corresponding prescription page.
Before rendering the page, ThinkPHP 8 identifies the image URLs.
The system queries the database for an existing valid token and generates a new one only when necessary.
Original image URLs are replaced with controlled API URLs.
The browser requests images through the API endpoint.
PHP validates the token and returns the corresponding image binary data.
This upgrade did not change the workflow for hospital staff or require historical images to be uploaded again.
For an existing production system, this incremental approach can significantly reduce development costs and deployment risks.
7. An Important Security Consideration: Hiding Image URLs Is Not the Same as Private Storage
Although the functional upgrade was completed, there is an important security distinction worth discussing.
Replacing original image URLs with random tokens does not automatically make the images private.
If the images are still stored in a publicly accessible directory, anyone who obtains the original image URL through another channel may still access the file directly, bypassing the PHP API.
Therefore, this solution primarily addresses the following issues:
Prevents normal webpage rendering from exposing original image URLs.
Reduces the risk of bulk image enumeration based on predictable filename patterns.
Centralizes image access through a controlled API endpoint.
Provides a foundation for additional authorization, expiration, and access logging mechanisms.
However, if the project requires stronger protection for patient information, additional measures should be considered.
For example:
Move images to a directory outside the public web root.
Use private object storage with controlled access.
Generate tokens using cryptographically secure random number generators rather than relying only on timestamps and ordinary random strings.
Validate token status, expiration time, and resource permissions on every request.
Enforce HTTPS and maintain access logs.
Apply rate limiting to suspicious or abnormal requests.
There is another important distinction: token reuse does not equal patient identity verification.
Anyone who obtains the QR code may potentially gain access to the corresponding page. Therefore, if the business requirement is that only the intended patient can view the prescription information, the system should introduce an additional authorization mechanism, such as SMS verification, patient identity verification, or another independent authentication method.
For sensitive prescription information, a QR code should not be treated as proof of identity.
8. Conclusion
This hospital project initially appeared to involve a relatively simple requirement: hiding original image URLs.
The first version introduced random tokens and a PHP image API to prevent the webpage from directly exposing actual image paths.
However, during the final review, I discovered that generating a new token on every page refresh could lead to unnecessary token records and inefficient lifecycle management.
The second version introduced a database index based on the original image URL. Before generating a new token, the application now checks whether a valid token already exists and reuses it when possible.
This resolved the token duplication problem without requiring a major architectural redesign.
The experience reminded me of an important lesson in software development:
A solution that works correctly does not necessarily mean its lifecycle design is complete.
Especially when working with sensitive information such as patient records and personal data, developers must consider more than whether a feature works.
They must also think about how data is stored, how access permissions are enforced, and whether unexpected situations could introduce new security risks.
Sometimes, the most valuable improvement does not come from rebuilding an existing system from scratch. It comes from identifying a hidden problem and finding the smallest effective change to solve it.

Comments
Post a Comment