问题:页面跳转重新请求跨域问题
问题描述:
再使用SpringSecurity做安全登录的时候,前端使用ajax发送请求,请求发送过去,但是返回响应出现以下问题,
网上查询解决方法:添加一个过滤器,把这些请求都过滤掉 ,这个方法是正确的,但是发现WebSecurityConfigurerAdapter继承了filter类,所以在写以后过滤器的方法就不适用了,在SpringSecurity核心类中直接处理即可,
@Component
public class CrossDomainFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));//设置允许跨域访问的地址
response.setHeader("Access-Control-Allow-Methods", "HEAD, POST, GET, OPTIONS, DELETE, PUT");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
filterChain.doFilter(servletRequest, servletResponse);
}
@Override
public void destroy() {
}
}
在SpringSecurity核心类中加入这些方法
.successHandler(new AuthenticationSuccessHandler() {
@Override
public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
//在此处加入方法跟上面效果一样
method(httpServletRequest,httpServletResponse);
PrintWriter out = httpServletResponse.getWriter();
RespBean respBean= RespBean.ok("登录成功",authentication.getPrincipal());
out.write(new ObjectMapper().writeValueAsString(respBean));
out.flush();
out.close();
}
})
public static void method(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse){
httpServletResponse.setContentType("application/json;charset=utf-8");
httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));//设置允许跨域访问的地址
httpServletResponse.setHeader("Access-Control-Allow-Methods", "HEAD, POST, GET, OPTIONS, DELETE, PUT");
httpServletResponse.setHeader("Access-Control-Max-Age", "3600");
httpServletResponse.setHeader("Access-Control-Allow-Headers", "x-requested-with");
httpServletResponse.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
}
以上