Single Sign-on

Source: Internet
Author: User
Tags dotnet

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.

View examples

Singlelogin. aspx code

<% @ Page Language = "C #" codebehind = "singlelogin. aspx. cs" autoeventwireup = "false"
Inherits = "emeng. Exam. singlelogin" %>
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> Single Sign-On test </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gb2312">
<Meta http-equiv = "author" content = "Chapter E of Mencius">
<Meta http-equiv = "website" content = "http://dotnet.aspx.cc/">
<Style>
H3 {Font: 17px}
Input {Font: 12px}
SPAN {Font: 12px}
P {Font: 12px}
H4 {Font: 12px}
</Style>
</Head>
<Body ms_positioning = "gridlayout">
<Form ID = "form1" method = "Post" runat = "server">
<Div align = "center">
<H3> Single Sign-On test <P> User name: <asp: textbox id = "username" runat = "server"> </ASP: textbox> </P>
<P> User Password: <asp: textbox id = "password" runat = "server" textmode = "password"> </ASP: textbox> </P>
<P> <asp: button id = "login" runat = "server" text = "login"> </ASP: button> </P>
<P> <asp: Label id = "MSG" runat = "server"> </ASP: Label> </P>
</Div>
</Form>
</Body>
</Html>

Singlelogin. aspx. CS code

Using system;
Using system. collections;
Using system. componentmodel;
Using system. Data;
Using system. drawing;
Using system. Web;
Using system. Web. sessionstate;
Using system. Web. UI;
Using system. Web. UI. webcontrols;
Using system. Web. UI. htmlcontrols;

Namespace emeng. Exam
{
/// <Summary>
/// Summary of singlelogin.
/// Implement Single-point Logon
/// </Summary>
Public class singlelogin: system. Web. UI. Page
{
Protected system. Web. UI. webcontrols. textbox username;
Protected system. Web. UI. webcontrols. textbox password;
Protected system. Web. UI. webcontrols. Label MSG;
Protected system. Web. UI. webcontrols. Button login;

Private void page_load (Object sender, system. eventargs E)
{
// The actual example can be accessed:
// Http://dotnet.aspx.cc/Exam/SingleLogin.aspx
}

# Code generated by region web Form Designer
Override protected void oninit (eventargs E)
{
Initializecomponent ();
Base. oninit (E );
}

/// <Summary>
/// The designer supports the required methods-do not use the code editor to modify
/// Content of this method.
/// </Summary>
Private void initializecomponent ()
{
This. login. Click + = new system. eventhandler (this. login_click );
This. Load + = new system. eventhandler (this. page_load );
}
# Endregion

Private void login_click (Object sender, system. eventargs E)
{
// The key as the unique identifier should be unique, which can be set as needed.
// As a test. Here, the user name and password are combined for identification. No other error checks are performed.

// Generate the key
String skey = username. Text + "_" + password. text;
// 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)
{
// The project where the key is not found in the cache. The table name user is not logged on or has timed out.
// Note that the following method of using the timespan constructor to overload the version is the key to determining whether to log on.
Timespan sesstimeout = new timespan (0, 0, system. Web. httpcontext. Current. session. Timeout, 0, 0 );
Httpcontext. Current. cache. insert (skey, skey, null, datetime. maxvalue, sesstimeout,
System. Web. caching. cacheitempriority. notremovable, null );
Session ["user"] = skey;
// Log on for the first time. You can do what you want.
MSG. Text = "<H4 style = 'color: red'> Hi! Welcome to <a href = 'HTTP: // DOTNET. aspx. CC/'> [wonderful world of the mengxian summit ]";
MSG. Text + = "</a>. Have a good time! :) </H4> ";
}
Else
{
// This user's record is found in the cache. The table name has been logged on and cannot be logged on again.
MSG. Text = "<H4 style = 'color: red'> sorry, you seem to have logged on:-(</H4> ";
Return;
}
}
}
}

**************************************** ***************************

By the way, there are several questions:

1. Windows2003 + IIS6. After configuration, the static page can be accessed now, And the ASPX page cannot be accessed.

This may be caused by the failure to select ASP. NET when IIS6 ("Add/delete Windows Components" --> "server") is installed. Available commands
C: \ windows \ Microsoft. NET \ framework \ v1.1.4322 \ aspnet_regiis.exe-I
. ASP. NET is also allowed on "Web Service extension.

2. Compile the file into a DLL file command.

CSC/Target: Library/out: xjsf. dll c: \ Inetpub \ wwwroot \ xjsf \ loginform. CS

You can also use wildcards to compile multiple files into one DLL file, for example:

CSC/Target: Library/out: xjsf. dll c: \ Inetpub \ wwwroot \ xjsf \ *. CS

Method 2: The system prompts "your account has been logged on elsewhere and is forced to go offline"

Web
The problem frequently encountered in the project is that the same user name is logged on multiple times, and there are many corresponding solutions. To sum up, these solutions: Put the user name after login into the database table; use after login
Put the account name in the session; put the user name after login into the application; put the user name after login into the cache. Generally, after logging in
Frequent logout. The second login will not be allowed. In this case, there will usually be a problem: if the user does not normally exit the system, then he will continue to log on to the system due to issues such as the session has not expired,
Will be denied to continue logging on to the system. You can only log on after the session expires. The method described in this article is similar to the MSN login method. During the second login, the First Login will be canceled.
The next login will be similar to the MSN pop-up message: Your account has been logged in elsewhere, and you are forced to go offline.

Functions are also relatively simple to implement:

Enter the following code after the login user name and password are verified:

Hashtable honline = (hashtable) application ["online"];
If (honline! = NULL)
{
Idictionaryenumerator ide = honline. getenumerator ();
String strkey = "";
While (IDE. movenext ())
{
If (IDE. value! = NULL & ide. value. tostring (). Equals (userid ))
{
// Already Login
Strkey = ide. Key. tostring ();
Honline [strkey] = "xxxxxx ";
Break;
}
}
}
Else
{
Honline = new hashtable ();
}

Honline [session. sessionid] = userid;
Application. Lock ();
Application ["online"] = honline;
Application. Unlock ();

When you log on, place the login user name in a global variable online. Online is in the hashtable structure, key is sessionid, and value is the user name. Each
During the next user login, determine whether the user name to be logged in already exists in online. If the user name already exists, set the user name corresponding to the sessionid logged in by the first user to strong
Change to xxxxxx, indicating that the login will be forcibly canceled.

Create a commonpage. All pages in the system are inherited from the commonpage. Add the following code to the background code of the commonpage:

Override protected void oninit (eventargs E)
{

Hashtable honline = (hashtable) application ["online"];
If (honline! = NULL)
{
Idictionaryenumerator ide = honline. getenumerator ();
While (IDE. movenext ())
{
If (IDE. Key! = NULL & ide. Key. tostring (). Equals (session. sessionid ))
{
// Already Login
If (IDE. value! = NULL & "xxxxxx". Equals (IDE. value. tostring ()))
{
Honline. Remove (session. sessionid );
Application. Lock ();
Application ["online"] = honline;
Application. Unlock ();
MessageBox ("your account has been logged in elsewhere, and you are forced to go offline! ", Login. aspx );
Return false;
}
Break;
}
}
}

}

When refreshing pages that inherit from commonpage, you must execute the code in the overloaded oninit to retrieve online, find the user's sessionid, and determine whether the user name in the sessionid has changed. If yes, then force the server to go offline, clear the session, and go to the login screen.

Finally, you need to release resources when the session expires or the system exits. Add the following code to session_end in the global. asax file:

Hashtable honline = (hashtable) application ["online"];
If (honline [session. sessionid]! = NULL)
{
Honline. Remove (session. sessionid );
Application. Lock ();
Application ["online"] = honline;
Application. Unlock ();
}

If the user does not normally log out and then re-log in, because of the high priority of the re-login, the user login will not be affected, and the resources occupied by the user who does not normally log out will be automatically cleared after the session expires, does not affect the system performance.

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.