天天看點

單點登入filter根據redis中的key判斷是否退出

package com.ailk.biapp.ci.localization.cntv.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;

import com.ailk.biapp.ci.localization.cntv.model.UserMessage;
import com.ailk.biapp.ci.util.JsonUtil;
import com.ailk.biapp.ci.util.RedisUtils;
import com.asiainfo.biframe.privilege.IUserSession;
import com.asiainfo.biframe.utils.config.Configure;

public class sessionFilter extends OncePerRequestFilter{

    // 登入頁面
    private String LoginPage = Configure.getInstance().getProperty("com.zyzx.dmc.login.html");

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        HttpServletRequest hrequest = (HttpServletRequest) request;
        HttpSession session = hrequest.getSession();
        // 不過濾的uri
        String[] notFilter = new String[] { "login.html", ".js", "/css","/images", "/logout", "/druid", "/login","/ssoAuth" };

        // 請求的uri
        String url = request.getRequestURL().toString();
        //Token

        String token = request.getParameter("token");
//        String url = uri.replaceAll("html", "bak");
        // 是否過濾
        boolean doFilter = true;
        for (String s : notFilter) {
            if (url.indexOf(s) != -1) {
                // 如果uri中包含不過濾的uri,則不進行過濾
                doFilter = false;
                break;
            }
        }
        
        /*
         * if(uri.contains("jsp") && uri.indexOf("login.jsp") == -1) { doFilter
         * = true; }
         */
        if (doFilter) {
            // 執行過濾
            // 從session中擷取登入者實體
            Object user = request.getSession().getAttribute(IUserSession.ASIA_SESSION_NAME);
            final IUserSession userSession = (IUserSession) session.getAttribute(IUserSession.ASIA_SESSION_NAME);
            final UserMessage UserMessage = (UserMessage) session.getAttribute("TOKEN");

            if (UserMessage == null) {
                //未登入狀态
                if(null == token){
                    response.sendRedirect(LoginPage + "?goto=" + url);
                    return;
                //token 存在則去儲存session,驗證使用者資訊
                }else{
                    JSONObject  result = checkTokenInfo(token);
                    if(null == result){
                        response.sendRedirect(LoginPage + "?goto=" + url);
                        return;
                    }
                    //驗證成功
                    if("suc".equals(result.get("result"))){
                      //正常登入
                        Map<String,String> sessionUserInfo = new HashMap<String, String>();
                        UserMessage userMessage = new UserMessage();
                        sessionUserInfo = JsonUtil.json2HashMap(result.get("userInfo").toString());
                        sessionUserInfo.put("token", token);
                        
                        String ip = request.getHeader("x-forwarded-for"); 
                        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
                            ip = request.getHeader("Proxy-Client-IP"); 
                        } 
                        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
                            ip = request.getHeader("WL-Proxy-Client-IP"); 
                        } 
                        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { 
                            ip = request.getRemoteAddr(); 
                        } 
                        userMessage.setUserID(sessionUserInfo.get("user_account"));
                        userMessage.setUserName(sessionUserInfo.get("user_name"));
                        userMessage.setSessionID(sessionUserInfo.get("token"));
                        userMessage.setClientIP(ip);
                        userMessage.setToken(sessionUserInfo.get("token"));
                        request.getSession().setAttribute(IUserSession.ASIA_SESSION_NAME,userMessage);
                        request.getSession().setAttribute("TOKEN",userMessage);
                        response.sendRedirect(url);
                    }else if("fail".equals(result.get("result"))){
                        response.sendRedirect(LoginPage + "?goto=" + url);
                    }
                }
                // 如果session中不存在登入者實體,則彈出框提示重新登入
                boolean isAjaxRequest = isAjaxRequest(request);
                if (isAjaxRequest) {
                    // 設定request和response的字元集,防止亂碼
                    response.setContentType("text/html;charset=UTF-8");
                    response.sendError(HttpStatus.UNAUTHORIZED.value(), "您已經太長時間沒有操作,請重新整理頁面");
                    return;
                }
                }else {
                    token = UserMessage.getToken();
                    String booleanexist = RedisUtils.getForString(token);
                    if(booleanexist == null){
                        session.removeAttribute("TOKEN");
                        session.removeAttribute(IUserSession.ASIA_SESSION_NAME);
                        response.sendRedirect(LoginPage + "?goto=" + url);
                        return;
                    }
                    // 如果session中存在登入者實體,則繼續
                    filterChain.doFilter(request, response);
                      }
        } else {
            // 如果不執行過濾,則繼續
            filterChain.doFilter(request, response);
        }
    }

    /**
     * 判斷是否為Ajax請求 <功能較長的描述>
     * 
     * @param request
     * @return 是true, 否false
     * @see [類、類#方法、類#成員]
     */
    public static boolean isAjaxRequest(HttpServletRequest request) {
        String header = request.getHeader("X-Requested-With");
        if (header != null && "XMLHttpRequest".equals(header))
            return true;
        else
            return false;
    }
    /**
     * 
     * 驗證Token是否存在
     * @param tokenValue
     * @return
     * @throws IOException
     */
    private JSONObject checkTokenInfo(String tokenValue) throws IOException {
        String checkUrl = Configure.getInstance().getProperty("com.zyzx.aqs.tokenCheckUrl")+tokenValue;
        HttpClient httpclient = new HttpClient();
        GetMethod httpget = new GetMethod(checkUrl);
        try {
            httpclient.executeMethod(httpget);
            String result = httpget.getResponseBodyAsString();
            JSONObject json = JSONObject.fromObject(result);
            return json;
        } finally {
            httpget.releaseConnection();
        }
    }
    
}      

其實可以直接用userSession 但由于項目已經封裝了,是以再建立個UserMessage實體類,在登入後将token存入session,當從redis中通過key擷取token為空時,便清除userSession,跳轉到指定系統頁面。