Implementation of Java single sign-on

Source: Internet
Author: User

Recently the company is going to make a single sign-on application, integrating forums and websites. To find a lot of information on the Internet, and finally a successful solution, the blog to record one side forget.

Single sign-on first of all to maintain the consistency of database data, this implementation is a lot of I do not have much nonsense.

At first my idea was to send an HTTP request to another application when landing in an application to ensure that two applications have a session at the same time, and later consider that the session expiration is not synchronized with the problem can only be discarded. In order to maintain full synchronization of the session I can only turn to cookies, first of all, to say:
1. To set path in the root directory for two application applications that can access the Cookie,cookie settings at the same time (the same server does not
With the application, not the same application can use a common domain name, such as. baidu.com, you must ensure that the cookie in the unified domain
2. When accessing an application first detects session if existence is already logged in to save cookies (guaranteed cookies are up to date)
3. If the session does not exist detection cookies if Cooki does not exist the description is not logged in another application
4.cookie There is a detection creation time (of course to set a time to save) if you do not expire, use the username password saved in the cookie to call the login method
5. Log in successfully save cookies

In order to ensure that every request can be detected I use filter below to paste the filter code
Import java.io.IOException;

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;

public class Loginfilter implements Filter {

Private String Logininfopath;
public void Destroy () {
Logininfopath = null;
}

public void Dofilter (ServletRequest sreq, Servletresponse Sresp,
Filterchain chain) throws IOException, Servletexception {
HttpServletRequest req = (httpservletrequest) sreq;
HttpServletResponse resp = (httpservletresponse) sresp;
Class logininfoclass = null;
Logininfobase logininfo = null;
try {
Logininfoclass = Class.forName (Logininfopath);
Logininfo = (logininfobase) logininfoclass.newinstance ();
catch (ClassNotFoundException e) {
E.printstacktrace ();
catch (Instantiationexception e) {
E.printstacktrace ();
catch (Illegalaccessexception e) {
E.printstacktrace ();
}
Logininfo.setreq (req);
Logininfo.setresp (RESP);
The session value is empty
if (Logininfo.issessionempty ()) {
if (Logininfo.init ()) {
Boolean loginresult = Logininfo.dologin ();
if (Loginresult) {
Logininfo.savecookie ();
}
}
}else{
if (Logininfo.init ()) {
Another set of systems has been withdrawn.
if ("Out". Equals (Logininfo.getloginstate ()) {
Logininfo.dologout ();
Cookieutil.delcookie (resp, logininfobase.cookie_name);
}
}
}
Chain.dofilter (Sreq, SRESP);
}

public void init (Filterconfig config) throws servletexception {
This.logininfopath = Config.getinitparameter ("Logininfopath");
}

Public String Getlogininfopath () {
return logininfopath;
}

public void Setlogininfopath (String logininfopath) {
This.logininfopath = Logininfopath;
}

}
Logininfopath the full path of the subclass that indicates the logininfobase in Web.xml is used to reflect

Logininfobase Code:
Package com.yt.util;

Import Java.text.SimpleDateFormat;
Import Java.util.Date;

Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Public abstract class Logininfobase {
public static final String separation = "-->";
public static final String date_format = "Yyyy-mm-dd HH:mm:ss";
public static final Long cookie_time = 1800000;
public static final String cookie_name = "Logininfo";
public static final String Cookie_path = "/";

protected HttpServletRequest req;
protected HttpServletResponse resp;

protected Date sessiontime;
protected String userName;
protected String Userpass;
protected String loginstate;

Public Logininfobase () {
Super ();
}

Public Logininfobase (HttpServletRequest req, HttpServletResponse resp) {
Super ();
This.req = req;
This.resp = resp;
}

Public Logininfobase (String userName, string pwd, Date sessiontime) {
This.username = UserName;
This.userpass = pwd;
This.sessiontime = Sessiontime;
}

abstract void Dologout ();
Abstract Boolean issessionempty ();
Abstract Boolean dologin ();

Public HttpServletRequest Getreq () {
return req;
}
public void Setreq (HttpServletRequest req) {
This.req = req;
}
Public HttpServletResponse Getresp () {
Return resp;
}
public void Setresp (HttpServletResponse resp) {
This.resp = resp;
}

Initializing a Login Object
Protected Boolean init () {
String logininfostr = Cookieutil.getvalue (req, logininfobase.cookie_name);
if (logininfostr = null | | "". Equals (Logininfostr)) {
return false;
}
string[] Infoarray = logininfostr.split (separation);
if (infoarray.length>3) {
This.username = Digestutil.getfrombase64 (infoarray[0]);
This.userpass = Digestutil.getfrombase64 (infoarray[1]);
This.sessiontime = Builddate (infoarray[2]);
This.loginstate = infoarray[3];
}
if (new Date (). GetTime ()-Getsessiontime (). GetTime () > Logininfo.cookie_time) {
Cookieutil.delcookie (resp, logininfo.cookie_name);
return false;
}
return true;
}

protected void Savecookie () {
Setsessiontime (New Date ());
Setloginstate ("in");
Cookieutil.addcookie (resp, Logininfo.cookie_name, toString (), "/");
}

public void ClearCookie () {
Setusername ("XX");
Setuserpass ("XX");
Setsessiontime (New Date ());
Setloginstate ("Out");
Cookieutil.addcookie (resp, Logininfo.cookie_name, toString (), "/");
}

@Override
Public String toString () {
Return Digestutil.getbase64 (UserName) +separation+digestutil.getbase64 (Userpass) +separation+formatesessiontime () +separation+loginstate;
}

Private String Formatesessiontime () {
SimpleDateFormat df = new SimpleDateFormat (date_format);
String timestr =df.format (sessiontime);
return timestr;
}
Private Date builddate (String sessiontime) {
SimpleDateFormat df = new SimpleDateFormat (date_format);
Date date = null;
try {
Date = Df.parse (Sessiontime);
}catch (Exception ex) {
System.out.println (Ex.getmessage ());
}
return date;
}

Public Date Getsessiontime () {
return sessiontime;
}

public void Setsessiontime (Date sessiontime) {
This.sessiontime = Sessiontime;
}

Public String GetUserName () {
return userName;
}

public void Setusername (String userName) {
This.username = UserName;
}

Public String Getuserpass () {
return userpass;
}

public void Setuserpass (String userpass) {
This.userpass = Userpass;
}

Public String getloginstate () {
return loginstate;
}

public void Setloginstate (String loginstate) {
This.loginstate = loginstate;
}

}
Dologin (), Dologout (), Issessionempty () must be implemented in subclasses
Log in to the system, log off the system, and determine whether to log in

OK, it's a bit confusing to ask questions.

Someone asked for Util code, no words, stick it out.

Package net.heart.util;

Import java.io.UnsupportedEncodingException;
Import Java.net.URLDecoder;
Import Java.net.URLEncoder;

Import Javax.servlet.http.Cookie;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;

Public abstract class Cookieutil {

public static void Addcookie (HttpServletResponse response,string name,string value,int maxage) {
try {
Cookie Cookie=new Cookie (name,urlencoder.encode (value, "utf-8"));
Cookie.setmaxage (MaxAge);
Response.addcookie (cookie);

catch (Unsupportedencodingexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
}
public static String GetValue (httpservletrequest request,string name) {
String Value=null;
Cookie[] Cookies=request.getcookies ();
if (cookies!=null) {
for (Cookie cookie:cookies) {
if (Name.equals (Cookie.getname ())) {
try {
Value=urldecoder.decode (Cookie.getvalue (), "utf-8");
catch (Unsupportedencodingexception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
Break
}
}
}
return value;
}
public static void Delcookie (HttpServletResponse response,string name) {
Cookie Cookie=new Cookie (name, "");
Cookie.setmaxage (0);
Response.addcookie (cookie);
}
}

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.