Security Principles For Angular's Regular Web Applications -
1. You
should avoid direct use of the DOM APIs.
2. You
should enable Content Security Policy (CSP) and configure your web server to
return appropriate CSP HTTP headers.
3. You
should Use the offline template compiler.
4. You
should Use Server Side XSS protection.
5. You
should Use DOM Sanitizer.
6. You
should Preventing CSRF or XSRF attacks.
Example
–
export
const
BROWSER_SANITIZATION_PROVIDERS: Array<any>
= [
{provide: Sanitizer,
useExisting: DomSanitizer},
{provide: DomSanitizer,
useClass: DomSanitizerImpl},
];
@NgModule({
providers: [
BROWSER_SANITIZATION_PROVIDERS
...
],
exports: [CommonModule,
ApplicationModule]
})
export
class BrowserModule
{}
DOM sanitization - Use to clean untrusted parts
of values -
export
enum SecurityContext
{ NONE, HTML, STYLE, SCRIPT, URL, RESOURCE_URL }
export
abstract class
DomSanitizer implements
Sanitizer {
abstract sanitize(context:
SecurityContext, value:
SafeValue|string|null):
string|null;
abstract bypassSecurityTrustHtml(value: string): SafeHtml;
abstract bypassSecurityTrustStyle(value: string): SafeStyle;
abstract bypassSecurityTrustScript(value: string): SafeScript;
abstract bypassSecurityTrustUrl(value: string): SafeUrl;
abstract bypassSecurityTrustResourceUrl(value: string): SafeResourceUrl;
}
The DOM Sanitize Methods –
sanitize(ctx:
SecurityContext, value: SafeValue|string|null):
string|null
{
if (value
== null) return
null;
switch (ctx)
{
case SecurityContext.NONE:
return value
as string;
case SecurityContext.HTML:
if (value
instanceof SafeHtmlImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value,
'HTML');
return sanitizeHtml(this._doc,
String(value));
case SecurityContext.STYLE:
if (value
instanceof SafeStyleImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value,
'Style');
return sanitizeStyle(value
as string);
case SecurityContext.SCRIPT:
if (value
instanceof SafeScriptImpl)
return value.changingThisBreaksApplicationSecurity;
this.checkNotSafeValue(value,
'Script');
throw new
Error('unsafe
value used in a script context');
case SecurityContext.URL:
if (value
instanceof SafeResourceUrlImpl
|| value instanceof
SafeUrlImpl) {
// Allow resource
URLs in URL contexts, they are strictly more trusted.
return
value.changingThisBreaksApplicationSecurity;
}
this.checkNotSafeValue(value,
'URL');
return sanitizeUrl(String(value));
case SecurityContext.RESOURCE_URL:
if (value
instanceof SafeResourceUrlImpl)
{
return
value.changingThisBreaksApplicationSecurity;
}
this.checkNotSafeValue(value,
'ResourceURL');
throw new
Error(
'unsafe value used
in a resource URL context (see http://g.co/ng/security#xss)');
default:
throw new
Error(`Unexpected
SecurityContext ${ctx}
(see http://g.co/ng/security#xss)`);
}
}
I hope you are enjoying with this post! Please share with you friends. Thank you so much!