gpt4 book ai didi

Angular2 - 预期的安全值必须使用 [property] = binding

转载 作者:太空狗 更新时间:2023-10-29 17:44:33 24 4
gpt4 key购买 nike

我正在为 SafePipe 编写测试。该方法使用 bypassSecurityTrustResourceUrl() 。我搜索了可用的解决方案并进行了尝试,但不幸的是,它对我没有帮助。错误是

Expected SafeValue must use [property]=binding: Cross (see http://g.co/ng/security#xss) to be 'Cross site Request'.

我在这里做错了什么?

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

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

public transform(url: string): any {
return this.sanitizer.bypassSecurityTrustResourceUrl(url);
}
}

测试是:

import {SafePipe} from './safe.pipe';
import {DomSanitizer} from "@angular/platform-browser";
import {DomSanitizerImpl} from "@angular/platform-browse/src/security/dom_sanitization_service";

fdescribe('SafePipe', () => {
let pipe: SafePipe;
let sanitizer: DomSanitizer = new DomSanitizerImpl();
beforeEach(() => {
pipe = new SafePipe(sanitizer);
});

it('should transform', () => {
expect(pipe.transform("Cross <script>alert('Hello')</script>")).toBe("Cross alert('Hello')");
});
});

最佳答案

sanitizer.bypassSecurityTrustResourceUrl 方法返回 SafeResourceUrlImpl 类,您无法将其转换为字符串(jasmine 试图在内部进行转换)。

abstract class SafeValueImpl implements SafeValue {
constructor(public changingThisBreaksApplicationSecurity: string) {
// empty
}

abstract getTypeName(): string;

toString() {
return `SafeValue must use [property]=binding: ${this.changingThisBreaksApplicationSecurity}` +
` (see http://g.co/ng/security#xss)`;
}
}

您应该使用 DomSanitizer.sanitize 方法(Angular 在应用 [url]="value | safe" 等属性时使用它)

it('should transform', () => {
const safeResourceUrl = pipe.transform("Cross <script>alert('Hello')</script>");
const sanitizedValue = sanitizer.sanitize(SecurityContext.RESOURCE_URL, safeResourceUrl);

expect(sanitizedValue).toBe("Cross <script>alert('Hello')</script>");
});

PS. 这里我假设您在 toBe 语句中有拼写错误,并且您期望字符串将保存 script 标签。

您可以在 Plunker 中找到完整的示例

关于Angular2 - 预期的安全值必须使用 [property] = binding,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45318082/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com