ANGULAR – Unsafe values used in a resource URL Context

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/
Please follow and like us:

2 Comments

  1. YOGESH

    Nice Article

  2. YOGESH PARMAR

    Help ful

Leave a Reply

Your email address will not be published. Required fields are marked *

© 2023

Theme by Anders NorenUp ↑