单点登录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,跳转到指定系统页面。

posted on 2015-11-17 00:15  松伯  阅读(1204)  评论(0编辑  收藏  举报