DEV Community

Rizwan Saleem
Rizwan Saleem

Posted on

Frontend security: XSS, CSRF, CSP, and secure authentication flows

Frontend security: XSS, CSRF, CSP, and secure authentication flows

Frontend security is often overlooked because developers assume security is the backend's responsibility. But the frontend is the first line of defense against many attacks, and a secure frontend can prevent attacks that would otherwise reach your backend.

Cross-site scripting is the most common frontend vulnerability. XSS occurs when an attacker injects malicious scripts into your application. Prevent XSS by never inserting user content into the DOM without sanitization. Use textContent instead of innerHTML. React and modern frameworks escape output by default.

Cross-site request forgery tricks authenticated users into performing actions they didn't intend. If a user is logged into your bank and visits a malicious site, that site can submit a request to transfer money. CSRF tokens, SameSite cookies, and custom request headers prevent CSRF.

Content Security Policy is your most powerful frontend defense. CSP restricts what scripts, styles, and resources can load on your page. A strict CSP can prevent most XSS attacks even if there's a vulnerability in your code.

Secure cookie configuration prevents token theft. Set your cookies with HttpOnly, Secure, and SameSite=Strict. Never store authentication tokens in localStorage or sessionStorage they're accessible to any JavaScript on your page.

Authentication flows on the frontend must handle token storage and refresh securely. Use the authorization code flow with PKCE for OAuth. Store tokens in HttpOnly cookies when possible. Never expose tokens in URLs.

Third-party scripts are a major security risk. Each script you load from a CDN can be compromised. Self-host critical scripts. Use Subresource Integrity tags for scripts loaded from CDNs. Monitor which third-party scripts are loaded on your pages.

Security is a shared responsibility between frontend and backend. The frontend protects against attacks that affect the user's browser. The backend protects against attacks that reach the server. Both layers are essential.

-

Rizwan Saleem | https://rizwansaleem.co

Top comments (0)