ContentSecurityPolicy
header in spring security e.g. extending the example from the previous spring security tutorials.@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests(authorizeRequests ->
authorizeRequests
.mvcMatchers("/dashboard").authenticated()
.mvcMatchers("/user/**").hasAnyRole("USER","ADMIN")
.mvcMatchers("/admin/**").hasRole("ADMIN")
.mvcMatchers("/styles/**").permitAll()
.mvcMatchers("/signup").permitAll()
.anyRequest().denyAll()
)
.formLogin(formLogin ->
formLogin
.permitAll()
).logout(logout ->
logout
.permitAll())
.headers().contentSecurityPolicy(csp ->
csp.policyDirectives("default-src 'self'; object-src 'self'")
);
}
csp.policyDirectives("default-src 'self'; script-src 'unsafe-inline'; object-src 'self'")
. However, do not do this as you are allowing possibly malicious JavaScript to run if it gets reflected back onto the page..js
file served from, for example, your static resource folder. This is then loaded using the tag. As this will be located on the same origin (so origin is 'self'
) the browser will load, trust, and execute it.onclick=""
etc. These need to be replaced with addEventListener()
calls. For example: //In your HTML
<script>
function alertMe(){
window.alert("hi");
}
</script>
<div onclick="alertMe()"/>
Should be replaced by:
//In your HTML
<div id="clickable-div"/>
//In your external js file
function alertMe(){
window.alert("hi");
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('clickable-div')
.addEventListener('click', alertMe);
});
onclick
, so you need to include the event listener in your inline script as well. //In the HTML
<script>
function alertMe(){
window.alert("hi");
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('game-container')
.addEventListener('click', alertMeExternally);
});
</script>
becomes the ‘string to hash' of:
function alertMe(){window.alert("hi");}document.addEventListener('DOMContentLoaded',function(){document.getElementById('game-container').addEventListener('click', alertMe);});
which you must also use in your <script> tag (replacing the formatted one in the first snippet):
<script>function alertMe(){window.alert("hi");}document.addEventListener('DOMContentLoaded',function(){document.getElementById('game-container').addEventListener('click', alertMe);});</script>
siPmkQwTblLsYDVnOPqTPEfWGML0dXY0o+SdZF6GGB0
. A hash can be generated using various command line tools or websites e.g. https://approsto.com/sha-generator/.script-src
; csp.policyDirectives("default-src 'self'; script-src 'sha256-siPmkQwTblLsYDVnOPqTPEfWGML0dXY0o+SdZF6GGB0'; object-src 'self'")