Content-Security-Policy and Base 64 Images
published on
Not too long ago I started to add some additional security headers to the sites I build. I started doing this on my own site to explore new techniques, but then started to like the idea and a little extra security doesn't hurt.
A problem that I have ran into: When using base64 encoded images in your code and you want to add a Content-Security-Policy (CSP), the image-src
directive in the header needs a little extra instruction. It's not enough to declare self
or unsafe-inline
. Instead, for base64-encoded images, its "scheme" must be allowed.
data:image/png;base64,iVBORw0KGgoAAAANSUhEU…
The data:
part in the above is called the scheme, which is similar to a better known scheme like https:
. By using this scheme, it needs to be declared in the CSP. It's important to notice that the colon needs to be included, otherwise it won't work.
img-src 'self' data:;
The reason for this little awkwardness is that it's otherwise difficult to distinguish between a 'data' scheme, and a host named 'data'. You can find some more details in the spec.