Web Development  

Web Security Basics Every Developer Should Know

Introduction

Web security is no longer a “backend only” concern. In modern web applications, especially single-page applications built using frameworks like Angular, security is a shared responsibility. Frontend developers, backend developers, DevOps engineers, and even product teams influence how secure an application is.

Yet, many security breaches still happen because of basic mistakes:

  • Trusting user input

  • Misusing authentication tokens

  • Poor session handling

  • Incorrect CORS configuration

  • Ignoring browser security features

This article is written for experienced developers who already build production systems but want a clear, practical understanding of web security basics—without academic theory or unnecessary jargon.

The focus will be:

  • Core web security principles

  • Real attack scenarios

  • How these attacks actually happen

  • How to prevent them in real Angular applications

  • What belongs in frontend vs backend responsibility

You don’t need to be a security expert to build secure software. You just need to understand the common attack vectors and apply consistent defensive patterns.

1. Understanding the Web Security Model

Before discussing attacks, it’s important to understand how the web fundamentally works from a security perspective.

1.1 The Browser Is Not Your Trusted Environment

A common beginner mistake is assuming:

“This code runs in the browser, so users cannot change it.”

This is completely false.

Users can:

  • Modify JavaScript in DevTools

  • Intercept API calls

  • Replay requests

  • Change headers

  • Inject custom payloads

Never trust the browser.
Angular runs in an environment fully controlled by the user.

Angular helps with mitigation, not protection.

1.2 Client vs Server Trust Boundary

The most important security rule:

The server is the final authority.

Frontend responsibilities:

  • Input validation for user experience

  • Safe rendering

  • Token storage discipline

  • Preventing accidental vulnerabilities

Backend responsibilities:

  • Authentication

  • Authorization

  • Input validation (again)

  • Business rule enforcement

  • Data access control

Angular should assist security, not enforce it.

2. Authentication vs Authorization (Many Developers Mix This Up)

2.1 Authentication

Authentication answers:

“Who are you?”

Examples:

  • Login with email/password

  • OAuth (Google, GitHub)

  • SSO

  • JWT tokens

Angular does not authenticate users.
It stores proof of authentication (tokens).

2.2 Authorization

Authorization answers:

“What are you allowed to do?”

Examples:

  • Admin can delete users

  • Normal user can only view own profile

  • Manager can approve requests

Authorization must never be enforced only in Angular.

Angular can:

  • Hide buttons

  • Disable routes

  • Improve UX

But backend must always re-check permissions.

3. Cross-Site Scripting (XSS)

3.1 What Is XSS?

XSS occurs when untrusted input is rendered as executable code in the browser.

Example attack

<script>alert('Hacked')</script>

If this script executes in another user’s browser, attacker can:

  • Steal tokens

  • Hijack sessions

  • Perform actions on behalf of user

3.2 Types of XSS

  1. Stored XSS
    Malicious script stored in database and served to users

  2. Reflected XSS
    Script reflected via URL or form input

  3. DOM-based XSS
    JavaScript manipulates DOM unsafely

Angular mostly protects against DOM-based XSS, but not all cases.

3.3 Angular’s Built-in XSS Protection

Angular uses automatic sanitization for:

  • HTML

  • URLs

  • Styles

Example:

<div [innerHTML]="userComment"></div>

Angular sanitizes userComment automatically.

3.4 Dangerous APIs in Angular

Avoid these unless you fully understand them:

DomSanitizer.bypassSecurityTrustHtml()
DomSanitizer.bypassSecurityTrustUrl()

Once you bypass Angular’s sanitizer, you are responsible for security.

Use them only when:

  • Content source is fully trusted

  • You control the HTML

  • You have audited the input

3.5 Best Practices to Prevent XSS

  • Never render raw HTML from users

  • Avoid innerHTML unless necessary

  • Never trust query parameters

  • Encode user-generated content

  • Let Angular sanitize by default

  • Review any bypassSecurityTrust* usage carefully

4. Cross-Site Request Forgery (CSRF)

4.1 What Is CSRF?

CSRF tricks a logged-in user’s browser into sending a request without their intention.

Example

  • User logged into banking site

  • Visits malicious website

  • Malicious site sends request to bank using existing cookies

Browser automatically attaches cookies.

4.2 Why SPAs Are Still Vulnerable

If your app uses cookie-based authentication, CSRF is a real threat.

If you use Authorization headers with tokens, CSRF risk is lower.

4.3 CSRF Protection Techniques

1. SameSite Cookies

Set cookies as:

SameSite=Lax or Strict

This prevents cookies from being sent in cross-site requests.

2. CSRF Tokens

Backend generates a random token:

  • Stored in cookie or response

  • Sent back in request headers

Angular example using HttpInterceptor:

@Injectable()
export class CsrfInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest<any>, next: HttpHandler) {
    const csrfToken = localStorage.getItem('csrfToken');

    if (csrfToken) {
      req = req.clone({
        setHeaders: {
          'X-CSRF-TOKEN': csrfToken
        }
      });
    }

    return next.handle(req);
  }
}

Backend validates the token.

4.4 Best Practice Recommendation

For modern Angular apps:

  • Prefer JWT in Authorization headers

  • Avoid cookie-based auth unless necessary

  • Use SameSite cookies if cookies are used

5. Authentication Tokens: Storage Matters

5.1 Where Should You Store JWT?

Common options:

  • localStorage

  • sessionStorage

  • Cookies (HttpOnly)

Each has trade-offs.

5.2 localStorage

Pros

  • Simple

  • Works well with Angular

Cons

  • Vulnerable to XSS

If attacker runs JS, token can be stolen.

5.3 HttpOnly Cookies

Pros

  • Not accessible via JavaScript

  • Safer against XSS

Cons

  • CSRF risk

  • Harder SPA integration

5.4 Production Recommendation

For most Angular apps:

  • Use short-lived access tokens

  • Store in memory or localStorage

  • Use refresh tokens carefully

  • Protect against XSS aggressively

Security is about reducing impact, not eliminating all risk.

6. Route Guards Are Not Security

Angular Route Guards are UX controls, not security controls.

canActivate(): boolean {
  return this.authService.isLoggedIn();
}

Attackers can:

  • Bypass routes

  • Call APIs directly

Always enforce authorization on backend.

7. CORS Misconfiguration

7.1 What Is CORS?

CORS controls which origins can access your APIs.

It is enforced by the browser, not the server.

7.2 Common Mistake

Access-Control-Allow-Origin: *
Access-Control-Allow-Credentials: true

This is invalid and dangerous.

7.3 Best Practices

  • Whitelist exact origins

  • Avoid wildcard in production

  • Allow only required headers

  • Do not rely on CORS for authentication

CORS is not a security feature; it is a browser restriction.

8. Input Validation: Frontend vs Backend

8.1 Angular Forms Validation

Angular forms provide:

  • Required

  • Min/max length

  • Patterns

This improves UX but does not guarantee security.

8.2 Backend Validation Is Mandatory

Always validate again on server:

  • Length

  • Type

  • Range

  • Format

Never trust frontend validation.

9. Secure HTTP Headers

Important headers every production app should use:

  • Content-Security-Policy

  • X-Frame-Options

  • X-Content-Type-Options

  • Referrer-Policy

  • Strict-Transport-Security

Angular does not set these. Backend or CDN must.

10. Content Security Policy (CSP)

CSP reduces impact of XSS.

Example

Content-Security-Policy:
  default-src 'self';
  script-src 'self';

Angular works well with CSP but requires:

  • Avoid inline scripts

  • Avoid eval

  • Use proper builds

11. Dependency Security

11.1 NPM Is a Supply Chain Risk

Every Angular project depends on hundreds of packages.

Risks:

  • Malicious packages

  • Vulnerable versions

11.2 Best Practices

  • Use npm audit

  • Lock versions

  • Avoid abandoned libraries

  • Review major updates

  • Prefer Angular ecosystem libraries

12. Secure API Communication

12.1 Always Use HTTPS

No exceptions.

HTTP allows:

  • Token interception

  • Man-in-the-middle attacks

12.2 Angular HttpClient Best Practices

  • Centralize API calls

  • Use interceptors for auth

  • Handle errors globally

  • Avoid leaking sensitive info in logs

13. Error Handling and Information Leakage

Never expose:

  • Stack traces

  • SQL errors

  • Internal IDs

  • Server details

Angular should show:

  • Generic user-friendly messages

Backend should log detailed errors internally.

14. Logging and Monitoring

Security is not just prevention.

You need:

  • Audit logs

  • Login attempt tracking

  • Rate limiting

  • Alerting

Angular can assist by:

  • Sending correlation IDs

  • Logging client-side errors responsibly

15. Security Is a Process, Not a Feature

No application is “100% secure”.

Real security comes from:

  • Defense in depth

  • Regular reviews

  • Code audits

  • Dependency updates

  • Developer awareness

Angular gives you good defaults, but security still depends on how you build.

Conclusion

Web security is not about complex cryptography or obscure attacks. Most real-world breaches happen due to:

  • Trusting the client

  • Poor token handling

  • Missing authorization checks

  • Unsafe rendering

  • Misconfigured infrastructure

As Angular developers, your role is critical. You control:

  • How data is rendered

  • How tokens are stored

  • How APIs are consumed

  • How users interact with sensitive actions

If you understand and apply the basics covered in this article, you will already be ahead of most teams.

Security is not optional. It is part of professional software engineering.