본문 바로가기
반응형

HTML에서 iframe을 사용할 경우 XSS(Cross Site Scripting) 공격에 대한 방어의 목적으로 SOP( Same Oringin Policy) 정책을 걸어놨습니다.

iframe을 이용한 XSS공격은 간단히 설명하면 해커가 어떤 게시판에 글을 작성할때 iframe으로 해킹코드가 있는 문서를 불러오도록 해 놓을 경우 해당 게시물을 열어 보는 대부분의 사용자 정보를 탈취할 수 있게 되는 해킹 기법을 말합니다.

하지만 보안이 검증된 youtube 영상을 불러온다던가 하는 경우에는 일시적으로 SOP를 해제 시켜야 하는 경우가 생기는데요.
그 방법에 대해 Angular에서는 pipe를 이용하여 외부 iframe을 불러 올 수 있게 처리 할 수 있습니다.

에러 유형

보통 아래와 같은 에러메시지가 발생 합니다.

Error: unsafe value used in a resource URL context

발생상황

HTML에 iframe을 사용하면 발생을 합니다.

<iframe width="100%" height="300" [src]="youtube.url"></iframe>

해결방법

Angular의 Pipe기능을 이용하여 template에서 iframe를 불러올때 사용하면 됩니다.
Pipe문서를 따로 만들어도 되고 Component에 직접 적용해도 됩니다.

아래와 같이 Pipe를 사용하기 위해 Pipe, PipeTransform를 불러오고 XSS를 막기 위해 DomSanitizerimport 합니다.
동일한 문서의 하단에 아래와 같이 @Pipe를 적용합니다.

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

아래와 같이 NgModuledeclarations에도 등록을 해놔야 작동을 합니다.

import { SafePipe } from './safe-pipe';

@NgModule({
  declarations: [ SafePipe ],
  imports: [ ],
  exports: [ ]
})

마지막으로 template에 Pipe에서 지정한 이름 safe를 붙혀넣습니다.

<iframe width="100%" height="300" [src]="youtube.url | safe"></iframe>

끝입니다. ㅎ

참고

How to set iframe src in Angular 2 without causing unsafe value exception? - stack overflow

나만모르는 이야기

여행, 맛집,IT, 리뷰에 대한 이야기를 공유하는 블로그 .