Add custom HSTS filter using ContainerResponseFilter

北战南征 提交于 2021-02-11 12:12:31

问题


I've tried to update HSTS header value using custom filter (using ContainterResponseFilter)

This is my class where I'm setting HSTS header values but there is some unknown issue that's preventing to update these values on server. I've checked locally and it's getting updated but not on server.

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.Provider;

import org.glassfish.jersey.server.ContainerRequest;
@Provider
public class HSTSFilter implements ContainerResponseFilter {
  private static final String HEADER_NAME = "Strict-Transport-Security";
  private static final String MAX_AGE_DIRECTIVE = "max-age=%s";
  private static final String INCLUDE_SUB_DOMAINS_DIRECTIVE = "includeSubDomains";
  private static final String HTTPS = "https";

  private int maxAgeSeconds = 31536000;
  private String hstsHeaderValues = "";

  private final EnhancedLocLogger LOGGER;

  @Inject
  public HSTSFilter(final EnhancedLocLoggerFactory locLoggerFactory) {
    this.LOGGER = locLoggerFactory.getLogger(HSTSFilter.class);
    this.init();
  }

  @Override
  public void filter(final ContainerRequestContext requestContext, final ContainerResponseContext responseContext) {
    if (((ContainerRequest) requestContext).getRequestUri().getScheme().equalsIgnoreCase("https")) {
      MultivaluedMap<String, Object> headers = responseContext.getHeaders();
      headers.putSingle(HEADER_NAME, hstsHeaderValues);
    }
  }

  public void init() {
    final List<String> hstsValues = new ArrayList<>();
    hstsValues.add(String.format(MAX_AGE_DIRECTIVE, this.maxAgeSeconds));
    hstsValues.add(INCLUDE_SUB_DOMAINS_DIRECTIVE);
    hstsHeaderValues = String.join("; ", hstsValues);
  } 

来源:https://stackoverflow.com/questions/65617801/add-custom-hsts-filter-using-containerresponsefilter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!