Intermediate Topic 25 of 51 Security & Cryptography
Cross-Site Scripting
Attack injecting script into pages seen by others.
How it works
Cross-site scripting happens when an application includes untrusted data in a page without proper encoding, so an attacker's script executes in a victim's browser within the site's origin. Types are stored, where the payload is saved on the server, reflected, where it comes from the request, and DOM-based, where client-side code writes it into the page. A script can steal session data, perform actions as the user or rewrite the page.
Step-by-step walkthrough
- The attacker posts a comment containing a script.
- The site stores it unescaped.
- A victim loads the page.
- The script runs in the victim's browser with the site's privileges.
- It can steal cookies, so escape output and use a content security policy.
Where it is used
Every website displaying user content, such as comments, profiles and search results, must defend against XSS with context-aware output encoding, safe templating frameworks and sanitizing any allowed HTML.
Common pitfall
Using innerHTML or dangerouslySetInnerHTML with user data, building URLs with javascript: schemes and trusting client-side filtering are typical failures. Encoding must match the context: HTML, attribute, JavaScript or URL. Add Content Security Policy, HttpOnly cookies and Trusted Types as defense in depth.
Where it fits in the course
Cross-Site Scripting is topic 25 of 51 in Security & Cryptography, rated Intermediate. It follows SQL Injection. The next topic is CSRF.
Practice and explore
- Open the interactive lesson, with a mini quiz.
- Take the Security & Cryptography quiz.
How to study this topic
- Read the explanation above and restate the definition in your own words.
- Open the interactive lesson and answer its mini quiz.
- Read the common pitfall, then write a short example that avoids it.
- Check your understanding in the Security & Cryptography quiz, and revisit the topic if you miss a question.
Frequently asked questions
What is Cross-Site Scripting?
Where do people use Cross-Site Scripting?
What is the most common mistake with Cross-Site Scripting?
What should I learn before this topic?
How can I practice it?
Is Cross-Site Scripting hard to learn?
How long does it take to learn Cross-Site Scripting?
Which topics are related to Cross-Site Scripting?
What should I study after Cross-Site Scripting?
Related topics
- SQL Injection (Security & Cryptography)
- CSRF (Security & Cryptography)
- Message Authentication Codes (Security & Cryptography)
- Buffer Overflow (Security & Cryptography)
- Cross-Platform Frameworks (Mobile, Embedded & IoT)
- Shell Scripting (DevOps & Tooling)
- Cross-Validation (AI & Machine Learning)