我们如何从'HttpServletRequest'中删除“授权”标题

时间:2015-11-09 15:31:55

标签: java servlets

我们如何从'HttpServletRequest'中删除“授权”标题。

我们有2个过滤器,在第一个过滤器之后,我们需要在将请求传递给第二个过滤器之前从请求中删除“Authorization”标头。我知道我们可以使用

添加标题
    HttpServletRequest req = (HttpServletRequest) request;

     HeaderMapRequestWrapper requestWrapper = new HeaderMapRequestWrapper(req);

    //requestWrapper.addHeader("Authorization", "PPPPPPPP");

    requestWrapper.removeHeader("Authorization"); // Did not work

    public void removeHeader(String name) {
        headerMap.remove(name);
    }

但是我们如何删除“授权”标题。

2 个答案:

答案 0 :(得分:3)

一种可能的解决方案是将原始请求包装在自定义的HttpServletRequestWrapper中,该请求会覆盖getHeadergetHeadersgetHeaderNames方法:

request = new HttpServletRequestWrapper(request) {
    private Set<String> headerNameSet;

    @Override
    public Enumeration<String> getHeaderNames() {
        if (headerNameSet == null) {
            // first time this method is called, cache the wrapped request's header names:
            headerNameSet = new HashSet<>();
            Enumeration<String> wrappedHeaderNames = super.getHeaderNames();
            while (wrappedHeaderNames.hasMoreElements()) {
                String headerName = wrappedHeaderNames.nextElement();
                if (!"Authorization".equalsIgnoreCase(headerName)) {
                    headerNameSet.add(headerName);
                }
            }
        }
        return Collections.enumeration(headerNameSet);
    }

    @Override
    public Enumeration<String> getHeaders(String name) {
        if ("Authorization".equalsIgnoreCase(name)) {
            return Collections.<String>emptyEnumeration();
        }
        return super.getHeaders(name);
    }

    @Override
    public String getHeader(String name) {
        if ("Authorization".equalsIgnoreCase(name)) {
            return null;
        }
        return super.getHeader(name);
    }
};

答案 1 :(得分:1)

看起来HeaderMapRequestWrapper是您自己实现的内容,因为它不是规范标准,我在Google上可以找到关于此类的唯一内容就是此代码示例:http://www.codegithub.com/watch?v=0NByHgxUxPPU

假设HeadermapRequestWrapper是您从该代码示例中复制的类,只需添加removeHeader()方法。

public void removeHeader(String name) {
    headerMap.remove(name);
}