Threadlocal+cookie of implementation of Java stateless login

Source: Internet
Author: User
Tags base64 set cookie

Note: the non-state referred to in this article refers to the need to complete the session authentication, the user package information.

Non-stateful advantages:

  1. Multi-application Single sign-on: In multiple applications, only after logging in to server login. Each child application does not need to log on again.

  2. Multi-server clusters: You can do this without creating a cache for session sharing.

Disadvantages of this scenario:

  1, relying on cookies, even though mainstream browsers now support cookies.

  2. Single sign-on requires that the sub-applications belong to the same primary domain (the cross-primary domain cannot be implemented).

Implementation principle:

  Encapsulates user information at logon and writes user information to user cookies through serialized encryption. The next time the user requests the application server, the filter takes the user information to the anti-decryption deserialization and puts it into threadlocal, taking advantage of the threadlocal thread security feature, and then taking the user information.


User encapsulation Information class

Package Com.xxx.commons.framework.bean;import Java.io.serializable;public class Principal implements Serializable { Private static final Long Serialversionuid = -1373760761780840081l;private long id;private String username;private intege  R usertype;private Long Pharmacyid;private long salemanid;private long ydid;private String name;public Principal (Long ID, String username,integer usertype,long pharmacyid,long salemanid,long ydid,string name) {this.id = Id;this.username = user Name;this.usertype = Usertype;this.pharmacyid = Pharmacyid;this.salemanid = Salemanid;this.ydid = YdId;this.setName ( name);} Public Long GetId () {return ID;} public void SetId (Long id) {this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} @Overridepublic String toString () {return username;} Public Integer Getusertype () {return usertype;} public void Setusertype (Integer usertype) {this.usertype = usertype;} /** * @return Pharmacyid * */public Long Getpharmacyid () {return Pharmacyid;} /** * @param pharmacyid * */public void Setpharmacyid (Long pharmacyid) {This.pharmacyid = Pharmacyid;} /** * @return Salemanid * */public Long Getsalemanid () {return salemanid;} /** * @param salemanid * */public void Setsalemanid (Long salemanid) {This.salemanid = Salemanid;} /** * @return Ydid * */public Long Getydid () {return ydid;} /** * @param ydid * */public void Setydid (Long ydid) {this.ydid = Ydid;} /** * Get name * @return the name * */public String getName () {return name;} /** * Set Name * @param name * */public void SetName (String name) {this.name = name;}}


User Information Tool class

/** * Copyright RH Corporation 2014 All rights reserved * Created December 18, 2014 PM 1:24:27 * @version V1.0 */package Com.xxx.common S.framework.utils;import com.xxx.commons.framework.bean.principal;/** * Add class descriptive narrative * @authorElongDeo * @version1.0 * Created2014 December 18 pm 1:24:27 */public class Userutil {public static final threadlocal<principal> Principal = new THR Eadlocal<principal> (); public static Principal Getuserprincipal () {Principal Principal = UserUtil.principal.get (); return Principal;} public static string GetUserName () {String userName = ""; Principal Principal = Getuserprincipal (); if (principal!=null) {userName = Principal.getusername ();} return userName;} public static string GetName () {String name = ""; Principal Principal = Getuserprincipal (); if (principal!=null) {name = Principal.getname ();} return name; public static long GetUserId () {long userId = null; Principal Principal = Getuserprincipal (); if (principal!=null) {userId = Principal.getid ();} return userId;} public static Integer GetusertYpe () {Integer usertype = null; Principal Principal = Getuserprincipal (); if (principal!=null) {usertype = Principal.getusertype ();} return usertype;} public static long Getpharmacyid () {long Pharmacyid = null; Principal Principal = Getuserprincipal (); if (principal!=null) {Pharmacyid = Principal.getpharmacyid ();} return Pharmacyid;} public static long Getsalemanid () {long salemanid = null; Principal Principal = Getuserprincipal (); if (principal!=null) {Salemanid = Principal.getsalemanid ();} return Salemanid;} public static long Getydid () {long ydid = null; Principal Principal = Getuserprincipal (); if (principal!=null) {ydid = Principal.getydid ();} return ydid;} public static long Getbuyerid () {Long Buyerid = Null;integer usertype = Getusertype (); if (usertype! = null && userty PE > Constants.user_admin_type) {if (Usertype.equals (Constants.user_pharmary_type)) {Buyerid = GetPharmacyId ();} Else{buyerid = Getydid ();}} return Buyerid;} public static string Getcartyn () {String Cartyn = "No"; Integer usertype = GetUserType (); if (Usertype > Constants.user_admin_type) {Cartyn = "yes";} return Cartyn;}}

Cookie Tool Class (used to encapsulate/parse user information)

/** * Cookieutils.java Copyright? 2008-2013 lefeng.com Inc. All rights Reserved. */package Com.xxx.commons.framework.utils;import Java.util.hashmap;import Java.util.map;import Javax.servlet.http.cookie;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.codec.binary.base64;import Com.xxx.commons.framework.bean.principal;import com.xxx.commons.items.propertiesfileloader;/** * <pre> * < p>author:elongdeo</p> * <p>date:2014-3-10 </P> * <p>cookie Operation Auxiliary class </P> * </pre> * /public class Cookieutils {public static string DOMAIN = ". xxx.com";p ublic static final String cookie_token_login = "xxx_t Oken ";p ublic static final String cookie_user_info =" Xxx_user "; static {Propertiesfileloader instance = Propertiesfileloader.getinstance ();D omain = instance.getproerties ("Config/user.properties", "DOMAIN");} /** * Set Cookie * @param response * @param name Cookie name * @param value of cookie * @paramMaxAge cookie lifetime in seconds */public static void Addcookie (HttpServletResponse response,string name,string value,int MaxAge,    String domain) {Cookie cookie = new Cookie (name,value);    Cookie.setdomain (domain);    Cookie.setpath ("/");    if (maxage>0) cookie.setmaxage (MaxAge); Response.addcookie (cookie);} /** * Obtain a cookie by name * @param request * @param name Cookie name * @return */public static cookie Getcookiebyname (Httpservletreq    Uest request,string name) {map<string,cookie> Cookiemap = readcookiemap (request);        if (Cookiemap.containskey (name)) {Cookie cookie = (cookie) cookiemap.get (name);    return cookie;    }else{return null; }}/** * Enclose the Cookie in MAP * @param request * @return */public static map<string,cookie> Readcookiemap (httpservletre    Quest request) {map<string,cookie> Cookiemap = new hashmap<string,cookie> ();    cookie[] cookies = request.getcookies (); if (null!=cookies) {for (Cookie cookie:cookies) {COOKiemap.put (Cookie.getname (), cookie); }} return cookiemap;} public static Principal Getprincipal (HttpServletRequest request) {Cookie Cookie = getcookiebyname (Request, Cookie_user_ INFO); if (cookie! = NULL &&! "). Equals (Cookie.getvalue ())) {try {return (Principal) serializeutils.deserialize (Base64.decodebase64 (cookie.getvalue ()));} catch (Exception e) {e.printstacktrace ();}} return null;} public static void Setprincipal (HttpServletResponse response, Principal Principal) {try {Addcookie (response, Cookie_ User_info, Base64.encodebase64string (serializeutils.serialize (Principal)), 0, DOMAIN);} catch (Exception e) {e.printstacktrace ();}} public static void Removeprincipal (HttpServletResponse response) {try {Addcookie (response, cookie_user_info, NULL, 0, DOMAIN);} catch (Exception e) {e.printstacktrace ();}}}


Login Write cookie code snippet

Principal Principal = new Principal (userId,  login, usertype, Pharmacyid, Salemanid, Ydid, name);//assuming correct, Then write the cookie and jump correctly to try {Cookieutils.setprincipal (response, principal); redirect = Stringutils.isempty ( Request.getparameter ("redirect"))?

LOGIN_REDIRECT_URL:request.getParameter ("REDIRECT");//need to handle home printutils.printtomobile (response, New Resultobject <Object> (1, redirect), "JSON"); return;} catch (Exception e) {e.printstacktrace ();}


filter to get user information and put into threadlocal

/** * */package com.xxx.commons.framework.filters;import java.io.ioexception;import Java.util.HashSet;import Java.util.set;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;import Com.xxx.commons.framework.utils.cookieutils;import Com.xxx.commons.framework.utils.stringutils;import com.xxx.commons.framework.utils.userutil;/** * Servlet Filter Implementation class Authenticationfilter */public class Principalfilter implements Filter {Logger Logger = Logger.getlog GER (Principalfilter.class);p rivate static String Notloginurl = null;//ignored all url.private static set<string> Mobjignoredurls = new hashset<string> ();/** * @see filter#dofilter (servletrequest, Servletresponse, FilterChain) */public void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, Servletexception { UserUtil.principal.set (Cookieutils.getprincipal (httpservletrequest) request); if (notloginurl! = null && UserUtil.principal.get () = = null &&!isignoreurl ((httpservletrequest) request) {(httpservletresponse) Response). Sendredirect (Notloginurl); return;} Chain.dofilter (request, response);} /** * Add descriptive narrative * @author Elongdeo June 26, 2015 * @param filterconfig * @throws servletexception */@Overridepublic void init (F Ilterconfig filterconfig) throws servletexception {Notloginurl = Filterconfig.getinitparameter ("NotLoginUrl");// Packaging to be ignored urlstring Urltext = Filterconfig.getinitparameter ("Ignoredurls"); if (urltext! = null) {Urltext = Urltext.replaceall ("\ r \ n", ""). ReplaceAll ("\ T", ""). Trim (); string[] URLs = Urltext.split (","); for (int i = 0; i < urls.length; i++) {Mobjignoredurls.add (urls[i]);}}} /** * <pre> * Verify if the URL to be ignored. * </pre> * * @param pobjrequest * the Pobjrequest * @return True, if is ignore URL * @author Guotianchi 2011-4-20 */private boolean isignoreurl (httpservletrequ EST pobjrequest) {String Objrequesturi = Pobjrequest.getrequesturi (); if (Stringutils.isnotempty (Objrequesturi)) {int index = Objrequesturi.lastindexof ('/'); if (index >= 0&& Index < (objrequesturi.length ()-1) && Mobj Ignoredurls.contains (objrequesturi.substring (index + 1, objrequesturi.length ()))) {return true;}} return false;} /** * Add descriptive narrative * @author Elongdeo June 26, 2015 */@Overridepublic Void Destroy () {}}

Apply Serverweb.xml configuration

    <filter><filter-name>PrincipalFilter</filter-name><filter-class> Com.xxx.commons.framework.filters.principalfilter</filter-class><init-param><param-name> notloginurl</param-name><param-value>/common/logout.htm</param-value></init-param>< Init-param><param-name>ignoredurls</param-name><param-value>logout.htm</param-value ></init-param></filter>    <filter-mapping><filter-name>principalfilter</ Filter-name><url-pattern>/*</url-pattern></filter-mapping>


Threadlocal+cookie of implementation of Java stateless login

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.