ANGULAR – Unsafe values used in a resource URL Context

By Sigar Dave No comments

Ok, when you get this error you are probably trying to use url variable in you template. The most elegant way to fix this is use pipe to bypass security. In this example we will pass URL variable into iframe src.

First of all we will create our pipe. We are injecting the DomSanitizer service, SecurityContext and executing the sanitize and bypassSecurityTrustResourceUrl method to sanitize and bypass security to trust the given value to be a safe style URL.

Note: calling these methods with untrusted USER DATA exposes your application to XSS security risks!

 
import { Pipe, PipeTransform } from '@angular/core';

import { DomSanitizer } from '@angular/platform-browser';
@Pipe({
name: 'safe'
})
export class SafePipe implements PipeTransform {
constructor(private sanitizer: DomSanitizer) { }
transform(url) {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}

Now add you pipe to app.module:

@NgModule({
imports: [ BrowserModule ],
declarations: [ App, SafePipe ],
bootstrap: [ App ]
})


Then just use it!
<iframe [src]="url | safe"></iframe>

You can create pipes or implement logic for other contexts:

SecurityContext.NONE
SecurityContext.HTML
SecurityContext.STYLE
SecurityContext.SCRIPT
SecurityContext.URL
SecurityContext.RESOURCE_URL


courtesy:
https://filipmolcik.com/error-unsafe-value-used-in-a-resource-url-context/

Leave a Reply