Single Sign-on filter to determine whether to exit based on key in Redis

Source: Internet
Author: User

 PackageCom.ailk.biapp.ci.localization.cntv.filter;Importjava.io.IOException;ImportJava.util.HashMap;ImportJava.util.Map;ImportJavax.servlet.FilterChain;Importjavax.servlet.ServletException;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;Importjavax.servlet.http.HttpSession;ImportNet.sf.json.JSONObject;Importorg.apache.commons.httpclient.HttpClient;ImportOrg.apache.commons.httpclient.methods.GetMethod;ImportOrg.springframework.http.HttpStatus;ImportOrg.springframework.web.filter.OncePerRequestFilter;ImportCom.ailk.biapp.ci.localization.cntv.model.UserMessage;ImportCom.ailk.biapp.ci.util.JsonUtil;Importcom.ailk.biapp.ci.util.RedisUtils;Importcom.asiainfo.biframe.privilege.IUserSession;Importcom.asiainfo.biframe.utils.config.Configure; Public classSessionfilterextendsonceperrequestfilter{//Login Page    PrivateString loginpage = Configure.getinstance (). GetProperty ("com.zyzx.dmc.login.html"); @Overrideprotected voiddofilterinternal (httpservletrequest request, httpservletresponse response, Filterchain Filterchain)throwsservletexception, IOException {httpservletrequest hrequest=(httpservletrequest) request; HttpSession Session=hrequest.getsession (); //non-filtered URIstring[] Notfilter =NewString[] {"login.html", ". js", "/css", "/images", "/logout", "/druid", "/login", "/ssoauth" }; //URI of the requestString URL =Request.getrequesturl (). toString (); //TokenString Token= Request.getparameter ("token");//String url = uri.replaceall ("html", "Bak"); //whether to filter        BooleanDoFilter =true;  for(String s:notfilter) {if(Url.indexof (s)! =-1) {                //If the URI contains a non-filtered URI, it is not filteredDoFilter =false;  Break; }        }                /** IF (uri.contains ("JSP") && uri.indexof ("login.jsp") = =-1) {DoFilter * = true;} */        if(doFilter) {//Perform filtering//get the login entity from the sessionObject user =request.getsession (). getattribute (Iusersession.asia_session_name); FinalIusersession usersession =(iusersession) Session.getattribute (iusersession.asia_session_name); FinalUsermessage usermessage = (usermessage) session.getattribute ("TOKEN"); if(Usermessage = =NULL) {                //not logged in status                if(NULL==token) {Response.sendredirect (LoginPage+ "? goto=" +URL); return; //token exists to save session, verify user information}Else{jsonobject result=Checktokeninfo (token); if(NULL==result) {Response.sendredirect (LoginPage+ "? goto=" +URL); return; }                    //Validation Successful                    if("Suc". Equals (Result.get ("Result"))){                      //Normal LoginMap<string,string> Sessionuserinfo =NewHashmap<string, string>(); Usermessage usermessage=Newusermessage (); 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); }                }                //if the login entity does not exist in the session, the popup prompts you to log in again                BooleanIsajaxrequest =isajaxrequest (Request); if(isajaxrequest) {//set the character set of request and response to prevent garbled charactersResponse.setcontenttype ("Text/html;charset=utf-8"); Response.senderror (HttpStatus.UNAUTHORIZED.value (),"You have been too long to operate, please refresh the page"); 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; }                    //if the login entity exists in the session, continueFilterchain.dofilter (request, response); }        } Else {            //If filtering is not performed, continueFilterchain.dofilter (request, response); }    }    /*** Determine if the AJAX request < feature description is detailed > * *@paramRequest *@returnis true, no false *@see[Class, Class # method, Class # member]*/     Public Static Booleanisajaxrequest (HttpServletRequest request) {String header= Request.getheader ("X-requested-with"); if(Header! =NULL&& "XMLHttpRequest". Equals (header))return true; Else            return false; }    /*** * Verify token exists *@paramTokenvalue *@return     * @throwsIOException*/    PrivateJsonobject Checktokeninfo (String tokenvalue)throwsIOException {String Checkurl= Configure.getinstance (). GetProperty ("COM.ZYZX.AQS.TOKENCHECKURL") +Tokenvalue; HttpClient HttpClient=NewHttpClient (); GetMethod HttpGet=NewGetMethod (Checkurl); Try{Httpclient.executemethod (httpget); String result=httpget.getresponsebodyasstring (); Jsonobject JSON=jsonobject.fromobject (Result); returnJSON; } finally{httpget.releaseconnection (); }    }    }

In fact, can be directly used usersession but because the project has been encapsulated, so create a Usermessage entity class, after login to the token to the session, when the key from the Redis to get token is empty, it clears the usersession, Jumps to the specified system page.

Single Sign-on filter to determine whether to exit based on key in Redis

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.