How does Angular handle security issues such as XSS and XSRF?
Angular provides built-in protection against common security threats such as Cross-Site Scripting (XSS) and Cross-Site Request Forgery (XSRF) attacks.
Cross-Site Scripting (XSS): XSS attacks occur when an attacker injects malicious code into a web page that is executed by the browser of an unsuspecting user. Angular helps prevent XSS attacks by sanitizing untrusted values and by escaping values that are displayed to the user. Angular also provides a mechanism for defining custom sanitizers that can be used to sanitize values before they are displayed to the user.
Cross-Site Request Forgery (XSRF): XSRF attacks occur when an attacker tricks a user into making a request to a website on their behalf, without the user’s knowledge. Angular helps prevent XSRF attacks by automatically adding a token to each HTTP request, which can then be verified on the server to ensure that the request came from the same origin as the application.
Here’s an example of using Angular’s built-in XSRF protection:
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { HttpXsrfTokenExtractor } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class DataService {
constructor(private http: HttpClient, private tokenExtractor: HttpXsrfTokenExtractor) { }
getData() {
const headerName = 'X-XSRF-TOKEN';
let token = this.tokenExtractor.getToken() as string;
if (!token) {
token = '';
}
const headers = new HttpHeaders().set(headerName, token);
return this.http.get('https://api.example.com/data', { headers });
}
}
In this example, the HttpXsrfTokenExtractor
is used to extract the XSRF token from the cookie, and then the token is added to the HTTP header of each request made by the HttpClient
.
By using Angular’s built-in security features, you can help protect your application and its users against common security threats. However, it’s important to always stay informed about new security risks and to be vigilant about implementing best practices to protect your application and its users.