Security

Comprehensive security guidance for building secure Aurelia 2 applications.

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:

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

DOMPurify Configuration

Customize DOMPurify based on your needs:

  • ALLOWED_TAGS: Whitelist of allowed HTML tags

  • ALLOWED_ATTR: Whitelist of allowed attributes

  • FORBID_TAGS: Blacklist of forbidden tags

  • FORBID_ATTR: Blacklist of forbidden attributes

See DOMPurify documentation for all options.

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:

  1. Server generates a unique CSRF token per session

  2. Token is included in forms or sent with requests

  3. 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):

SameSite Options

  • Strict: Cookie never sent in cross-site requests (strongest protection)

  • Lax: Cookie sent on top-level navigation (GET), not on cross-site POST

  • None: Cookie sent in all contexts (requires Secure flag)

For most applications, SameSite=Lax provides good CSRF protection without breaking legitimate use cases.


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() or new Function()

  • ✅ Templates are pre-compiled, not evaluated at runtime

  • ✅ All code is in JavaScript files, not inline scripts

Explanation:

  • default-src 'self': Only allow resources from same origin

  • script-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 API

  • frame-ancestors 'none': Prevent clickjacking (same as X-Frame-Options: DENY)

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

  1. Start strict, then relax if needed - Begin with default-src 'self' and add exceptions

  2. Never use 'unsafe-eval' - Aurelia doesn't need it

  3. Avoid 'unsafe-inline' for scripts - Aurelia doesn't need it for scripts

  4. Use HTTPS only - upgrade-insecure-requests directive

  5. Test thoroughly - Use report-only mode first


Secure Token Storage

How you store authentication tokens affects security. Each method has trade-offs.

Storage Options Comparison

Storage Method
XSS Vulnerable
CSRF Vulnerable
Persists on Close
Accessible via JS

localStorage

✅ Yes

❌ No

✅ Yes

✅ Yes

sessionStorage

✅ Yes

❌ No

❌ No

✅ Yes

Cookie (HttpOnly)

❌ No

✅ Yes (without SameSite)

✅ Yes

❌ No

Memory only

❌ No

❌ No

❌ No

⚠️ Limited

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)

  • SameSite attribute 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:

  1. Use sessionStorage instead of localStorage (cleared on tab close)

  2. Use short-lived tokens (15-30 minutes)

  3. Implement refresh token rotation

  4. Clear on logout


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:


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:

  1. Redirect HTTP to HTTPS (server configuration)

  2. Use HSTS header:

  3. Use Secure flag 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



Additional Resources

External Security Resources

Security Testing Tools

  • OWASP ZAP - Security scanner

  • npm audit - Dependency vulnerability scanner

  • Snyk - Dependency and code security scanner

Stay Informed

Security is an ongoing process, not a one-time task. Subscribe to security advisories for your backend framework and dependencies. Regularly review and update your security measures.

Last updated

Was this helpful?