. NET Single Sign-on Solution _ Practical Tips

Source: Internet
Author: User
Tags httpcontext
Here refers to the single point, generally refers to the Web server, an account at the same time can only exist a ticket!

You may have encountered a problem in development, how to make the same user, at the same time only allowed to log in once.

A lot of people would think of using an identity field in a database, log in to set 1, exit 0, log in to judge this field, if it is 1 to explain this user online, not allowed to login, this scheme seems to be effective, but in actual use found a lot of problems, for example, the user is not through the program in the Exit button exit, Instead of directly shutting down IE, the next time you log in to the user in the database online, the user will not be able to log in, of course, there are some ways to solve this problem: Add a timed job, regularly reset those users for a long time on-line, which will cause some problems, If this user is actually using it for so long, it is manslaughter.

through many experiments, it is found that. NET itself can provide this solution. The steps are as follows:

First: Create the Global.asax file, write the following code in the Session_End event:
Copy Code code as follows:

Hashtable h = (Hashtable) application["Online"];
if (H[session.sessionid]!= null)
H.remove (Session.SessionID);
application["Online"] = h;

Second: Modify Web.config file, add in system.web node
Copy Code code as follows:

<sessionstate mode= "InProc" ></sessionState>

This is to use the Session_End event in Global.asax to take effect.

Third: The page login event, to determine whether the logged-in user in the server-side global variables exist, there is not allowed to log on, do not exist to create. Here is the implementation process, which is invoked in the event of the login button.
Copy Code code as follows:

private void IsLogin ()
{
Hashtable h = (Hashtable) application["Online"];

if (h = null)
{
h = new Hashtable ();
}

Verify that the user exists in the application (online)
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
{
Generating server-side identity values
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 + identity value to the global variable table
H[session.sessionid] = this.txt_user_id. Text.trim () + "-" + cookievalue;
application["Online"] = h;
Write identity value to client cookie
response.cookies["HQs"]. Value =cookievalue;
response.cookies["HQs"]. Expires = DateTime.Now.AddDays (1);

User information is entered into 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: Testing may be problematic in VS2005 's built-in Web server, and is still being tested in the formal environment of IIS.

Description of this scenario: In general, the session timeout time is 20 minutes, that is, if the user directly shut down the browser, and then login again, this time session has not expired, all will not trigger the Global.asax in the Session_ End event, the user is prompted to be online, after 20 minutes after the event is executed, the inactive user will be deleted, and then log on normally. So do not think that the direct switch off ie, and then login can not go, that the scheme is invalid.

Of course, the session timeout time can be modified, 20 minutes is not suitable to change. The change is as follows:

<sessionstate mode= "InProc" timeout= "What do you think is the right value" ></sessionState>

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

On the last article, there are new problems, if the user is not a normal exit then, the session in 20 minutes will not execute the end event, which means that the user is still online status, then this user login will not be allowed. This is obviously a bit unreasonable. This plan is not perfect enough, I hope you can add.

add: The third step of the code has been updated to solve this problem

Second, for some reason, in our application will encounter a user can only be logged in one place, that is, we usually call the single sign-on. In the asp.net to achieve a single sign-on is very simple, the following is the main method and all the code analysis.

Realize the idea

Using the cache function, we put the user's login information in the cache, and set the expiration time for the session expiration time, so, once the session is invalid, our cache also expired, and cache for all users can access, therefore, It is easier to save user information with it than the database.

Program code
Copy Code code as follows:

String SKey = Username. Text.tostring (). Trim (); Gets the value of the given key in the Cache
string suser = Convert.ToString (Cache[skey]);/check for existence
if (suser = = NULL | | suser = = Stri Ng. Empty)
{

TimeSpan sesstimeout = new TimeSpan (0, 0, System.Web.HttpContext.Current.Session.Timeout, 0, 0) //Gets the expiration time of the session
HttpContext.Current.Cache.Insert (SKey, SKey, NULL, DateTime.MaxValue, Sesstimeout, System.Web.Caching.CacheItemPriority.NotRemovable, NULL);//Put the value into the Cache's own single sign-on
//login successfully
}
else if (cache[skey ]. ToString () = = SKey)//If this account is already logged in
{
Clientscript.registerstartupscript (GetType (), "Prompt", "<script>alert" (' Sorry, the current user has logged in ');</script> ');
return;
}
Else
{
Session.Abandon ()//This paragraph is primarily to avoid unnecessary errors that can cause you to not log on

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.