. NET Single Sign-On Solution

Source: Internet
Author: User

This refers to the single point. Generally, on the WEB server, an account can only have one ticket at a time!

One problem that everyone may encounter during development is how to allow the same user to log on only once at the same time.

Many people will think of using an identification field in the database, logging in to set 1, logging out to set 0, and determining this field at login. If it is 1, the user is online and cannot log on, this solution seems to be effective, but many problems are found in actual use. For example, the user does not exit through the exit button in the program, but directly closes IE. In this case, the user in the database is still online at the next login, so this user cannot log on. Of course, there are some ways to solve this problem: Add a scheduled job, regular resetting of those online users for a long time will cause some problems. If this user is actually using this long time, it will be mistaken.

Through multiple experiments, we found that. net itself can provide this solution. The procedure is as follows:

1. Create the global. asax file and write the following code in the Session_End event:
Copy codeThe Code is as follows:
Hashtable h = (Hashtable) Application ["online"];
If (h [Session. SessionID]! = Null)
H. Remove (Session. SessionID );
Application ["online"] = h;

2. Modify the web. config file and add it to the system. web node.
Copy codeThe Code is as follows:
<SessionState mode = "InProc"> </sessionState>

This is to use the session_end event in global. asax to take effect.

Third: In logon events on the page, you can determine whether a logon user exists in the global variables of the server. If a logon user exists, you cannot log on. If no logon exists, you can create a logon event. The following is the implementation process called in the logon button event.
Copy codeThe Code is as follows:
Private void isLogin ()
{
Hashtable h = (Hashtable) Application ["online"];

If (h = null)
{
H = new Hashtable ();
}

// Verify whether the user exists in the Application (online or not)
IDictionaryEnumerator e1 = h. GetEnumerator ();
Bool flag = false;
While (e1.MoveNext ())
{
If (checkCookie (e1.Value. ToString ()))
{
Flag = true;
Break;
}
}
If (flag)
{
Response. Write ("<script defer language = 'javascript '> alert ('this user is online! '); History. go (-1); </script> ");
}
Else
{
LoginLogic login = new loginLogic(this.txt _ user_id.Text.Trim (), this.txt _ password. Text. Trim ());

If (! Login. getLoginStatus)
{
Response. Write ("<script defer language = 'javascript '> alert ('invalid UserID or password. Please try again.'); </script> ");
}
Else
{
// Generate the server id value
DateTime now = DateTime. Now;
String cookieValue = now. year. toString () + now. month. toString () + now. day. toString () + now. hour. toString () + now. minute. toString () + now. second. toString () + now. millisecond. toString ();
// Write the userid + id value to the global variable table
H [Session. SessionID] = this.txt _ user_id.Text.Trim () + "-" + cookieValue;
Application ["Online"] = h;
// Write the id value to the client cookie
Response. Cookies ["hqs"]. Value = cookieValue;
Response. Cookies ["hqs"]. Expires = DateTime. Now. AddDays (1 );

// Log user information to the session
Session ["userid"] = this.txt _ user_id.Text.Trim ();
Response. Redirect ("Manage/index. aspx ");
}
}
}

Private bool checkCookie (string appValue)
{
Bool isExist = false;

If (Request. Cookies ["hqs"]! = Null)
{
String cookieValue = Request. Cookies ["hqs"]. Value;

Char [] sp = new char [1] {'-'};
String appUserid = appValue. Split (sp) [0]. ToString ();
String appCookie = appValue. Split (sp) [1]. ToString ();

If (appUserid = this.txt _ user_id.Text.Trim () & appCookie! = CookieValue)
IsExist = true;
}
Return isExist;
}

Note: problems may occur during the test on the built-in WEB server of VS2005, which is still being tested in the official IIS environment.

Description of this solution: Generally, the timeout time of the session is 20 minutes. That is to say, if the user directly closes the browser and logs on again immediately, the session has not expired yet, none will trigger global. the session_end event in asax will prompt that the user is still online. After the event is executed 20 minutes later, the non-active user will be deleted, and then the login will be normal. Therefore, do not think that this solution is ineffective if IE is directly disabled and cannot be accessed again.

Of course, the timeout time of the session can be modified, but it is not suitable for 20 minutes. The modification method is as follows:

<SessionState mode = "InProc" timeout = "value you think is appropriate"> </sessionState>

------------------------

In the previous article, there are new problems. If the user unexpectedly exits, the session will not execute the END event within 20 minutes, that is, the user is still online, this user will not be allowed to log on again. This is obviously a bit unreasonable. This solution is not perfect. I hope you can add it.

Supplement: the code in step 3 has been updated to solve this problem.

2. For some reason, a single user can only log on to one location in our application, which is also called single-point logon. 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.

Program code
Copy codeThe Code is as follows:
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.
}

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.