Prevent image leech by dynamically streaming image in Blazor WASM
Blazor
30 Articles
Table of Contents
What we gonna do?
In this article let's learn how to prevent unauthorised use of images from crawlers in Blazor WASM apps.
Note: If you have not done so already, I recommend you read the article on Improve performance by dynamically loading image in Blazor WASM.
Why we gonna do?
Every now and then somebody builds a web site with the brilliant idea that they will uses images from other people's web sites as part of their content. They enjoy the benefits of the traffic (for example, advertising revenue), while the image owner ends up paying for the bandwidth. This is called image leeching. Image leeching or unauthorised use of images is a common problem on the web. It is a problem that has been around since the early days of the web.
How we gonna do?
Use Case for Dynamic Streaming
We can also stream image into blazor wasm app using Javascript Interop. The image will be stored as BLOB and we can create a temporary URL to display the image. The benefit of using temporary URL is that it will be difficult to crawl the image and it will make stealing / leeching difficult. Thus we can prevent unauthorised use of image.
Implementing Dynamic Streaming
First, we need to remove static image src reference from <img> tag and add a ElementReference to the <img> tag. Now we need to get the image Stream using HttpClient and convert it to DotNetStreamReference and pass the ElementReference and DotNetStreamReference to Javascript Interop method. The Javascript Interop method transforms the DotNet Stream to array buffer and creates BLOB and use that to create a temporary URL and set it as src of the <img> tag.
Code Sample - Script to Create Temporary URL
Code Sample - Dynamically stream image in Blazor WASM
If we inspect the image element in the developer tools, we can see that the src of the image is a temporary BLOB URL as shown below.
When you copy that URL and try to access it via browser you get an Error 404 saying that file cannot be accessed as shown below.
As a result, it makes it more difficult to download the image outside the application and prevents unauthorised use of the image.
Advantages of Dynamic Streaming
The advantages of dynamic streaming are as follows,
- Unauthorised Image Access.
- Bandwidth Savings.
- Cost Savings.