While adding video sub-tabs to the loklak search, we faced an issue regarding how could we possibly embed YouTube videos returned by the Loklak search.json API and avoid security risks. Either way was to add iframely APIs or use automatic sanitization. I made reference to Angular Documentation to get this approach for DOM Sanitization. The main issue faced when using an iframe element to display videos in Loklak Search is that the web application became vulnerable to cross-site scripting (XSS) attack .
I would be explaining in this blog about I implemented lazy loading in loklak search and used automatic sanitization to make video resource trusted and safe to be displayed on loklak search. This is the error we got when <iframe> was used in loklak search without sanitizing it.
How to display Youtube videos and avoid security risks?
These steps were used in loklak search and show how to get embeddable youtube links and bypass Security risks by marking resource URL as trusted.
- Importing DomSanitizer into the component from the @angular/platform-browser module and then injecting into the constructor of the component.
This step will inject Domsantizer and provides some bypassSecurityTrust APIs.
- Calling a method during the initialization of the component and passing all the video URLs as a parameter which needs to bypass security
As, the Angular Documentation states ,it is better to call it during initialization so that bypasses security as early as possible and it is declared that no security risks are created by its use at an early stage.
- Make youtube links embeddable and bypass security to mark video URLs as safe and trusted.
This method performs two functions:-
- Firstly, for each link, it tries matches the URLs of the youtube videos to standard formats of the youtube URLs using regular expressions and then extracts the unique video ID and brings it to an embeddable format for the iframe.
- Secondly, it also makes the sanitizer to bypass security and trusts the Resource URL.
- Now links are ready to be used as the value for the source attribute for the iframe element.
Done! This makes our application risk-free for the users, Youtube Videos can now be displayed safely using iframe tag.