Web development is not only about writing code that works just fine, it is also about writing code that works perfectly and is not prone to vulnerabilities. There are four key points to remember while developing any Angular applications-
1. Application Level Security:- To provide better application level security, we can do the following-
2. Prevent Cross Site Scripting (XSS):- Cross Site Scripting allows attackers to inject malicious script or code into web pages. To prevent XSS attacks, we must prevent the DOM from receiving malicious code. This type of attack is mostly executed via the query string, input fields, and request headers. To prevent XSS attacks, we can do the following in our Angular application-
3. HTTP Level Vulnerabilities:- Angular comes with built-in support to help prevent common HTTP vulnerabilities, which include the following -
Angular 21 continues to improve security with the following built-in protections:
// auth.guard.ts - Functional guard (Angular 15+)
import { inject } from '@angular/core';
import { CanActivateFn, Router } from '@angular/router';
import { AuthService } from './auth.service';
export const authGuard: CanActivateFn = (route, state) => {
const authService = inject(AuthService);
const router = inject(Router);
if (authService.isLoggedIn()) {
return true;
}
// Redirect to login with return URL
return router.createUrlTree(['/login'], {
queryParams: { returnUrl: state.url }
});
};
// app.routes.ts - Apply the guard
export const routes: Routes = [
{ path: 'dashboard', component: DashboardComponent, canActivate: [authGuard] },
{ path: 'admin', component: AdminComponent, canActivate: [authGuard, adminGuard] },
{ path: 'login', component: LoginComponent },
];
// auth.service.ts - Token-based auth
@Injectable({ providedIn: 'root' })
export class AuthService {
isLoggedIn(): boolean {
const token = localStorage.getItem('auth_token');
if (!token) return false;
// Check token expiry
try {
const payload = JSON.parse(atob(token.split('.')[1]));
return payload.exp > Date.now() / 1000;
} catch {
return false;
}
}
}
Explore 500+ free tutorials across 20+ languages and frameworks.