<img>: Giá trị không an toàn được sử dụng trong ngữ cảnh URL tài nguyên


109

Kể từ khi nâng cấp lên ứng cử viên phát hành Angular 2 mới nhất, imgcác thẻ của tôi :

<img class='photo-img' [hidden]="!showPhoto1" src='{{theMediaItem.photoURL1}}'>

đang gặp lỗi trình duyệt:

NGOẠI LỆ GỐC: Lỗi: giá trị không an toàn được sử dụng trong ngữ cảnh URL tài nguyên

Giá trị của url là:

http://veeu-images.s3.amazonaws.com/media/userphotos/116_1464645173408_cdv_photo_007.jpg

BIÊN TẬP:

Tôi đã thử đề xuất được thực hiện trong giải pháp khác mà câu hỏi này được cho là trùng lặp nhưng tôi gặp lỗi tương tự.

Tôi đã thêm mã sau vào bộ điều khiển:

import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [[NavController], [App], [MenuController], [DomSanitizationService]];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;

    this.theMediaItem.photoURL1 = this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }

Tôi vẫn nhận được thông báo lỗi tương tự.

EDIT2:

Tôi cũng đã thay đổi html thành:

<img class='photo-img' [hidden]="!showPhoto1" [src]='theMediaItem.photoURL1'>

Tôi vẫn nhận được thông báo lỗi tương tự


Tôi không rõ mình nên thay đổi điều gì. Tôi có thay đổi src = "{{something.else}}" thành [src] = "something.else" không?
Bill Noble

1
Chính xác:[src]='theMediaItem.photoURL1'
Günter Zöchbauer

Có, tôi đã thử và nhận được thông báo lỗi tương tự.
Bill Noble

Bạn đang sử dụng phiên bản Angular2 nào?
Günter Zöchbauer

Tôi nghĩ rằng tôi đang sử dụng 2.0.0-beta.15 (Tôi đang sử dụng ionic và hoàn toàn không chắc chắn về cách kiểm tra) Xin lỗi vì cách tôi đã thêm mã mà tôi không rõ trên giao thức.
Bill Noble

Câu trả lời:


95

Tôi đang sử dụng rc.4 và phương pháp này hoạt động cho ES2015 (ES6):

import {DomSanitizationService} from '@angular/platform-browser';

@Component({
  templateUrl: 'build/pages/veeu/veeu.html'
})
export class VeeUPage {
  static get parameters() {
    return [NavController, App, MenuController, DomSanitizationService];
  }

  constructor(nav, app, menu, sanitizer) {

    this.app = app;
    this.nav = nav;
    this.menu = menu;
    this.sanitizer = sanitizer;    
  }

  photoURL() {
    return this.sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
  }
}

Trong HTML:

<iframe [src]='photoURL()' width="640" height="360" frameborder="0"
    webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>

Sử dụng một hàm sẽ đảm bảo rằng giá trị không thay đổi sau khi bạn khử trùng nó. Cũng lưu ý rằng chức năng làm sạch bạn sử dụng phụ thuộc vào ngữ cảnh.

Đối với hình ảnh, bypassSecurityTrustUrlsẽ hoạt động nhưng đối với các mục đích sử dụng khác, bạn cần tham khảo tài liệu :

https://angular.io/docs/ts/latest/api/platform-browser/index/DomSanitizer-class.html


3
" Rc4 " là gì (và sau này Helzgate đề cập đến RC3 )? Ý tôi là, làm cách nào để ánh xạ nó sang phiên bản github? Trong cả github và npm, tôi chỉ thấy các phiên bản như 2.4.4 hoặc 2.4.5. Tôi hiện đang sử dụng 2.4.4 và có vẻ như DomSanitizer đã thay đổi; vì vậy đây là việc nhập khẩu bạn cần:import {DomSanitizer} from '@angular/platform-browser';
The Red Pea

Ồ, tôi nghĩ rằng các nhánh github của angle sẽ đề cập đến ví dụ, nhưng các thẻ github sẽ đề cập đến các ứng cử viên phát hành, chẳng hạn như . Và tôi có thể thấy trong rc3 , ví dụ như lớp vẫn được đặt tên . 2.4.x2.0.0-rc3DomSanitizationService
The Red Pea

1
this.sanitizer.bypassSecurityTrustResourceUrl(url)cho video
prayagupd

Đọc kỹ tài liệu trước khi sử dụng: bypassSecurityTrustUrl () CẢNH BÁO: việc gọi phương thức này với dữ liệu người dùng không đáng tin cậy khiến ứng dụng của bạn gặp rủi ro bảo mật XSS! Có vẻ với tôi rằng làm như vậy là không an toàn, trừ khi bạn thực sự chắc chắn về nguồn hình ảnh đáng tin cậy. Ngay cả khi nó đến từ một máy chủ, nếu nó được người dùng tải lên thì vẫn có thể khai thác một giải pháp như vậy.
Héo

144

Ống

// Angular
import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer, SafeHtml, SafeStyle, SafeScript, SafeUrl, SafeResourceUrl } from '@angular/platform-browser';

/**
 * Sanitize HTML
 */
@Pipe({
  name: 'safe'
})
export class SafePipe implements PipeTransform {
  /**
   * Pipe Constructor
   *
   * @param _sanitizer: DomSanitezer
   */
  // tslint:disable-next-line
  constructor(protected _sanitizer: DomSanitizer) {
  }

  /**
   * Transform
   *
   * @param value: string
   * @param type: string
   */
  transform(value: string, type: string): SafeHtml | SafeStyle | SafeScript | SafeUrl | SafeResourceUrl {
    switch (type) {
      case 'html':
        return this._sanitizer.bypassSecurityTrustHtml(value);
      case 'style':
        return this._sanitizer.bypassSecurityTrustStyle(value);
      case 'script':
        return this._sanitizer.bypassSecurityTrustScript(value);
      case 'url':
        return this._sanitizer.bypassSecurityTrustUrl(value);
      case 'resourceUrl':
        return this._sanitizer.bypassSecurityTrustResourceUrl(value);
      default:
        return this._sanitizer.bypassSecurityTrustHtml(value);
    }
  }
}

Bản mẫu

{{ data.url | safe:'url' }}

Đó là nó!

Lưu ý: Bạn không cần thiết nhưng đây là cách sử dụng thành phần của ống
  // Public properties
  itsSafe: SafeHtml;

  // Private properties
  private safePipe: SafePipe = new SafePipe(this.domSanitizer);

  /**
   * Component constructor
   *
   * @param safePipe: SafeHtml
   * @param domSanitizer: DomSanitizer
   */
  constructor(private safePipe: SafePipe, private domSanitizer: DomSanitizer) {
  }

  /**
   * On init
   */
  ngOnInit(): void {
    this.itsSafe = this.safePipe.transform('<h1>Hi</h1>', 'html');
  }


24

Sử dụng Ống an toàn để sửa chữa nó.

  • Tạo một đường ống an toàn nếu bạn chưa có.

    ng gc an toàn đường ống

  • thêm Safe pipe trong app.module.ts

    khai báo: [SafePipe]

  • khai báo đường ống an toàn trong ts của bạn

Nhập Dom Sanitizer và Safe Pipe để truy cập url một cách an toàn

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);
  }
}

- Thêm an toàn với url src

<iframe width="900" height="500" [src]="link | safe"/>

2
Tuyệt quá! Có một điều, không phải là 'ng g pipe safe' thay vì 'ng gc pipe safe', điều gì rõ ràng sẽ không hoạt động?
Jacob-Jan Mosselman

15

Bạn có thể hiển thị trình vệ sinh cho chế độ xem hoặc hiển thị một phương thức chuyển tiếp cuộc gọi đến bypassSecurityTrustUrl

<img class='photo-img' [hidden]="!showPhoto1" 
    [src]='sanitizer.bypassSecurityTrustUrl(theMediaItem.photoURL1)'>

2

Angular coi tất cả các giá trị là không đáng tin cậy theo mặc định. Khi một giá trị được chèn vào DOM từ một mẫu, thông qua thuộc tính, thuộc tính, kiểu, ràng buộc lớp hoặc nội suy, Angular sẽ làm sạch và thoát các giá trị không đáng tin cậy.

Vì vậy, nếu bạn đang thao tác trực tiếp DOM và chèn nội dung vào đó, bạn cần phải làm sạch nó nếu không Angular sẽ gặp lỗi.

Tôi đã tạo đường dẫn SanifyingUrlPipe cho cái này

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeUrl"
})
export class SanitizeUrlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustResourceUrl(v);
    }
}

và đây là cách bạn có thể sử dụng

<iframe [src]="url | sanitizeUrl" width="100%" height="500px"></iframe>

Nếu bạn muốn thêm HTML, thì SanifyingHtmlPipe có thể giúp

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Pipe({
    name: "sanitizeHtml"
})
export class SanitizeHtmlPipe implements PipeTransform {

    constructor(private _sanitizer: DomSanitizer) { }

    transform(v: string): SafeHtml {
        return this._sanitizer.bypassSecurityTrustHtml(v);
    }
}

Đọc thêm về bảo mật góc ở đây .


1

Tôi thường thêm safe pipethành phần có thể tái sử dụng riêng biệt như sau

# Add Safe Pipe

import { Pipe, PipeTransform } from '@angular/core';
import { DomSanitizer } from '@angular/platform-browser';

@Pipe({name: 'mySafe'})
export class SafePipe implements PipeTransform {
    constructor(private sanitizer: DomSanitizer) {
    }

    public transform(url) {
        return this.sanitizer.bypassSecurityTrustResourceUrl(url);
    }
}
# then create shared pipe module as following 

import { NgModule } from '@angular/core'; 
import { SafePipe } from './safe.pipe';
@NgModule({
    declarations: [
        SafePipe
    ],
    exports: [
        SafePipe
    ]
})
export class SharedPipesModule {
}
# import shared pipe module in your native module

@NgModule({
    declarations: [],
    imports: [
        SharedPipesModule,
    ],
})
export class SupportModule {
}
<!-------------------
call your url (`trustedUrl` for me) and add `mySafe` as defined in Safe Pipe
---------------->
<div class="container-fluid" *ngIf="trustedUrl">
    <iframe [src]="trustedUrl | mySafe" align="middle" width="100%" height="800" frameborder="0"></iframe>
</div>

0
import {DomSanitizationService} from '@angular/platform-browser';
@Component({
 templateUrl: 'build/pages/veeu/veeu.html'
 })
  export class VeeUPage {
     trustedURL:any;
      static get parameters() {
               return [NavController, App, MenuController, 
              DomSanitizationService];
        }
      constructor(nav, app, menu, sanitizer) {
        this.app = app;
        this.nav = nav;
        this.menu = menu;
        this.sanitizer = sanitizer;  
        this.trustedURL  = sanitizer.bypassSecurityTrustUrl(this.mediaItems[1].url);
        } 
 }



 <iframe [src]='trustedURL' width="640" height="360" frameborder="0"
   webkitallowfullscreen mozallowfullscreen allowfullscreen>
</iframe>


User property binding instead of function.

0

Có thể đặt hình ảnh làm hình nền để tránh unsafe urllỗi:

<div [style.backgroundImage]="'url(' + imageUrl + ')'" class="show-image"></div>

CSS:

.show-image {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background-size: cover;        
}
Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.