Enterprise security system for single sign-on web applications

xiaoxiao2021-03-06  57

Enterprise security system for single sign-on web applications

Release Date: 8/17/2004

| Update Date: 8/17/2004

Paul D. Sheriffpdsa, Inc.

Applicable range: Microsoft® ASP.NET

Summary: Disclose technology that can log in to multiple web applications in a single login. This article also provides an example code that has a good start to create a strong enterprise security system in the case of single sign-on.

Download The Code Samples for this Article.

This page

Introduction Single Login Solution Overview Class and Page Table APPLAUNCHER Web Applications Apps Class In Web Application Retrieved Token Enhances Your Single Login System Installation Example Conclusion Reference

introduction

If your company is the same as with most of the most of the company, you may have many web applications for supporting company services. Most of these types of applications need to take safety measures, because you don't want users to enter any web applications as they want. For example, only certain users are allowed to enter the execution summary decision support system, while other users should only allow access to customer information systems. There may be some external users who use these systems, they are not your Microsoft® Windows® domain users. This can be enforced through the security mechanism to control each user login system. But the problem does this is that when accessing different systems, each system will continue to log in. For companies with only five web applications, if a user is allowed to access each program, the user is bored because of frequent login and logout. So you must find a better way.

After reading this article, you will learn about a method of applying a single login solution in an enterprise. The company's internal users can use Windows authentication to access applications, while external users will be enforced (see Figure 1).

The subject discussed in this article

Single login web application

• Generate a single login token • Map users to applications • Form-based authentication • Integrated authentication in Windows

Back to top

Single login solution overview

Figure 1 shows a series of steps performed when the internal user and the external user are logged in to a website located on a company's intranet. At a level of 50,000 feet, this system has only four components: a website that authenticates a website, Active Directory, a database server, and one or more forms that identify form-based forms.

Figure 1: Example of a single sign-on solution covering internal users and external users

Intranet solution

In the upper left corner of Figure 1, you can see that internal users browse to specific websites using the browser (step 1). This website is verified (step 2) The user's Windows credentials (via Active Directory). If the user is a valid Windows user, it allows it to enter the site. After authentication, the user's identity will be retrieved and the database table containing the specified application list (step 3) containing the specified user can run. These applications will be displayed in DataGrid for users to choose.

When the user clicks the application you want to run, it will generate a unique, which can only use the token (step 4). This token and user ID will be stored in another database table. Then this token is passed to a specific page in a web application to run (by querying line). This special page reads the token from the query row, then verify that this token is existed in the database table (step 5). If the token exists, it retrieves the login ID in the database and then deletes the record of the storage of this token. This action prevents others from using this token again and sends the login ID back to the web application. After you understand the user ID in the web application, you need to generate an ASP.NET Form authentication bill, because in the intranet, all web applications will use the form-based authentication. This bill will be used by users of all security pages in the site.

EXTRANET solution

Want to access an external user of the web application (user outside of your domain) will be directed to the starting page different from the internal users (see Figure 2). The internal user and external users are oriented to the web application takes a form based on the form of authentication. When the external user attempts to open any of this web application, they will be automatically redirected to the login page. This login page is different from the page that authenticates the internal user. Users must enter their credentials, and then the system will call the same database to determine if the user is valid. If it is valid, a normal form-based authentication cookie will be generated for this user session.

Back to top

Class and page

You need to create several classes and web pages to support enterprise-class security systems. Figure 2 shows each class and web page that needs to be written for this system. This article will discuss each class displayed in this figure. After this picture, the description information of each class and the main features of the web page in your system are listed.

Figure 2: Designing and developing a single login solution requires only a few classes and pages

APPS class

Such a list for retrieving a specified user's application. It will also generate a new token, retrieve the user's identification information and delete the token according to a given token.

Table 1: Method Name of Apps Class Description GetAppSbyLoginId looks for the application associated with this user based on a domain's domain's domain, and returns the application's DataSet. CreateLogintoken creates and returns a new login token. GenerateToken generates a new token method. In this release, a simple GUID will use a token. VerifyLogintoken is based on a given token, this method will verify that there is this token in the database. It will create an instance of the AppToken class, return it after writing the appropriate information. DeleToken deletes the token in the table.

AppToken class

This class contains four attributes required to return to token information from the VerifyLogintoken method of the Apps class. Table 2 illustrates the four attributes included in this class.

Table 2: Attribute Properties of the AppToken class Description Loginid string, its value represents the user's login ID. Appname string, its value represents the application name associated with this AppToken record. Loginkey integer type, its value represents the primary key of the user in the ESUSERS table. AppKey integer type, its value represents the primary key of the application in the ESAPPS table.

AppUserRoles class

Such information for retrieving users attempting to log in to the application. One of the methods checks if the login is valid based on a given login ID and the application key value. Another method returns a given user's role set. There is also a method returns the primary key of the ESUSER table based on the login ID and the application key value.

Default.aspx in Applauncher app

This web page will retrieve Windows users passing the IIS authentication and returns a list of applications that allow these users to access. It will display this list (Figure 3) in the DataGrid and allow the user to click on specific applications. After the user clicks the application, this page will generate a new token and store this token and user ID to the EsAppToken table, and then call this application to pass the token to the AppLogin.aspx page in the web application. Figure 3: Application launcher displays a list of applications that allow log in to run

AppLogin.aspx in each website

You can only call this web page from the application starter. If any other application is trying to call this page, it redirects the user to the website's default.aspx page. Because each web application uses a form-based authentication, this action will force ASP.NET to redirect the user to the Login.aspx page in the site.

If this page is called from the application starter site, this page will call the method in the Apps class to verify that this token is valid. If the token is valid, the Apps class will return an AppToken object so that this page can create a form-based authenticated user using information in this object.

Login.aspx in each website

This is a regular web login page that requires the user to enter credentials and check these credentials in the database to ensure that it is a valid user; in addition, if it is a valid user, it will also create an authentication ticket and enter the site, Redirect to the user requesting page.

Default.aspx in each website

This is the main landing page for each website. Only users passing the authentication of the AppLogin or Login web page can also browse this page and all other pages in the site.

Back to top

table

You also need to create several tables in the database to support this single login enterprise security system. There are not many fields included in the tables in this article, but it is sufficient to say the content. Figure 4 shows the relationship between each table that needs to be created in the database. After Figure 4, the list of these tables, and the description of each table used in this solution.

Figure 4: Several tables required to realize the complete role of a single login system

ESAPPS

This table contains a list of all web applications in the enterprise. In addition to the name of the application, the table also contains detailed description information of the application and the URL of the application. The URL is a full-form URL and should end at the end of the AppLogin.aspx page. The Default.aspx page in the application launcher will be responsible for adding strings "token = " to the URL forward to the URL before redirect to the web application.

Figure 5: Example data for the ESAPPS table

ESUSERS

This table lists all users who can use applications. You need to copy your user domain login ID for all internal users. You may also want to add a password field for external users.

Figure 6: Example data for the ESUSERS table

ESAPPSUSERS

This table associates users in the ESUSERS table to the applications they can run in the ESAPPS table. The data in the table is only the foreign key of the ESUSERS table and the ESAPPS table.

EsApproles

This table contains the role set of each application. For example, an application may contain "Admin" and "User" roles, while other applications may contain "User" and "Supervisor" rules.

Figure 7: Example data for the esapproles table

Esappusersroles

This table contains a list of each role of each user in the application. In the application "HR", the user "Joe" may be "supervisor", but in the application "Payroll", it may be "admin" and "user". EsappToken

ESAPPToken contains tokens generated by the login portal application and passed to a single web application. These records should only have two seconds (or shorter time) in general, because the web application being called will immediately delete this token after collecting information from this table. This prevents others from using this token again.

Figure 8: Example data for the esappletoken table

Back to top

Applauncher web application

Application launcher solution (Figure 9) consists of a site and class library project authenticated through Windows. This station passing through the Windows authentication will directly read the user domain ID in the thread, and use this user domain ID to find the user in the user table. Let's take a look at the web page of the application that the user can run.

Figure 9: ApplaunCherxx solution contains ApplaunCherxx projects and references to ApplauncherDataxx projects

Default.aspx in ApplaunCherxx

Application launcher is only a web page: ie default.aspx. This web page reads the user's Windows login ID from the User object of the page and loads a list of applications defined in the database. The following is the code for the Page_Load event process that is called when loading the Default.aspx page.

// C #

Private Void Page_Load (Object Sender, System.EventArgs E)

{

/ / Display user name

// without domain prefix

LBLLogin.Text = "Applications Available for:"

Apps.loginidNodomain (user.Identity.name);

APPLOAD ();

}

'VB.NET

Private sub page_load (byval sender as system.Object, _

BYVAL E as system.eventargs) Handles mybase.load

'Show user name

'Without domain prefix

LBLLogin.Text = "Applications Available for:" & _

Apps.loginidnodomain (user.Identity.name)

AppLoad ()

End Sub

The static method of calling the Apps class LoginidNodomain is to remove the domain prefix. If the login ID is "Ken" user passed the authentication name "PDSA" authentication, the user.Identity.name property will return "PDSA / KEN". And this method only returns a string "ken".

Loading this user can run an application

The AppLoad method retrieves the DataSet of the application that allows this user to run using an instance of the Apps class. The contents later in this article will display the getAppSbyLoginid method in the Apps class.

// C #

Private void copload ()

{

Apps app = new apps ();

Try

{

/ / Load the application for this user

Grdapps.datasource =

App.getAppsbyLoginid (user.Identity.name);

Grdapps.databind ();

}

Catch (Exception EX)

{

LBlMessage.Text = ex.Message;

}

}

'VB.NET

Private Sub Appload () DIM App As New Apps

Try

'Loading applications for this user

Grdapps.datasource = app.getAppsbyLoginid (user.Identity.name)

Grdapps.databind ()

Catch exception

LBlMessage.Text = ex.Message

END TRY

End Sub

LinkButton control

The DataGrid control of the default.aspx page displays the specified user's application list (see Figure 3), the user can select the application. DataGrid is used to display a hyperlink for users to click on the control. In the web page, LinkButton is defined as follows:

AppId = '<% # databinder.eval (container.DataItem, "IAPPID")%>'

Userid = '<% # databinder.eval (Container.DataItem, "iUserid")%>'

Commandargument = '<% # databinder.eval (container.DataItem, "surl")%>'

Text = '<% # databinder.eval (container.DataItem, "Sappname")%>>>

As can be seen from the above code, add some additional properties of the primary key (IUSERID) of the primary key (IUSERID) of the ESAPPS table. These attributes and the URL in Commandargument provides sufficient user information that can be stored in the database. You will see later, we will retrieve these additional properties during the ItemMand event.

Tip: You can add any desired properties to the server control. ASP.NET will ignore these properties, but you can retrieve their values ​​using the Attributes property of the server control.

ItemCommand event

Users will call the itemCommand event procedure after clicking the LinkButton control in the DataGrid. In this method, you need to create a new instance of the Apps class, and retrieve the LinkButton control to get the properties, then call the CreateLogintoken method in the Apps class to store this data into the ESAppToken table in the database. Finally, after the token is retrieved, this token will connect to the URL in the Commandargument property in LinkButton and then call Response.Redirect to call the web application passed by the token.

// C #

Private Void GrdApps_ItemCommand (Object Source,

System.Web.ui.WebControls.DataGridCommandEventArgs E)

{

Apps app = new apps ();

Bool redirect = false;

String token = string.empty;

LinkButton LB;

Try

{

lb = (linkbutton) E.Item.cells [0] .controls [1]; // Create a token for this user or application

Token = app.createlogintoken

lb.text,

User.Identity.name,

Convert.TOINT32 (lb.attributes ["userid"]),

Convert.TOINT32 (LB.Attributes ["AppID"]);

REDIRECT = True;

}

Catch (Exception EX)

{

Redirect = false;

LBlMessage.Text = ex.Message;

}

IF (redirect)

{

/ / Redirect to the generated token

// Transfer web application

Response.Redirect (E.commandargument.toString ()

"? Token =" token, false);

}

}

'VB.NET

Private sub grdapps_itemcommand (Byval Source As Object, _

Byval e as system.Web.ui.WebControls.DataGridCommandEventArgs_

Handles Grdapps.ItemMand

DIM App as new apps

Dim Boolredirect as Boolean

Dim token as string

DIM LB AS LINKBUTTON

Try

LB = Directcast (E.Item.cells (0) .controls (1), LinkButton

'Create a token for this user or app

Token = app.createlogintoken (lb.text, _

User.Identity.name, _

Convert.TOINT32 (LB.Attributes ("UserID"), _

Convert.TOINT32 (lb.attributes ("appid")))))))))))

BoolRedirect = TRUE

Catch exception

BoolRedirect = false

LBlMessage.Text = ex.Message

END TRY

IF BoolRedirect Then

'Redirect to the generated token

'Passive web application

Response.Redirect (E.commandargument.toString () &_

"? Token =" & token, false)

END IF

End Sub

You will notice that in the code above, the LinkButton control in the E.Item parameter is retrieved. E.Item is used to reference your rows you click in DataGrid. You can retrieve a specific instance of the cached LinkButton control after the column where LinkButton is located. In this example, it is in Cells (0). In this cell, the control can be obtained after Controls (1). The control is located in position 1 (1) is used in DataGrid, allowing us to place LinkButton ItemTemplate in a cell is considered to be element zero (0).

Once you have retrieved LinkButton, you can use the Attributes property to retrieve the userID and appid stored when setting LinkButton. Attributes property is a collection of all additional properties you add to the server control, which is not an integral part of the initial control definition.

Modify Web.config Before the web application authenticates the user authentication, you must set elements in the web.config file to "Windows". In addition, you must also reject anonymous users in element in Web.config.

Setting these two elements can retrieve user Windows credentials from the browser to force the server. Of course, it will only work if you use Internet Explorer when you log in in the user.

The last job to be completed is to store the connection string to get from the table of the database. In the examples of this article, I only use the part of Web.config stores the connection string.

Value = "server = (local); database = esecurity; uid = myuserid; pwd = mypassword" />

In this article, I created a database called ESECURITM in SQL ServerTM and created all the tables described in the previous contents described above. The sample code of this article contains a SQL script that can run this script to create a table in the SQL Server database. If you use another database system, you need to make appropriate modifications to your script according to your database.

Back to top

APPS class

Now look at the Apps class that implements the main function in this enterprise security system. Each class in the three classes containing the ApplauncherData program set can be responsible for loading applications, load user roles, and operating security tokens. A preferred practice is to reserve the functions of interacting with the database, as well as the function of operating the token outside the user interface. This allows you to modify the user interface to modify the creation method of the token, and modify how to interact with the database.

The Apps class is responsible for the token and loads the application for the user. Let's take a look at the definition of this class.

// C #

Public Class Apps

{

String mconnectstring;

Public apps ()

{

MConnectString = ConfigurationSettings.

Appsettings ["ESECURITYCONNECTSTRING"];

}

...

}

'VB.NET

Public Class Apps

Private MConnectString As String

Public Sub New ()

MConnectString = ConfigurationSettings. _

Appsettings ("ESECURITYCONNECTSTRING")

End Sub

...

END CLASS

You can see that this class first loads the member variable using the connection string from the web.config file.

GetAppsbyLoginid method

To load an application for a particular user, the user's login ID should be passed to the getAppsbyLoginid method. This method is responsible for performing join to retrieve all relevant information. Use SQL coupled to get information from the ESAPPS and ESAPPSUSERS tables. In addition, you also need to join the ESUSERS table, because only the specific user's application needs to be retrieved, and all the information we can use only the user's login ID, so you must find the user's primary key in the ESUSERS table to join other tables. Note: This article uses dynamic SQL just to display the concept. In actual enterprise security systems, you need to use stored procedures for all SQL calls.

// C #

Public DataSet GetAppsbyLoginid (String Loginid)

{

DataSet DS = New Dataset ();

SQLCommand CMD;

SqlDataAdapter Da;

String SQL;

SQL = "Select esapps.iappid, esappsusers.iuserid,";

SQL = "esapps.sappname, esapps.sdesc, esapps.surl";

SQL = "from esaps";

SQL = "Inner Join EsAppsusers";

SQL = "on esapps.iappid = esappsusers.iappid";

SQL = "Inner Join Esusers";

SQL = "on esappsusers.iuserid = esusers.iuserid";

SQL = "Where sloginid = @Sloginid";

SQL = String.Format (SQL, Apps.LoginidNodomain);

Try

{

CMD = New SQLCOMMAND (SQL);

cmd.Parameters.Add (New

Sqlparameter ("@ sloginid", sqldbtype.char);

cmd.parameters ["@ sloginid"]. value =

Apps.loginidNodomain (Loginid);

cmd.connection = new SqlConnection (MCONNECTSTRING);

Da = New SqldataAdapter (CMD);

Da.fill (DS);

Return DS;

}

Catch (Exception EX)

{

Throw EX;

}

}

'VB.NET

Public Function GetAppsbyLoginid (Byval Loginid AS String)

AS Dataset

DIM DS AS New DataSet

DIM CMD As Sqlcommand

DIM DA As SqldataAdapter

DIM SQL AS STRING

SQL = "Select esapps.iappid, esappsusers.iUserid,"

SQL & = "esapps.sappname, esapps.sdesc, esapps.surl"

SQL & = "from esaps"

SQL & = "Inner Join Esappsusers" SQL & = "on esapps.iappid = esappsusers.iappid"

SQL & = "Inner Join Esusers"

SQL & = "on esappsusers.iuserid = esusers.iUserid"

SQL & = "Where sloginid = @Sloginid"

SQL = String.Format (SQL, Apps.LoginidNodomain (LoginiD))

Try

CMD = New SQLCOMMAND (SQL)

cmd.parameters.add (new _

Sqlparameter ("@ sloginid", sqldbtype.char))

cmd.parameters ("@ sloginid"). Value = _

Apps.loginidNodomain (Loginid)

cmd.connection = new sqlconnection (mconnectString)

Da = New SqldataAdapter (cmd)

Da.fill (DS)

Return DS

Catch exception

Throw EX

END TRY

END FUNCTION

Createlogintoken method

When the user clicks after the application in the DataGrid, you must generate a new token. The Createlogintoken method is responsible for performing this task.

// C #

Public String Createlogintoken (String Appname,

String loginid, int userid, int AppID)

{

SQLCommand cmd = new sqlcommand ();

Sqlparameter param;

String token;

String SQL;

/ / Generate a new token

Token = generateToken ();

SQL = "INSERT INTO EsappToken (stokeen, sappname,";

SQL = "Sloginid, iUserid, IAPPID, DTCREATED";

SQL = "VALUES (@stoken, @sappname, @sloginid,";

SQL = "@iUserid, @iappid, @dtcreated)";

Param = New Sqlparameter ("@ stokeen", sqldbtype.char);

Param.value = token;

cmd.Parameters.Add (param);

Param = New Sqlparameter ("@ sappname", sqldbtype.char);

Param.Value = appname;

cmd.Parameters.Add (param);

Param = New Sqlparameter ("@ sloginid", sqldbtype.char);

Param.Value = apps.loginidnodomain (loginid);

cmd.Parameters.Add (param);

Param = New Sqlparameter ("@ iuserid", sqldbtype.int); param.value = userid;

cmd.Parameters.Add (param);

Param = New Sqlparameter ("@ @ @ ketpid", sqldbtype.int);

PARAM.VALUE = AppID;

cmd.Parameters.Add (param);

Param = New Sqlparameter ("@ dtcreated", sqldbtype.datetime);

Param.Value = datetime.now;

cmd.Parameters.Add (param);

Try

{

cmd.commandtype = commandtype.text;

cmd.comMandText = SQL;

cmd.connection = new SqlConnection (MCONNECTSTRING);

cmd.connection.open ();

cmd.executenonquery ();

}

Catch (Exception EX)

{

Throw EX;

}

Finally

{

IF (cmd.connection.state! = connectionState.closed)

{

cmd.connection.close ();

cmd.connection.dispose ();

}

}

Return token;

}

'VB.NET

Public Function Createlogintoken (Byval AppName As String, _

Byval loginid as string, byval userid as integer, _

BYVAL APPID AS INTEGER AS STRING

DIM CMD AS New Sqlcommand

Dim Param as Sqlparameter

Dim token as string

DIM SQL AS STRING

'Generate a new token

Token = generateToken ()

SQL = "INSERT INTO ESAPPTOKEN (stokeen, sappname,"

SQL & = "Sloginid, iUserid, IAPPID, DTCREATED"

SQL & = "VALUES (@stoken, @sappname, @sloginid,"

SQL & = "@iUserid, @iappid, @dtcreated)"

SQL = String.Format (SQL, Token, Appname, _

Apps.loginidNodomain (Loginid), UserId, AppID, _

DateTime.now.toString ())

Param = new sqlparameter ("@ stokeen", sqldbtype.char)

Param.Value = token

cmd.Parameters.Add (param)

PARAM = New Sqlparameter ("@ sappname", sqldbtype.char)

Param.Value = Appname

cmd.Parameters.Add (param)

Param = New Sqlparameter ("@ sloginid", sqldbtype.char) param.value = apps.loginidnodomain (loginid)

cmd.Parameters.Add (param)

Param = New Sqlparameter ("@ iuserid", sqldbtype.int)

Param.Value = UserID

cmd.Parameters.Add (param)

Param = New Sqlparameter ("@ ildpid", sqldbtype.int)

Param.Value = appid

cmd.Parameters.Add (param)

Param = New Sqlparameter ("@ dtcreated", sqldbtype.datetime)

Param.Value = datetime.now

cmd.Parameters.Add (param)

Try

cmd.comMandType = CommandType.Text

cmd.comMandText = SQL

cmd.connection = new sqlconnection (mconnectString)

cmd.connection.open ()

cmd.executenonquery ()

Catch exception

Throw EX

Finally

IF cmd.connection.state <> connectionState.closed then

cmd.connection.close ()

cmd.connection.dispose ()

END IF

END TRY

Return token

END FUNCTION

To create a token, you should call the GenerateToken method. This method is why this method is independent of the Createlogintoken method is that it allows you to change the type of token to generate later. At the end of this article, the idea was put forward. This method uses the GUID class to generate a new GUID as a token.

// C #

Public String generateToken ()

{

Return system.guid.newguid (). TOSTRING ();

}

'VB.NET

Public function generateToken () AS String

Return system.guid.newguid (). TSTRING ()

END FUNCTION

Back to top

Search in the web application

To test the application from the application launcher, you should create a web application that can be tested from the initiator (see Figure 10). This web application used to test will use the ApplauncherDataxx project discussed earlier.

Figure 10: Each web application will use the ApplauncherDataxx item combined with AppLogin, Login and Default pages.

Modify Web.config

To create a web application integrating a single login system, you first need to modify the web.config file, and create the section to store the connection string to interact with the Esecurity database. It also needs to store the application ID and application name to use when external users are entered. Because the external user enters, the token has not yet created, there is a need to know the application selected by the user so that the AppToken object to be used is loaded when the user role is established. In the following content, you will learn how to do this.

Value = "Server = (local); Database =

Esecurity; uid = murse; pwd = mypassword ">

You also need to set up a web application to use a form-based authentication. To do this, modify the element as shown below.

Finally, in order to reject anonymous users, you need to modify the element.

AppLogin.aspx page

Keep in mind that each application called from the application launcher calls the AppLogin page and passes the generated token to this page. The AppLogin page verifies that this token is correct, retrieved from the ESAppToken table, and then deletes the record in EsAppToken so that the token is not reused.

// C #

Private Void Page_Load (Object Sender, System.EventArgs E)

{

VerifyToken ();

}

Private void verifytoken ()

{

Apps app = new apps ();

AppToken Al;

Try

{

Al = app.VerifyLogintoken

Request.QueryString ["token"]. TOSTRING ());

IF (al.loginid.trim () == "")

{

// Non-effective login

/ / Redirect it to the default page

// This will turn the user to the login page

Response.Redirect ("Default.aspx");

}

Else

{

// Create Form Authentication Cookie

// Set the form authentication variable

FormsAuthentication.initialize ();

Formsauthentication.setAuthCookie (

Al.Loginid.toString (), false); // Set the application token object

Application ["AppToken"] = Al;

/ / Redirect to the default page

Response.Redirect ("Default.aspx");

}

}

Catch

{

// Redirect the user to the login page via the default page

Response.Redirect ("Default.aspx");

}

}

'VB.NET

Private Sub Page_Load (Byvale AS System.Object, Byval E AS System.Eventargs) Handles MyBase.Load

VerifyToken ()

End Sub

Private sub verifytoken ()

DIM App as new apps

Dim Al As AppToken

Try

Al = app.VerifyLogintoken (_

Request.QueryString ("token"). Tostring ())

If al.loginid.trim () = "" THEN

'Non-effective login

'Redirect it to the default page

'This will turn your user to your login page

Response.Redirect ("default.aspx")

Else

'Creating a Form authentication cookie

'Setting the form authentication variable

FormsAuthentication.initialize ()

Formsauthentication.setAuthCookie (_

Al.loginid.toString (), false

'Setting the application token object

Application ("AppToken") = al

'Redirect to the default page

Response.Redirect ("default.aspx")

END IF

Catch

'Redirect the user to the login page by the default page

Response.Redirect ("default.aspx")

END TRY

End Sub

In the VerifyLogin method, first check if the token is valid. This operation is done by calling the VerifyLogintoken method in the Apps class. This method returns an instance of the AppToken class. If this type of LoginID attributes exists, it indicates that this user is a valid user. If there is no value, the token is invalid. In the case where the token is invalid, this method redirects the user to the Default.aspx page in the website. Of course, if the form-based authentication is turned on, the user will be forced to redirect to the Login.aspx page, and the request is re-logged in.

Call the FormSauthentication.initialize and the FormSauthentication.SetAuthCookie method to send the window to the outside. This will send cookies in memory to the browser. When the user returns this site, the ASP.NET runtime checks this cookie.

VerifyLogintoken method

This method accepts the generated token by queries the line and checks it to ensure that the token is valid. This method will go to the ESAPTOKEN table to check this token. If you find this token in the table, place all the values ​​in the table in the respective properties of the AppToken object, and then return the AppToken object from this method.

// C #

Public AppToken VerifyLogintoken (String token)

{

AppToken Al = New AppToken ();

DataSet DS = New Dataset (); SQLCOMMAND CMD;

DataRow DR;

SqlDataAdapter Da;

String SQL;

SQL = "SELECT IAPTOKENID, SAPPNAME, SLOGINID,";

SQL = "IAPPID, IUSERID";

SQL = "from esapptoken";

SQL = "Where stoken = @stokeen";

Try

{

CMD = New SQLCOMMAND (SQL);

cmd.Parameters.Add (New

Sqlparameter ("@ stokeen", sqldbtype.char);

CMD.Parameters ["@ stoken"]. value = token;

cmd.connection = new SqlConnection (MCONNECTSTRING);

Da = New SqldataAdapter (CMD);

Da.fill (DS);

IF (DS.TABLES [0] .Rows.count> 0)

{

DR = DS.TABLES [0]. ROWS [0];

Al.loginid = DR ["sloginid"]. TOSTRING ();

Al.Appname = DR ["sappname"]. TOSTRING ();

Al.appkey = convert.toint32 (DR ["iappid"]);

Al.Loginkey = Convert.Toint32 (DR ["iuserid"]);

DeleteToken (Convert.Toint32 (DR ["Iapptokenid"]));

}

}

Catch (Exception EX)

{

Throw EX;

}

Return Al;

}

'VB.NET

Public Function VerifyLogintoken (Byval Token As String) AS AppToken

DIM Al As New AppToken

DIM DS AS New DataSet

DIM CMD As Sqlcommand

DIM DR AS DATAROW

DIM DA As SqldataAdapter

DIM SQL AS STRING

SQL = "SELECT IAPPTOKENID, SAPPNAME, SLOGINID,"

SQL & = "IAPPID, IUSERID"

SQL & = "from esappletoken"

SQL & = "Where stokeen = @stokeen"

Try

CMD = New SQLCOMMAND (SQL)

cmd.parameters.add (new _

Sqlparameter ("@ stokeen", sqldbtype.char))

Cmd.Parameters ("@ stokeen"). Value = token

cmd.connection = new sqlconnection (mconnectString)

Da = New SqldataAdapter (cmd)

Da.fill (DS)

IF ds.tables (0) .Rows.count> 0 THEN

DR = ds.tables (0) .ROWS (0) al.loginid = DR ("sloginid"). Tostring ()

Al.Appname = DR ("sappname"). Tostring ()

Al.appKey = Convert.Toint32 (DR ("IAPPID")))

Al.Loginkey = Convert.Toint32 (DR ("iUserid"))

DeleteToken (Convert.Toint32 (DR ("IappTokenID")))))))

END IF

Catch exception

Throw EX

END TRY

Return Al

END FUNCTION

Role-based security

After the user passes the Web application, it will be redirected to the Default.aspx page. Because I have sent authentication cookies to the browser, this cookie will be sent back each time. The Application_AuthenticateRequest method in the global.asax file is called before transmitting the requested page to the user. Only any role to be associated with this user can only be established in this method. I am not intended to show this method here, because there is a special article discuss it. You can view an example of using this method in the sample code. The code based on role is very simple. You can improve this code to make it cache. Its purpose just tells you how to do it.

Back to top

Enhance your single login system

This article describes a lot of content in creating an enterprise-level security system. However, if you want to introduce all aspects of the enterprise-level security system, the scope of this article is exceeded. For example, you should also add a range of maintenance screens to allow administrators to add users and build mappings between users and applications. It also needs to take safety measures to this set of screens so that users only in a particular role can open them.

Another place where the system needs to be enhanced is automatically added to the domain users in the system. It helps you add users to your system without having to manually enter user information, or you can also write an application to add users. You usually specify these users as the default role so that they only allow them to run some applications instead of all applications. In addition, if new users have been added in this way, the administrator should also receive notification information in the form of email.

Because this safety system relies on the generated specific token, the web application is immediately called immediately after the token is created, so there may be problems if the application is not started to respond to request. If this happens, the token will remain in the database, resulting in potential security risks. So you also need to pre-arrange a job to delete a token that exceeds the specified time length. You can also create your own specific token, which consists of tokens and the time to create this token. This simply modifies the VerifyLogintoken method to check the time, make sure it is less than the specified length of time.

The token used in this article is a GUID type, which enforces you to call up the database to retrieve user profile information. One of the preferred enhancements of the system is to use the WS-Security Enhancement Standard to Encrypted Profile Information and only passed it as a token to each web application by the application initiator. This will avoid the round-trip database.

Of course, you might want to change all the dynamic SQL calls in the code to use stored procedures and parameters to avoid suffering from any SQL traffic injection attack, and completely guarantee the security of data tables. For command objects, stored procedures and parameters should be used.

Back to top

Installation example

This article comes with two sample applications. They are all web applications. The solution also contains class libraries for each web application. Examples have two versions of Microsoft Visual Basic® .NET and C #, you can choose the you want to use. There is also a .sql file in the solution file, can be used to help you create the table you want in the database. The .sql file is used for SQL Server, but after a simple modification, it can also be used in other database systems. The following is the steps that the installation sample application should perform. • Create a database named ESECURITY in DBMS. • Execute the .sql file, create a table in the ESECURITY database. • Unzip the supplied .zip file into the folder. • Create a virtual directory to point to each folder you want to use. For example, if you are using an example of VB.NET versions, create two names that are applaunchervb and AppTestvb, respectively, and point to both folders. • Modify the .sln file to point to the virtual directory folder you created.

Back to top

in conclusion

A single sign-in system for web applications helps save user time and mitigated inconvenience caused by memory login IDs and passwords in the enterprise. In addition, it allows external users to use internal web applications without having to add these users to the domain. Realizing such a system simply creates a few simple tables and classes. But to create a reliable enterprise security system that completely uses a single login method, you need to do a lot of work. The examples in this article allow you to have a good start.

Back to top

Reference

ASP.NET Developer's JumpStart (English)

Building Secure Microsoft ASP.NET Applications (English)

About author

Paul D. Sheriff is the president of PDSA, Inc. (http://www.pdsa.com/products), the company is Microsoft consulting firm and partner, providing consulting, products, and services related to .NET, including SDLC documents And architecture frame. Paul is the regional head of Microsoft in South California. He writes .NET books include "ASP.NET Developer's JumpStart" (Addison-Wesley), and some e-books listed on the PDSA website. Paul's contact email is psheriff@pdsa.com.

转载请注明原文地址:https://www.9cbs.com/read-113370.html

New Post(0)