1. 程式人生 > >ajax跨域傳遞cookie,驗證登入

ajax跨域傳遞cookie,驗證登入

ajax跨域登入:
系統許可權安全框架使用shiro,系統登入時傳送ajax請求呼叫springmvc action方法進行系統登入及身份認證,角色許可權授權等。由於ajax請求時,瀏覽器會認為攜帶Cookie是不安全請求,將限制其攜帶Cookie資訊,導致登入action方法無法獲取並響應相應的Cookie(JSESSIONID),身份認證及角色許可權授權、退出等都操作都無法正常使用。

解決辦法:
在客戶端中的 中jquery中的ajax中新增

crossDomain: true,

xhrFields:{ withCredentials:true },
//或者
beforeSend: function
(xhr) {
xhr.withCredentials = true; },

伺服器添寫一個過濾器

package com.game.filter;

import java.io.IOException;
import java.util.Collection;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import
javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; public class CORSFilter implements Filter { private final Logger logger = Logger.getLogger(CORSFilter.class); @Override
public void destroy() { } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse response = (HttpServletResponse) resp; HttpServletRequest request = (HttpServletRequest) req; //允許所有url路徑都可以跨域請求 //response.setHeader("Access-Control-Allow-Origin","*"); response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin")); //允許POST,GET,OPTIONS,DELETE的外域請求 response.setHeader("Access-Control-Allow-Methods","POST,GET,OPTIONS,DELETE"); //表名在3600秒內,不需要傳送預檢請求 response.setHeader("Access-Control-Max-Age","3600"); //表明允許跨域請求所包含的頭 //response.setHeader("Access-Control-Allow-Headers","host,connection,content-length,accept,origin,x-requested-with,user-agent,content-type,referer,accept-encoding,accept-language,cookie"); response.setHeader("Access-Control-Allow-Headers", "DNT,X-Mx-ReqToken,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Authorization,SessionToken,Cookie"); //ajax跨域求情允許傳遞cookie response.setHeader("Access-Control-Allow-Credentials", "true"); //獲取request的頭部資訊 Enumeration<String> headers = request.getHeaderNames(); while(headers.hasMoreElements()){ String header = headers.nextElement(); logger.info("header:"+header+" value:"+request.getHeader(header)); } //獲取response的頭部資訊 Collection<String> rheaders = response.getHeaderNames(); for(String header:rheaders){ logger.info("ResponseHeader:"+header+" ResponseValue:"+response.getHeader(header)); } //執行目標路徑的mothod chain.doFilter(req, resp); } @Override public void init(FilterConfig config) throws ServletException { } }

web.xml中的配置為:

<!-- 跨域請求預處理CORS -->
    <filter>
        <filter-name>CORS</filter-name>
        <filter-class>com.game.filter.CORSFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CORS</filter-name>
        <url-pattern>/game/*</url-pattern>
    </filter-mapping>

就可以傳遞cookie資料