我有一个自定义的春季AuthenticationProvider
课程,但尝试拦截HTTPServletRequest
方法中的HTTPServletResponse
和loadUserDetails
。
@Component("darnGoodAuthenticaionProvider")
public class DarnGoodAuthenticaionProvider
extends HandlerInterceptorAdapter
implements AuthenticationUserDetailsService {
private HttpServletRequest request;
private HttpServletResponse response;
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler)
throws Exception {
this.request = request;
this.response = response;
// we don't want anything falling here
return true;
}
@Override
public UserDetails loadUserDetails(Authentication token)throws
UsernameNotFoundException{
.......
}
}
我知道来自preHandler
的{{1}}方法能胜任这项工作,但我怎样才能确定在HandlerIntercepterAdapter
之前调用preHandler
方法,以便我可以得到请求和响应吗?
由于
答案 0 :(得分:1)
在servlet容器上,每个请求都将从收到请求的那一刻开始处理,直到只有一个线程(request == current thread)返回响应。
所以这是在Spring安全过滤器链之前放置一个servlet过滤器(在spring-security的过滤器映射之上使用filter-mapping元素),并使用{{1}将请求和响应存储在线程中变量 - 另请参阅此answer。
然后在ThreadLocal
上使用静态方法DarnGoodAuthenticaionProvider
访问请求。
web.xml配置:
RequestResponseHolder.getRequest()
过滤以在线程中保存请求响应:
<filter>
<filter-name>saveRequestResponseFilter</filter-name>
<filter-class>sample.save.request.filter.SaveRequestResponseFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>saveRequestResponseFilter</filter-name>
<url-pattern>/mobilews/*</url-pattern>
</filter-mapping>
请求/响应持有者:
public class SaveRequestResponseFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse resp = (HttpServletResponse) response;
RequestResponseHolder.setRequestResponse(req,resp);
try {
chain.doFilter(request, response);
}
finally {
RequestResponseHolder.clear();
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
...
}
@Override
public void destroy() {
...
}
}
从public class RequestResponseHolder {
private static ThreadLocal<HttpServletRequest> requestHolder = new ThreadLocal<HttpServletRequest>();
private static ThreadLocal<HttpServletResponse> responseHolder = new ThreadLocal<HttpServletResponse>();
public static void setRequestResponse(HttpServletRequest request, HttpServletResponse response) {
requestHolder.set(request);
responseHolder.set(response);
}
public static HttpServletRequest getServletRequest(){
return requestHolder.get();
}
public static HttpServletResponse getServletResponse() {
return responseHolder.get();
}
public static void clear() {
requestHolder.remove();
responseHolder.remove();
}
}
获取请求:
DarnGoodAuthenticaionProvider