Security
Comprehensive security guidance for building secure Aurelia 2 applications.
Critical Security Principle
The client cannot be trusted. All security enforcement must happen on the backend. Your Aurelia application's security measures are for user experience and first-line defense only. Always validate, authenticate, and authorize on the server.
What you'll learn...
How Aurelia protects against XSS attacks in templates
Authentication and authorization patterns using the router
CSRF protection strategies
Content Security Policy (CSP) configuration
Secure data handling and storage
Input validation and sanitization
Table of Contents
XSS Prevention in Templates
Cross-Site Scripting (XSS) is one of the most common web vulnerabilities. Aurelia provides built-in protections, but you must understand when they apply.
Text Interpolation (Safe by Default)
Text interpolation using ${} is automatically escaped and safe from XSS:
How it works: Aurelia sets the textContent property, not innerHTML, so the browser automatically escapes HTML entities.
Attribute Binding (Safe by Default)
Attribute bindings are also safe when using standard binding commands:
URL Injection Risk
While attribute binding escapes HTML, malicious URLs can still be dangerous:
Solution: Validate URLs before binding:
innerHTML Binding (Dangerous - Requires Sanitization)
The innerHTML binding is where XSS vulnerabilities occur. Never bind user input directly to innerHTML without sanitization.
Implementing HTML Sanitization
Aurelia provides a sanitize value converter interface but requires you to provide the sanitization implementation.
Step 1: Install a sanitization library
Step 2: Create a sanitizer service
Step 3: Register the sanitizer
Step 4: Use in templates
Expression Parser Security
Aurelia's binding expression parser has built-in security features:
Restricted Globals: Only safe globals are accessible in binding expressions:
Allowed globals: Array, Boolean, Date, JSON, Math, Number, Object, RegExp, String, Intl, Map, Set, BigInt, Infinity, NaN, isFinite, isNaN, parseFloat, parseInt, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent
No eval or Function constructor: Aurelia never uses eval() or new Function(), making it safe for Content Security Policy (CSP).
Authentication Patterns
Authentication verifies user identity. Aurelia provides the tools to create robust authentication flows using dependency injection and router hooks.
Creating an Authentication Service
Use Aurelia's DI container to create a singleton authentication service:
Adding Authentication Headers
Use an HTTP interceptor to automatically add authentication tokens to requests:
Register the interceptor during app startup:
Login Component Example
Authorization with Route Guards
Authorization determines what authenticated users can access. Use Aurelia's router lifecycle hooks to implement route guards.
Basic Route Guard with canLoad
The canLoad hook runs before navigating to a route. Return false or a redirect to prevent access:
Role-Based Authorization
Extend the auth service to support roles:
Use role checks in route guards:
Reusable Authorization Guard
Create a reusable guard for multiple routes:
Use the reusable guard:
Protecting Multiple Routes
Apply guards to multiple routes via route configuration:
CSRF Protection
Cross-Site Request Forgery (CSRF) attacks trick authenticated users into making unwanted requests. Protect against CSRF using tokens.
CSRF Token Pattern
How it works:
Server generates a unique CSRF token per session
Token is included in forms or sent with requests
Server validates the token on state-changing requests (POST, PUT, DELETE)
Implementation with Meta Tag
Many frameworks provide CSRF tokens via meta tags:
Read and send the token with requests:
Add CSRF token to requests via interceptor:
SameSite Cookies
Modern browsers support the SameSite cookie attribute, which provides automatic CSRF protection:
Server configuration (example with Express.js):
Content Security Policy
Content Security Policy (CSP) is an HTTP header that tells browsers which resources are allowed to load, preventing XSS and data injection attacks.
Aurelia's CSP Compatibility
Aurelia is fully compatible with strict CSP policies because:
✅ No use of
eval()ornew Function()✅ Templates are pre-compiled, not evaluated at runtime
✅ All code is in JavaScript files, not inline scripts
Recommended CSP Configuration
Explanation:
default-src 'self': Only allow resources from same originscript-src 'self': Only load scripts from your domain (no inline scripts)style-src 'self' 'unsafe-inline': Allow inline styles (needed for style attribute bindings)connect-src 'self' https://api.example.com: Allow AJAX to your APIframe-ancestors 'none': Prevent clickjacking (same as X-Frame-Options: DENY)
Inline Styles in Aurelia
Aurelia's style attribute binding generates inline styles:
This requires 'unsafe-inline' in style-src. For stricter CSP:
Use CSS classes instead of inline styles
Use
style-src 'self' 'nonce-...'with nonces (advanced)
Testing Your CSP
Use report-only mode during development to find violations without blocking resources:
Browser console will show CSP violations, and violations will be POSTed to /csp-report endpoint.
CSP Best Practices
Start strict, then relax if needed - Begin with
default-src 'self'and add exceptionsNever use
'unsafe-eval'- Aurelia doesn't need itAvoid
'unsafe-inline'for scripts - Aurelia doesn't need it for scriptsUse HTTPS only -
upgrade-insecure-requestsdirectiveTest thoroughly - Use report-only mode first
Secure Token Storage
How you store authentication tokens affects security. Each method has trade-offs.
Storage Options Comparison
localStorage
✅ Yes
❌ No
✅ Yes
✅ Yes
sessionStorage
✅ Yes
❌ No
❌ No
✅ Yes
Cookie (HttpOnly)
❌ No
✅ Yes (without SameSite)
✅ Yes
❌ No
Memory only
❌ No
❌ No
❌ No
⚠️ Limited
Recommended Approach: HttpOnly Cookies
Most secure option: Store tokens in HttpOnly cookies set by the server.
Server sets cookie:
Benefits:
✅ Not accessible via JavaScript (prevents XSS token theft)
✅ Automatically sent with requests (no client-side code needed)
✅
SameSiteattribute prevents CSRF
Client-side implementation:
Configure fetch client to include cookies:
Alternative: sessionStorage with Short Expiry
If you must store tokens in JavaScript (e.g., token-based API without cookies):
Best practices:
Use
sessionStorageinstead oflocalStorage(cleared on tab close)Use short-lived tokens (15-30 minutes)
Implement refresh token rotation
Clear on logout
Never Store Sensitive Data in localStorage/sessionStorage
If an XSS vulnerability exists, attackers can steal tokens from localStorage/sessionStorage. HttpOnly cookies are much safer.
Input Validation and Sanitization
Always validate and sanitize user input—both client-side and server-side.
Client-Side Validation
Use Aurelia's validation plugin for user experience:
See: Validation documentation for complete guide.
Custom Validation Rules
Create custom validators for security-sensitive inputs:
Server-Side Validation (Critical)
Client-side validation is for UX only. Always re-validate on the server:
Never Trust Client Input
An attacker can bypass client-side validation using browser dev tools or by crafting HTTP requests directly. Always validate and sanitize on the server.
Secure Communication
HTTPS Only
Always use HTTPS in production. HTTP transmits data in plaintext, exposing:
Passwords and tokens
Session cookies
User data
API requests/responses
Enforce HTTPS:
Redirect HTTP to HTTPS (server configuration)
Use HSTS header:
Use
Secureflag on cookies
Check protocol in app:
API Security
Configure fetch client securely:
See: Fetch Client documentation
Security Checklist
Use this checklist to audit your Aurelia application security:
Templates & Data Binding
Authentication
Authorization
Token Storage
CSRF Protection
Content Security Policy
Input Validation
Communication Security
Error Handling
Dependencies
Deployment
Related Documentation
Securing an App (Recipe) - Basic security overview
Authentication with Auth0 - Third-party authentication integration
Router Hooks - Lifecycle hooks for route guards
Validation Plugin - Client-side input validation
Fetch Client - HTTP client configuration
Dependency Injection - DI for services
Additional Resources
External Security Resources
OWASP Top 10 - Most critical web security risks
OWASP Cheat Sheet Series - Security best practices
MDN Web Security - Browser security features
Content Security Policy Reference - CSP guide
Security Testing Tools
Last updated
Was this helpful?