Security is very important when developing Angularjs applications, especially because many Angularjs apps are single-page applications (SPA) that deal with sensitive data and APIs.
Here is a description of the main security considerations and best practices for Angularjs apps,
Avoid Cross-Site Scripting (XSS)
XSS occurs when untrusted data is inserted into the DOM and interpreted as executable JavaScript.
AngularJS helps protect you:
Angular automatically escapes HTML content in bindings (for example, {{userInput}})
Don't use ng-bind-html with untrusted content
Insecure:
<div ng-bind-html="userComment"></div> <!-- Can inject script if not sanitized -->
Secure:
app.controller('SafeCtrl', function($scope, $sce) {
$scope.safeComment = $sce.trustAsHtml(userInput); // only for trusted content
});
Note: Use Angular’s $sce (Strict Contextual Escaping) carefully.
Prevent Cross-Site Request Forgery (CSRF)
Angularjs automatically includes cross-site request forgery (CSRF) protection when working with backend frameworks such as Django, Rails, or Spring.
Angular looks for a cookie called XSRF-TOKEN and sends it in the
X-XSRF-TOKEN header.
Make sure your backend:
- Sets the
XSRF-TOKENcookie - Verifies the token from the header
Content Security Policy (CSP)
A strong content security policy in Angularjs helps prevent XSS by disallowing inline JavaScript.
Tips:
- Avoid
eval()orFunction() - Avoid inline event handlers (e.g.,
onclick) - Use external script files
Example CSP header:
Content-Security-Policy: default-src 'self'; script-src 'self'
Don't trust user input
Always validate and sanitize input on both the client and server side.
- On the server: use a library to sanitize
- On the client: validate the format but never rely solely on it for security
Use ng-bind Instead of
{{ }}
Although {{ }} is safe, using ng-bind can reduce the chance of accidental unescaped HTML injection.
<!-- Avoid this if HTML might get injected -->
<div>{{userInput}}</div>
<!-- Prefer this -->
<div ng-bind="userInput"></div>
Authentication & Authorization
AngularJS doesn't handle authentication out-of-the-box.
- Use JWT tokens or OAuth2 for login
- Secure routes using Route Guard
- Store the token securely (preferably not in
localStorage) - Use HTTP interceptors to attach the token to requests
Avoid Exposing Sensitive Data in Client Code
- Don't put API keys, secrets, or business logic in Angularjs controllers or services
- Use a backend to handle sensitive operations
Keep AngularJS Updated
Always use the latest patched version of Angularjs to avoid known vulnerabilities (v1.8.2 is the last official release).
Also, read: Performance optimization techniques in Angularjs
Leave Comment