Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to solve .NET single sign-on

2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article introduces the relevant knowledge of "how to solve .NET single sign-on". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Here refers to a single point, generally refers to the WEB server, an account can only exist one ticket at a time!

A problem that everyone may encounter in development is how to make the same user only be allowed to log in once at the same time.

Many people will think of using an identification field in the database, log in to set 1, exit to set 0, and judge this field when logging in. If 1 means that the user is online and is not allowed to log in, this scheme seems to be effective, but there are many problems in practical use. For example, users do not exit through the exit button in the program, but directly close IE. The next time the user is still online in the database, the user will not be able to log in. Of course, there are some ways to solve this problem: add a scheduled job and reset those users who have been online for a long time on a regular basis, which will cause some problems. If the user has actually been using it for such a long time, it is manslaughter.

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

First: create a global.asax file, and write the following code in the Session_End event:

The copy code is as follows:

Hashtable h = (Hashtable) Application ["online"]

If (h [Session.SessionID]! = null)

H.Remove (Session.SessionID)

Application ["online"] = h

Second: modify the web.config file and add it to the system.web node

The copy code is as follows:

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

Third: in the login event of the page, determine whether the login user exists in the server global variable. Login is not allowed if it exists, and it is created if it does not exist. The following is the implementation process, which is called in the event of the login button.

The copy code is as follows:

Private void isLogin ()

{

Hashtable h = (Hashtable) Application ["online"]

If (h = = null)

{

H = new Hashtable ()

}

/ / verify whether the user exists in Application (online)

IDictionaryEnumerator E1 = h.GetEnumerator ()

Bool flag = false

While (e1.MoveNext ())

{

If (checkCookie (e1.Value.ToString ()

{

Flag = true

Break

}

}

If (flag)

{

Response.Write ("alert ('This user is onlineages'); history.go (- 1);")

}

Else

{

LoginLogic login = new loginLogic (this.txt_user_id.Text.Trim (), this.txt_password.Text.Trim ())

If (! login.getLoginStatus)

{

Response.Write ("alert ('Invalid UserID or password.Please try again.');")

}

Else

{

/ / generate server identification 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 + identification value to the global variable table

H [Session.SessionID] = this.txt_user_id.Text.Trim () + "-" + cookieValue

Application ["Online"] = h

/ / write the identification value to the client cookie

Response.Cookies ["hqs"] .Value = cookieValue

Response.Cookies ["hqs"] .Expires = DateTime.Now.AddDays (1)

/ / user information is recorded in 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 in VS2005's built-in WEB server may be problematic and is still being tested in IIS's formal environment.

Description about this solution: in general, the timeout time of session is 20 minutes, that is, if the user closes the browser directly and then logs in immediately, the session has not expired at this time, so the session_end event in global.asax will not be triggered, so the user will be prompted to be online. After the event is executed 20 minutes later, the inactive user will be deleted, and login will be normal at this time. So don't think that this plan is invalid just because you can't log in after shutting down IE directly.

Of course, the timeout time of session can be changed, but it can be changed if 20 minutes are not appropriate. The changes are as follows:

-

Now there is a new problem. If the user logs out abnormally, session will not execute the END event within 20 minutes, that is, the user is still online, and the user will not be allowed to log in again. This is obviously a little unreasonable. This plan is not perfect. I hope you can add it.

Add: the code for step 3 has been updated to solve this problem

Second, for some reason, in our application, we will encounter a situation in which a user can only log in in one place, which is what we usually call single sign-on. Implementing single sign-on in ASP.NET is actually very simple, so let's analyze the main methods and all the code.

Realization idea

Using the function of Cache, we save the user's login information in Cache, and set the expiration time to the time when Session expires, so once Session fails, our Cache also expires; and Cache can be accessed by all users, so it is more convenient to use it to save user information than the database.

Program code

The copy code is as follows:

String sKey = username.Text.ToString () .Trim (); / / get the value of the given Key in Cache

String sUser = Convert.ToString (Cache [sKey]); / / check whether it exists

If (sUser = = null | | sUser = = String.Empty)

{

TimeSpan SessTimeOut = new TimeSpan (0,0, System.Web.HttpContext.Current.Session.Timeout, 0,0); / / get the expiration time of Session

HttpContext.Current.Cache.Insert (sKey, sKey, null, DateTime.MaxValue, SessTimeOut, System.Web.Caching.CacheItemPriority.NotRemovable, null); / / put the value into cache to facilitate single sign-on

/ / Log in successfully

}

Else if (Cache [sKey] .ToString () = = sKey) / / if this account is already logged in

{

ClientScript.RegisterStartupScript (GetType (), "prompt", "alert ('sorry, the current user is logged in');"

Return

}

Else

{

Session.Abandon (); / / this paragraph is mainly to avoid unnecessary errors leading to unable to log in.

}

This is the end of "how to solve .NET single sign-on". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report