关于springsecurity添加自定义filter去除header中访问Authenzation的方法
因为springsecurity不论是否设置了开放路径只要请求中携带了authentization的请求头都会去校验token
这次因为有2个不同的系统,里面都带有security的依赖。
有一个系统的前端访问authentization带了他们的token过来,然后就会401的结果。
怎么让springsercurity 不去验证带了authentization的请求?
以下是解决的办法:
定义header返回值,这里如果不这么写可能会有一个问题,使用postman会正常执行并返回正常结果,但是如果用浏览器请求,会返回(fail)net::ERR_FAILED
public class HeaderMapRequestWrapper extends HttpServletRequestWrapper { /** * construct a wrapper for this request * * @param request */ public HeaderMapRequestWrapper(HttpServletRequest request) { super(request); } private Map<String, String> headerMap = new HashMap<>(); /** * add a header with given name and value * * @param name * @param value */ public void addHeader(String name, String value) { headerMap.put(name, value); } @Override public String getHeader(String name) { log.info("getHeader --->{}",name); String headerValue = super.getHeader(name); if (headerMap.containsKey(name)) { headerValue = headerMap.get(name); } return headerValue; } /** * get the Header names */ @Override public Enumeration<String> getHeaderNames() { List<String> names = Collections.list(super.getHeaderNames()); for (String name : headerMap.keySet()) { names.add(name); } return Collections.enumeration(names); } @Override public Enumeration<String> getHeaders(String name) { log.info("getHeaders --->>>>>>{}",name); List<String> values = Collections.list(super.getHeaders(name)); log.info("getHeaders --->>>>>>{}",values); if (headerMap.containsKey(name)) { log.info("getHeaders --->{}",headerMap.get(name)); values = Arrays.asList(headerMap.get(name)); } return Collections.enumeration(values); } }
自定义filter
public class DemoFilter extends OncePerRequestFilter{ @Overrider protected void doFilterInternal(HttpServletRequest request,HttpServletResponse response,FilterChain chain) throws IOException,ServletException{ if(过滤条件达成){ CustomHttpServletRequest custom = new CustomHttpServletRequest(request); //自定义的方法 custom.addHeader("替换的header",""); chain.doFilter(custom,response); return ; } chain.doFilter(request,response); } }
filter加入流程
//这里可以改成自己的配置类
public class DemoResourceServerConfigurerAdapter extends ResourceServerConfigurerAdapter{ //这里是让自定义filter加入security之前调用 @Override public void configure(HttpServlet http){ //主要代码 http.addFilterBefore(new DemoFilter(),SecurityContextPersistenceFilter.class); } }