ASP. NET Single Sign-On (CODE)
For some reason, a single user can only log on to one place in our application, which is also called Single Sign-On. Implementing Single Sign-On in ASP. NET is actually very simple. The main method and all the code are analyzed below.
Implementation
By using the Cache function, we store user login information in the Cache and set the expiration time to the Session expiration time. Therefore, once the Session fails, our Cache also expires; the Cache can be accessed by all users. Therefore, it is easier to use it to save user information than to use the database.
Code
String sKey = username. Text. ToString (). Trim (); // obtain the value of the given Key in the Cache.
String sUser = Convert. ToString (Cache [sKey]); // check for existence
If (sUser = null | sUser = String. Empty)
{
TimeSpan SessTimeOut = new TimeSpan (0, 0, System. Web. HttpContext. Current. Session. Timeout, 0, 0); // get the Session expiration time
HttpContext. current. cache. insert (sKey, sKey, null, DateTime. maxValue, SessTimeOut, System. web. caching. cacheItemPriority. notRemovable, null); // put the value into the cache to facilitate single-point Login
// Login successful
}
Else if (Cache [sKey]. ToString () = sKey) // if this account has been logged on
{
ClientScript. RegisterStartupScript (GetType (), "prompt", "<script> alert ('Sorry, the current user has logged on '); </script> ");
Return;
}
Else
{
Session. Abandon (); // This section is mainly used to prevent unnecessary errors and cause logon failure.
}
Reference to Chapter E of Mencius"