Use the user attribute of httpcontext for User Authentication

Source: Internet
Author: User

The httpcontext class contains all the specific HTTP information of individual HTTP requests. This example mainly describes how to use the user attribute in the httpcontext class for user authentication!
User authentication is a majority of ASP. net web applications, which play an important role in the entire application. net, including a lot of user authentication methods, such as the well-known passport authentication, Windows authentication, form authentication, etc., but these are difficult to meet our needs in practical applications, as a result, many of our friends write their own code to implement the functions they need, which requires us to consider a lot in terms of security and system efficiency.
In fact, Asp. the built-in user authentication mechanism in. NET is very powerful and scalable. It can generate a property named user in the httpcontext object, which allows us to access various information, this includes whether the user has been verified, the user type, and the user name. We can also extend the features of this attribute to meet our requirements.
The object assigned to httpcontext. user must implement the iprincipal interface, and one of the attributes defined by iprincipal is identity, which must implement the iidentity interface. Because we only need to write the classes that implement these two interfaces, we can add any functions we need in these classes.
First, we create two classes that implement iprincipal and iidentity, namely myiprincipal and myidentity.

Myiprincipal. CS

Using system;
Using system. collections;

Namespace httpcontextusereg
{
/// <Summary>
/// Summary of myprincipal.
/// </Summary>
/// Implement the iprincipal Interface
Public class myprincipal: system. Security. Principal. iprincipal
{
Private system. Security. Principal. iidentity identity;
Private arraylist rolelist;

Public myprincipal (string userid, string password)
{
//
// Todo: add the constructor logic here
//
Identity = new myidentity (userid, password );
If (identity. isauthenticated)
{
// Obtain the role of this user if the verification is passed. Here, you can change it
// Read the role of the specified user and add it to the role. In this example, add an admin role to the user.
Rolelist = new arraylist ();
Rolelist. Add ("admin ");
}
Else
{
// Do nothing
}
}

Public arraylist rolelist
{
Get
{
Return rolelist;
}
}
# Region iprincipal Member

Public system. Security. Principal. iidentity identity
{
Get
{
// Todo: Add myprincipal. Identity Getter
Return identity;
}
Set
{
Identity = value;
}
}

Public bool isinrole (string role)
{
// Todo: Add myprincipal. isinrole implementation
Return rolelist. Contains (role );;
}

# Endregion
}
}

Myidentity. CS

Using system;

Namespace httpcontextusereg
{
/// <Summary>
/// Summary of myidentity.
/// </Summary>
/// Implement the iidentity Interface
Public class myidentity: system. Security. Principal. iidentity
{
Private string userid;
Private string password;

Public myidentity (string currentuserid, string currentpassword)
{
//
// Todo: add the constructor logic here
//
Userid = currentuserid;
Password = currentpassword;
}

Private bool canpass ()
{
// Here, you can verify the user name and password from the database as needed,
// Here, for the convenience of directly specifying strings
If (userid = "yan0lovesha" & Password = "iloveshasha ")
{
Return true;
}
Else
{
Return false;
}
}

Public String Password
{
Get
{
Return password;
}
Set
{
Password = value;
}
}

# Region iidentity Member

Public bool isauthenticated
{
Get
{
// Todo: Add myidentity. isauthenticated getter implementation
Return canpass ();
}
}

Public string name
{
Get
{
// Todo: add the myidentity. Name getter implementation
Return userid;
}
}

// This attribute can be used flexibly according to our own needs. It is not used in this example.
Public String authenticationtype
{
Get
{
// Todo: Add myidentity. authenticationtype getter implementation
Return NULL;
}
}

# Endregion
}
}

After the two classes are completed, we need to create a page class of our own to cooperate with our verification. Here we name it mypage and inherit from the page class.

Mypage. CS

Using system;
Using system. collections;

Namespace httpcontextusereg
{
/// <Summary>
/// Summary of mypage.
/// </Summary>
/// Inherit from the page class
Public class mypage: system. Web. UI. Page
{
Public mypage ()
{
//
// Todo: add the constructor logic here
//
}

Protected override void oninit (eventargs E)
{
Base. oninit (E );
This. Load + = new eventhandler (mypage_load );
}

// Extract user information from the Cache during page loading
Private void mypage_load (Object sender, system. eventargs E)
{
If (context. User. Identity. isauthenticated)
{
If (context. cache ["usermessage"]! = NULL)
{
Hashtable usermessage = (hashtable) Context. cache ["usermessage"];
Myprincipal principal = new myprincipal (usermessage ["userid"]. tostring (), usermessage ["userpassword"]. tostring ());
Context. User = principal;
}
}
}
}
}

The following figure shows the webform. aspx and webform. aspx. CS interfaces.

Webform. aspx

<% @ Page Language = "C #" codebehind = "webform1.aspx. cs" autoeventwireup = "false" inherits = "httpcontextusereg. webform1" %>
<! Doctype HTML public "-// W3C // dtd html 4.0 transitional // en">
<HTML>
<Head>
<Title> webform1 </title>
<Meta content = "Microsoft Visual Studio. NET 7.1" name = "generator">
<Meta content = "C #" name = "code_language">
<Meta content = "JavaScript" name = "vs_defaultclientscript">
<Meta content = "http://schemas.microsoft.com/intellisense/ie5" name = "vs_targetschema">
</Head>
<Body>
<Form ID = "form1" method = "Post" runat = "server">
<P> <font face = ""> User Name:
<Asp: textbox id = "tbxuserid" runat = "server"> </ASP: textbox> <br>
Password:
<Asp: textbox id = "tbxpassword" runat = "server" textmode = "password"> </ASP: textbox> </font> </P>
<P> <font face = "">
<Asp: button id = "btnlogin" runat = "server" text = "login"> </ASP: button>
<Asp: Label id = "lblloginmessage" runat = "server"> </ASP: Label> </font> </P>
<P> <font face = "">
<Asp: Panel id = "Panel1" runat = "server" visible = "false">
<P>
<Asp: button id = "btnadmin" runat = "server" text = "role 1"> </ASP: button>
<Asp: button id = "btnuser" runat = "server" text = "role 2"> </ASP: button> </P>
<P>
<Asp: Label id = "lblrolemessage" runat = "server"> </ASP: Label> </P>
</ASP: Panel>
<P> </P>
</Font>
</Form>
</Body>
</Html>

Webform1.aspx. CS

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

Namespace httpcontextusereg
{
/// <Summary>
/// Summary of webform1.
/// </Summary>
/// Replace the class inherited from the page class with the mypage class inherited from ourselves.
Public class webform1: httpcontextusereg. mypage
{
Protected system. Web. UI. webcontrols. textbox tbxuserid;
Protected system. Web. UI. webcontrols. textbox tbxpassword;
Protected system. Web. UI. webcontrols. Panel Panel1;
Protected system. Web. UI. webcontrols. Button btnadmin;
Protected system. Web. UI. webcontrols. Button btnuser;
Protected system. Web. UI. webcontrols. Label lblrolemessage;
Protected system. Web. UI. webcontrols. Label lblloginmessage;
Protected system. Web. UI. webcontrols. Button btnlogin;

Private void page_load (Object sender, system. eventargs E)
{
// Place user code here to initialize the page
}

# Code generated by region web Form Designer
Override protected void oninit (eventargs E)
{
//
// Codegen: This call is required by the ASP. NET web form designer.
//
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. btnlogin. Click + = new system. eventhandler (this. btnlogin_click );
This. btnadmin. Click + = new system. eventhandler (this. btnadmin_click );
This. btnuser. Click + = new system. eventhandler (this. btnuser_click );
This. Load + = new system. eventhandler (this. page_load );

}
# Endregion

Private void btnlogin_click (Object sender, system. eventargs E)
{
Myprincipal principal = new myprincipal (tbxuserid. Text, tbxpassword. Text );
If (! Principal. Identity. isauthenticated)
{
Lblloginmessage. Text = "incorrect user name or password ";
Panel1.visible = false;
}
Else
{
// If the user passes authentication, the user information is saved in the cache for future use
// In reality, friends can try to save user information by using user verification tickets, which is also a built-in user Processing Mechanism of. net.
Context. User = principal;
Hashtable usermessage = new hashtable ();
Usermessage. Add ("userid", tbxuserid. Text );
Usermessage. Add ("userpassword", tbxpassword. Text );
Context. cache. insert ("usermessage", usermessage );
Lblloginmessage. Text = tbxuserid. Text + "logged on ";
Panel1.visible = true;
}
}

Private void btnadmin_click (Object sender, system. eventargs E)
{
// Verify whether the user's role contains Admin
If (context. User. isinrole ("admin "))
{
Lblrolemessage. Text = "user" + (myprincipal) Context. User). Identity. Name + "belongs to the admin group ";
}
Else
{
Lblrolemessage. Text = "user" + context. User. Identity. Name + "does not belong to the admin group ";
}
}

Private void btnuser_click (Object sender, system. eventargs E)
{
// Verify whether the user's role contains the user
If (context. User. isinrole ("user "))
{
Lblrolemessage. Text = "user" + context. User. Identity. Name + "belongs to the user group ";
}
Else
{
Lblrolemessage. Text = "user" + context. User. Identity. Name + "not in the user group ";
}
}
}
}

After the code is introduced, you can try to see the effect. In this example, values are assigned directly for convenience. in actual application, these will be obtained from the database or other configuration files, and the scalability of this method is very high. We can expand the functions of the myiprincipal and myidentity classes according to our own needs. For example, you can add an isinpermission so that the user not only belongs to the role, but also has different permissions for each role. In this example, after user verification, the information of verified users is saved through the cache. We can also try to use the user verification ticket method.
We can see that this user authentication mechanism is more favored in our programs, the more benefits it brings, and there are many places worth exploring!

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.