How to Fix the OWASP Top 10 Vulnerability in Angular 18.1.1v
Discuss the configurations and see examples of how to mitigate security vulnerabilities in an Angular web application 18.1.1v in detail.
Join the DZone community and get the full member experience.
Join For FreeThe latest release of Angular, which is presently version 18.1.1, offers a wide range of features for developing robust and scalable web applications in Angular. However, safety continues to be of concern. In this article, we will discuss the configurations and see examples of how to mitigate these vulnerabilities in an Angular web application 18.1.1v in detail.
1. Injection
Injection flaws (SQL, NoSQL, and OS command injection) occur when untrusted data is send to an interpreter situated among a machine or query.
Mitigation
- Always sanitize your data with the built in facilities of Angular to avoid injection attacks.
- Instead of
eval()
, use dynamic code execution.
import { DomSanitizer } from '@angular/platform-browser';
constructor(private domSanitizer: DomSanitizer) {}
safeHtml(html: string) {
return this.domSanitizer.bypassSecurityTrustHtml(html);
}
2. Broken Authentication
When authentication mechanisms are implemented poorly, an attacker can compromise passwords, keys or session tokens.
Mitigation
- Strong passwords should be enforced, and MFA must also been put into place.
- Use Angular HTTP Interceptors for secure authentication tokens
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable()
export class AppAuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authToken = this.getUserAuthToken();
const authRequest = req.clone({
headers: req.headers.set('Authorization', `Bearer ${authToken}`)
});
return next.handle(authRequest);
}
getUserAuthToken() {
return localStorage.getItem('authToken');
}
}
3. Sensitive Data Exposure
Security of sensitive data information such as personal details, healthcare information, credit card numbers must be secure.
Mitigation
- Always use HTTPS in transit to encrypt data.
- Do not maintain sensitive data in local storage. Secure storage of any kind of confidential information is a good habit to be made it.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class AppSecureService {
constructor(private http: HttpClient) {}
getUserSecureData() {
return this.http.get('https://secureapi.example.com/data');
}
}
4. XML External Entities (XXE)
A weakly configured XML parser processes the provided input (which is an XML that uses references to external entities) in form of a XXE attack.
Mitigation
- Use JSON instead of XML.
- Use XML parsers which disable external entity resolution.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class SecureXmlDataService {
constructor(private http: HttpClient) {}
getXmlData() {
return this.http.get('https://secureapi.example.com/data', { responseType: 'text' });
}
}
5. Broken Access Control
This is a lack of narrow permissions enforcement for authenticated users.
Mitigation
- Access control to be managed using Angular Guards
- Enable role-based access control (RBAC).
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class AuthGuard implements CanActivate {
constructor(private router: Router) {}
canActivate(): boolean {
const isAuthenticated = this.checkIfAuthenticated();
if (!isAuthenticated) {
this.router.navigate(['login']);
}
return isAuthenticated;
}
checkIfAuthenticated(): boolean {
return !!localStorage.getItem('authToken');
}
}
6. Security Misconfiguration
Vulnerabilities can allow an unauthenticated attacker to gain privileged access or perform restricted operations.
Mitigation
- Update dependencies frequently.
- Use scripts or configuration management tools.
// angular.json
{
"projects": {
"app": {
"architect": {
"build": {
"options": {
"optimization": true,
"outputHashing": "all",
"sourceMap": false,
"extractCss": true,
"namedChunks": false,
"aot": true,
"extractLicenses": true,
"vendorChunk": false,
"buildOptimizer": true
}
}
}
}
}
}
7. Cross-Site Scripting (XSS)
XSS flaws occur when a web application includes user provided data directly into the output sent to live page, without proper validation or escaping.
Mitigation
- Leverage Angular built in template sanitization.
- Do not use
innerHTML
to bind data.
import { Component } from '@angular/core';
@Component({
selector: 'app-safe-test-component',
template: `<div [innerHTML]="safeTestHtml"></div>`
})
export class SafeComponent {
safeTestHtml = '<p>Safe Content Test!</p>';
}
8. Insecure Deserialization
Insecure deserialization can result in serious consequences such as remote code execution or any other events.
Mitigation
- Avoid utilizing
eval()
or other methods that can execute arbitrary code. - Only use secure serializing and de-serializing libraries.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class SafeSerializationService {
serializeData(data: any): string {
return JSON.stringify(data);
}
deserializeData(json: string): any {
return JSON.parse(json);
}
}
9. Component With Known Vulnerabilities
Components, such as libraries, frameworks and other software modules that run on the same privilege along with application.
Mitigation
- Scan dependencies regularly and update them.
- Tools like
npm audit
will find application vulnerabilities.
# Run npm audit to find and fix vulnerabilities
npm audit fix
10. Lack of Monitoring and Logging
Insufficient logging and monitoring, coupled with missing or ineffective integration with incident response, allows attackers to further attack systems, maintains persistence pivot to more systems tamper, extract or destroy data.
Mitigation
- Introduce logging to the application throughout.
- Detect suspicious activities with the help of monitoring tools.
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggingService {
logMessage(message: string) {
console.log(`[LOG] ${message}`);
}
logError(error: any) {
console.error(`[ERROR] ${error}`);
}
}
Conclusion
Follow security best practices and use the latest features from Angular 18.1.1, you successfully protect yourself against OWASP Top 10 vulnerabilities on your apps. This not only improves security in your application but builds trust among users.
Opinions expressed by DZone contributors are their own.
Comments