This example demonstrates how to implement URL authentication using Edge Functions. It uses a timestamp and MD5 hash to create and verify secure URLs, protecting resources from unauthorized access and preventing URL manipulation.
- Define constants for the password, expiration time, and resource path.
- Create a
handleRequestfunction that:- Extracts
wsSecretandwsTimefrom the URL query parameters. - Checks if the URL has expired based on the current time and expiration period.
- Generates an expected
wsSecretusing MD5 hash of the pathname, password, and timestamp. - Compares the provided
wsSecretwith the expected one. - Returns a 403 response if authentication fails, otherwise allows the request to proceed.
- Extracts
- Add a 'fetch' event listener that calls the
handleRequestfunction for each incoming request.
This technique is particularly useful in the following situations:
- Protecting access to sensitive or premium content.
- Implementing time-limited access to resources.
- Preventing hotlinking of resources.
- Securing API endpoints that don't require full OAuth authentication.
- Choose an appropriate expiration time to balance security and user experience.
- Ensure that your server and clients have synchronized clocks for accurate timestamp verification.
- Regularly update your secret key (PASSWORD) to maintain security.
- Consider using HTTPS to protect the signed URLs during transmission.
By implementing URL authentication at the edge, you can efficiently protect your resources from unauthorized access and manipulation, providing an additional layer of security for your application.