Web applications often handle sensitive user data, which makes them attractive targets for attacks such as crosssite scripting (XSS). Content security policy (CSP) is a contentrestriction mechanism, now supported by all major browsers, that offers thorough protection against XSS. Unfortunately, simply enabling CSP for a web application would affect the application's behavior and likely disrupt its functionality. To address this issue, we propose AUTOCSP, an automated technique for retrofitting CSP to web applications. AUTOCSP (1) leverages dynamic taint analysis to identify which content should be allowed to load on the dynamically-generated HTML pages of a web application and (2) automatically modifies the serverside code to generate such pages with the right permissions. Our evaluation, performed on a set of real-world web applications, shows that AUTOCSP can retrofit CSP effectively and efficiently.