Post) a set of. net form authentication solutions (to prevent repeated user login, sessio

Source: Internet
Author: User
Blog. csdn. netjohnsontjarticles324369.aspx 1. Set web. config options to enable authentication using forms and default logon pages, as shown below. AuthenticationmodeFormsformsloginUrldefault. aspxformsauthentication

Http://blog.csdn.net/johnsontj/articles/324369.aspx 1. Set web. config related options to enable form authentication and default login pages, as shown below. Authenticationmode = "Forms" formsloginUrl = "default. aspx"/forms/authentication

Http://blog.csdn.net/johnsontj/articles/324369.aspx

I.SetWeb. configRelated options

Enable the form authentication and default logon page, as shown in the following figure.

Set the website to be accessible anonymously, as shown below:

Then, set the admin directory under the same directory to reject anonymous login, as shown below. Note that this section is under the System. Web section.

Set the http request and sent encoding to GB2312. Otherwise, the query string may fail, as shown below.

Set the session timeout to 1 minute and enable cookieless, as shown below.

To enable page tracing, we first start the trace of each page for convenient debugging, as shown below.

II.Set the Global. asax File

Process the Application_Start method, instantiate a Hasse table, and save it in the Cache.

Protected void Application_Start (Object sender, EventArgs e)

{

Hashtable h = new Hashtable ();

Context. Cache. Insert ("online", h );

}

Call the LogoutCache () method in the Session_End method. The method source code is as follows:

///

/// Clear the current user in the Cache, which is called mainly in the Session_End method of Global. asax and the method of user logout ///

Public void LogoutCache ()

{

Hashtable h = (Hashtable) Context. Cache ["online"];

If (h! = Null)

{

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

H. Remove (Session. SessionID );

Context. Cache ["online"] = h;

}

}

III.Set related login and logout Codes

Call the PreventRepeatLogin () method before logon. This method prevents repeated login by users. If the last logon times out for more than 1 minute, that is, the page under all admin directories is disabled for more than 60 seconds, it is deemed that the user logging on to the system has timed out, and you can log on to the system. If the time does not exceed 60 seconds, a custom exception will be generated. A Hasse table is saved in Cache ["online"]. The key of the Hasse table is the SessionID of the current login user, and the Value is an ArrayList. This ArrayList has two elements, the first is the user login name. The second element is the user login time. Then, when the page under each admin directory is refreshed, the login time of the Current login user is updated, however, only one page in the admin directory opens. Even if you do not manually send a request to the server, a request is automatically sent to update the logon time, below I have written a function in the base class of the page to do this. In fact, this will increase the burden on the server, but it is also a feasible method under certain circumstances.

///

/// Prevent repeated login by the user before the user wants to authenticate

///

///Username to be verified

Private void PreventRepeatLogin (string name)

{

Hashtable h = (Hashtable) Cache ["online"];

If (h! = Null)

{

IDictionaryEnumerator e1 = h. GetEnumerator ();

Bool flag = false;

While (e1.MoveNext ())

{

If (string) (ArrayList) e1.Value) [0] = name)

{

Flag = true;

Break;

}

}

If (flag)

{

TimeSpan ts = System. DateTime. Now. Subtract (Convert. ToDateTime (ArrayList) e1.Value) [1]);

If (ts. TotalSeconds <60)

Throw new oa. cls. myException ("sorry, the account you entered is in use. If you are the real owner of this account, please change your password in time upon the next login, because your password is very likely to be stolen! ");

Else

H. Remove (e1.Key );

}

}

Else

{

H = new Hashtable ();

}

ArrayList al = new ArrayList ();

Al. Add (name );

Al. Add (System. DateTime. Now );

H [Session. SessionID] = al;

If (Cache ["online"] = null)

{

Context. Cache. Insert ("online", h );

} Else

Cache ["Online"] = h;

}

Call the LogoutCache () method mentioned above when logging out.

4.Set the base class of all pages under the admin directory

Using System;

Using System. Web;

Using System. Web. UI;

Using System. Web. UI. WebControls;

Using System. Web. UI. HtmlControls;

Using System. Collections;

Namespace oa. cls

{

Public class MyBasePage: System. Web. UI. Page

{

///

/// Obtain whether the current page is in a protected directory. The entire program is in the virtual directory of OA, and the protected directory is the admin directory.

///

Protected bool IsAdminDir

{

Get

{

Return Request. FilePath. IndexOf ("/oa/admin") = 0;

}

}

///

/// Prevent session Timeout. If the session times out, the authentication will be canceled and the system prompts and redirects to the website login page.

///

Private void PreventSessionTimeout ()

{

If (! This. IsAdminDir) return;

If (Session ["User_Name"] = null & this. IsAdminDir)

{

System. Web. Security. FormsAuthentication. SignOut ();

This. Alert ("Login timeout", Request. ApplicationPath)

}

}

///

/// Update the logon time option in the Cache every time you refresh this page and call it in the OnInit method below.

///

Private void UpdateCacheTime ()

{

Hashtable h = (Hashtable) Cache ["online"];

If (h! = Null)

{

(ArrayList) h [Session. SessionID]) [1] = DateTime. Now;

}

Cache ["Online"] = h;

}

///

/// Output all the elements of a HashTable in the trace and call the following OnInit method to conveniently observe the cached data

///

///

Private void TraceValues (Hashtable myList)

{

IDictionaryEnumerator myEnumerator = myList. GetEnumerator ();

Int I = 0;

While (myEnumerator. MoveNext ())

{

Context. Trace. Write ("onlineSessionID" + I, myEnumerator. Key. ToString ());

ArrayList al = (ArrayList) myEnumerator. Value;

Context. Trace. Write ("onlineName" + I, al [0]. ToString ());

Context. Trace. Write ("onlineTime" + I, al [1]. ToString ());

TimeSpan ts = System. DateTime. Now. Subtract (Convert. ToDateTime (al [1]. ToString ()));

Context. Trace. Write ("the current time and the number of seconds between this logon time", ts. TotalSeconds. ToString ());

I ++;

}

}

///

/// Pop-up information and return to the specified page

///

///Pop-up message

///Page to be redirected

Protected void Alert (string msg, string url)

{

String scriptString = "script" alert (/"" + msg + "/"); location. href =/"" + url + "/" script ";

If (! This. IsStartupScriptRegistered ("alert "))

This. RegisterStartupScript ("alert", scriptString );

}

///

/// To prevent Session Timeout caused by frequent page refreshing, write a script and send a request to this page every minute to ensure that the session is not timed out, here, we use xmlhttp for refreshing requests.

/// This method is also called in the OnInit method below

///

Protected void XmlReLoad ()

{

System. Text. StringBuilder htmlstr = new System. Text. StringBuilder ();

Htmlstr. Append ("

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.