WebSecurityInterceptor implements Interceptor { void appendSecurityHeaders(Response response) { response.header("Strict-Transport-Security", "max-age=31536000"); response.contentType().ifPresent(contentType -> { if (TEXT_HTML.mediaType.equals(contentType.mediaType)) { if (contentSecurityPolicy != null) { response.header("Content-Security-Policy", contentSecurityPolicy); } response.header("X-XSS-Protection", "1; mode=block"); response.header("X-Frame-Options", "DENY"); response.header("Referrer-Policy", "origin-when-cross-origin"); } response.header("X-Content-Type-Options", "nosniff"); }); }  @Override Response intercept(Invocation invocation); public String contentSecurityPolicy; }
@Test void appendSecurityHeaders() { interceptor.contentSecurityPolicy = "default-src 'self';"; when(response.contentType()).thenReturn(Optional.of(ContentType.TEXT_HTML)); interceptor.appendSecurityHeaders(response); verify(response).header(eq("Strict-Transport-Security"), anyString()); verify(response).header("Content-Security-Policy", interceptor.contentSecurityPolicy); verify(response).header(eq("X-XSS-Protection"), anyString()); verify(response).header(eq("X-Content-Type-Options"), anyString()); verify(response).header(eq("X-Frame-Options"), anyString()); }
@Test void skipCSP() { interceptor.contentSecurityPolicy = null; when(response.contentType()).thenReturn(Optional.of(ContentType.TEXT_HTML)); interceptor.appendSecurityHeaders(response); verify(response, never()).header(eq("Content-Security-Policy"), anyString()); }