Angular 2 handling gradients as unsafe

I try to set the gradient on the component dynamically and get the following warning:

WARNING: sanitizing unsafe style value linear-gradient(#000,#00f) (see http://g.co/ng/security#xss).

Here's the minimum playback:

 import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1 [style.background]="(\'linear-gradient(#000,#00f)\')">My First Angular 2 App</h1>' }) export class AppComponent {} 

My search engine tells me to use bypassSecurityTrustStyle , but I'm not happy with it until I find out

  • Why is a linear gradient considered unsafe?
  • Is this the intended behavior or just a bug with the current version of Angular 2.
  • Is there a better way to do this without considering it unsafe?

This should be dynamic as I build the gradient line programmatically. I cannot use css classes for this.

+7
css angular xss gradient
source share
2 answers

1) Why is a linear gradient considered unsafe?

There are restrictions under which your style is skipped (in particular, brackets)

 linear-gradient(#000,#00f) 

https://github.com/angular/angular/blob/2.0.0-rc.7/modules/%40angular/platform-browser/src/security/style_sanitizer.ts#L30

Today (RC.7) RegExp looks like

 /^([-,."'%_!# a-zA-Z0-9]+|(?:(?:matrix|translate|scale|rotate|skew|perspective)(?:X|Y|3d)?|(?:rgb|hsl)a?)\([-0-9.%, a-zA-Z]+\))$/g 

enter image description here

2) Is this the intended behavior or just a bug with the current version from Angular 2.

I think this is more expected behavior than error

Github related issue

3) Is there a better way to do this without considering it unsafe?

You can get around this limitation by writing CustomDomSanitizer

 @NgModule({ imports: [ BrowserModule ], declarations: [ AppComponent ], bootstrap: [ AppComponent ], providers: [ { provide: DomSanitizer, useClass: CustomDomSanitizer } ], }) export class AppModule { } 

See also live. Plunger example.

+2
source share

All Articles