最近由于开发后台管理系统遇到问题,用户登录凭证失效,因为采用SSO处理,后台管理系统和SSO都是使用的二级域名
1.Ajax请求返回结果如果为重定向,其实是不生效
2.Iframe跨域会直接报错:Refused to display in a frame because it set 'X-Frame-Options' to 'deny'
最终方案:
思路:后台拦截处理的时候根据判断头部区分ajax请求和普通请求。如果为ajax请求则在ajax请求完成后处理,如果为其他请求则重定向到本系统的一个错误页面,然后通过js重定向,这样可以不依赖服务器配置,直接程序处理。好了。直接贴代码吧。
第一步:后台拦截用户登录处理
// 拦截处理块代码如下:
String header = ((HttpServletRequest) request).getHeader("X-Requested-With");
if ("XMLHttpRequest".equalsIgnoreCase(header)) {//ajax请求
return "redirect:/ajaxLoginError";
}else{
return "redirect:/frameLoginError";
}
/**
* ajax登录错误时执行
*/
@RequestMapping(value = "/ajaxLoginError", method = RequestMethod.GET)
@ResponseBody
public BaseOutVo<String> ajaxLoginError() {
return BaseOutVo.err("ajaxLoginError", "login session error", "重定向的URL");
}
/**
* frame登录错误时执行
*/
@RequestMapping(value = "/frameLoginError", method = RequestMethod.GET)
public ModelAndView frameLoginError() {
ModelAndView view = new ModelAndView("redirect");
try {
view.addObject("url", URLEncoder.encode(clientDetails.getResponseUrl(), "UTF-8"));
} catch (Exception e) {
}
return view;
}
第二步:JS添加Jquery的ajax请求处理
$.ajaxSetup({
//设置ajax请求结束后的执行动作
complete : function(xhr, textStatus) {
if (xhr.responseJSON != null && xhr.responseJSON.code === "ajaxLoginError") {
var win = window;
while (win != win.top){
win = win.top;
}
//将后端重定向的地址取出来,使用win.location.href去实现重定向的要求
win.location.href= xhr.responseJSON.data;
}
},
type:'POST'
});
第三步:iframe添加重定向页面redirect.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>XXX管理后台</title>
</head>
<body>
<script>
top.location.href= unescape("[[${url}]]");
</script>
</body>
</html>