Skip to content

HeaderWriterFilter writes headers at beginning #6509

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.security.config.annotation.authentication.configurers;

import javax.servlet.Filter;
import javax.servlet.ServletException;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import org.springframework.mock.web.MockFilterChain;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.mock.web.MockServletContext;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.header.HeaderWriterFilter;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;

import static org.assertj.core.api.Assertions.assertThat;

/**
* Tests for {@link HeadersConfigurer}.
*
* @author Ankur Pathak
*/
public class HeadersConfigurerJavaTests {

private boolean allowCircularReferences = false;
private MockServletContext servletContext;
private MockHttpServletRequest request;
private MockHttpServletResponse response;
private MockFilterChain chain;
private ConfigurableWebApplicationContext context;


@Before
public void setUp() {
this.servletContext = new MockServletContext();
this.request = new MockHttpServletRequest(this.servletContext, "GET", "");
this.response = new MockHttpServletResponse();
this.chain = new MockFilterChain();
}


@After
public void cleanup(){
if (this.context != null){
this.context.close();
}
}


@EnableWebSecurity
public static class HeadersAtTheBeginningOfRequestConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.headers()
.addObjectPostProcessor(new ObjectPostProcessor<HeaderWriterFilter>() {
@Override
public HeaderWriterFilter postProcess(HeaderWriterFilter filter) {
filter.setShouldWriteHeadersEagerly(true);
return filter;
}
});
}
}

@Test
public void headersWrittenAtBeginningOfRequest() throws IOException, ServletException {
this.context = loadConfig(HeadersAtTheBeginningOfRequestConfig.class);
this.request.setSecure(true);
getSpringSecurityFilterChain().doFilter(this.request, this.response, this.chain);
assertThat(getResponseHeaders()).containsAllEntriesOf(new LinkedHashMap<String, String>(){{
put("X-Content-Type-Options", "nosniff");
put("X-Frame-Options", "DENY");
put("Strict-Transport-Security", "max-age=31536000 ; includeSubDomains");
put("Cache-Control", "no-cache, no-store, max-age=0, must-revalidate");
put("Expires", "0");
put("Pragma", "no-cache");
put("X-XSS-Protection", "1; mode=block");
}});
}


@SuppressWarnings("unchecked")
private Map<String, String > getResponseHeaders() {
Map<String, String> headers = new LinkedHashMap<>();
this.response.getHeaderNames().forEach(name -> {
List values = this.response.getHeaderValues(name);
headers.put(name, String.join(",", values));
});
return headers;
}

private ConfigurableWebApplicationContext loadConfig(Class<?>... configs) {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(configs);
context.setAllowCircularReferences(this.allowCircularReferences);
context.setServletContext(this.servletContext);
context.refresh();
return context;
}

private Filter getSpringSecurityFilterChain() {
return this.context.getBean("springSecurityFilterChain", Filter.class);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ public class HeaderWriterFilter extends OncePerRequestFilter {
*/
private final HeaderWriter headerWriter;

/**
* Indicates whether to write the headers at the beginning of the request.
*/
private boolean shouldWriteHeadersEagerly = false;

/**
* Creates a new instance.
*
Expand All @@ -67,18 +72,41 @@ protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

if (this.shouldWriteHeadersEagerly) {
doHeadersBefore(request, response, filterChain);
} else {
doHeadersAfter(request, response, filterChain);
}
}

private void doHeadersBefore(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
this.headerWriter.writeHeaders(request, response);
filterChain.doFilter(request, response);
}

private void doHeadersAfter(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
HeaderWriterResponse headerWriterResponse = new HeaderWriterResponse(request,
response, this.headerWriter);
HeaderWriterRequest headerWriterRequest = new HeaderWriterRequest(request,
headerWriterResponse);

try {
filterChain.doFilter(headerWriterRequest, headerWriterResponse);
} finally {
headerWriterResponse.writeHeaders();
}
}

/**
* Allow writing headers at the beginning of the request.
*
* @param shouldWriteHeadersEagerly boolean to allow writing headers at the beginning of the request.
* @author Ankur Pathak
* @since 5.2
*/
public void setShouldWriteHeadersEagerly(boolean shouldWriteHeadersEagerly) {
this.shouldWriteHeadersEagerly = shouldWriteHeadersEagerly;
}

static class HeaderWriterResponse extends OnCommittedResponseWrapper {
private final HttpServletRequest request;
private final HeaderWriter headerWriter;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,4 +136,25 @@ public void doFilterWhenRequestContainsIncludeThenHeadersStillWritten() throws E

verifyNoMoreInteractions(this.writer1);
}

@Test
public void headersWrittenAtBeginningOfRequest() throws Exception {
HeaderWriterFilter filter = new HeaderWriterFilter(
Collections.singletonList(this.writer1));
filter.setShouldWriteHeadersEagerly(true);

MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();

filter.doFilter(request, response, new FilterChain() {
@Override
public void doFilter(ServletRequest request, ServletResponse response)
throws IOException, ServletException {
verify(HeaderWriterFilterTests.this.writer1).writeHeaders(
any(HttpServletRequest.class), any(HttpServletResponse.class));
}
});

verifyNoMoreInteractions(this.writer1);
}
}