Go ASP. NET user authentication (custom IPrincipal and IIdentity)

Source: Internet
Author: User
Tags httpcontext ticket

This article transferred from: http://www.cnblogs.com/amylis_chen/archive/2012/08/02/2620129.html

Default.aspx page Preview by default signin.aspx will navigate to the Default.aspx page when the login is successful, so let's simply build the Default.aspx page to see how it works:<asp:loginview id="LoginView1"runat="Server"> <AnonymousTemplate>Welcome to visit, visitors! </AnonymousTemplate> <LoggedInTemplate>Hello,<asp:loginname id="LoginName1"runat="Server"/>! <br/> <strong>userdata value:</strong> <asp:literal id="Lbuserdata"runat="Server"/> </loggedintemplate></asp:loginview><br/><asp:loginstatus ID="LoginStatus1"runat="Server"Logoutpageurl="~/logout.aspx"logoutaction="Redirect"/>Similarly, we have placed a LoginView control, but here we have placed more than one LoginStatus control. Next we look at the post code:protected voidPage_Load (Objectsender, EventArgs e) {    if(!IsPostBack) {        if(request.isauthenticated) {formsidentity identity= User.Identity asformsidentity; stringUserData =identity.            Ticket.userdata; Literal Lbuserdata= Loginview1.findcontrol ("Lbuserdata") asLiteral; Lbuserdata.text=UserData; }}} Finally, we will log in first, Then open the Default.aspx page and you'll see output similar to this: we've seen how to use Formsauthentionticket to come with additional user data, but we should see the problem with this approach: the data that can be saved is too singular, just a string. The user tables we described in the first section include various types of data. If you've seen the application of XML from an example this article, you should immediately think of this is another "single string to save a number of different types of data" scenario, we can define XML to solve. For this way, I'm not demonstrating anymore. In fact, we can customize a IPrincipal and IIdentity to finish, and then we'll take a look. Custom IPrincipal and IIdentity, whether on Windows or on the Web. NET uses both interfaces to implement user authentication. They are simply an interface that implements the type of the two interfaces that comes with the user's information and is ultimately assigned to the thread (Windows) or cookie (WEB) to authenticate the user. We add CustomPrincipal and customidentity under App_Code to implement these two interfaces: Public classCustomprincipal:iprincipal {Privatecustomidentity identity;  PublicCustomPrincipal (customidentity identity) { This. Identity =identity; }     PublicIIdentity Identity {Get {            returnidentity; }    }     Public BOOLIsInRole (stringrole) {        return false; }} Public classcustomidentity:iidentity {PrivateFormsAuthenticationTicket ticket; PrivateHttpContext context =HttpContext.Current;  Publiccustomidentity (FormsAuthenticationTicket ticket) { This. Ticket =ticket; }     Public stringAuthenticationType {Get{return "Custom"; } }     Public BOOLisauthenticated {Get{return true; } }     Public stringName {Get {            returnticket.        Name; }    }     PublicFormsAuthenticationTicket Ticket {Get{returnticket;} }    //This can be any value from the database, obtained by the Name property//be aware that authentication is now in use     Public stringEmail {Get{HttpCookie Cookie= Context. request.cookies["Email"]; if(cookie==NULL||string.isnullorempty (cookies. Value)) {stringType ="jimmy_dev[at]163.com";//You should actually get from the database based on the Name propertyCookie =NewHttpCookie ("usertype", type); Cookies. Expires= DateTime.Now.AddDays (1); Context.            RESPONSE.COOKIES.ADD (cookie); }            returncookies.        Value; }    }     Public stringHomepage {Get{HttpCookie Cookie= Context. request.cookies["Homepage"]; if(cookie==NULL||string.isnullorempty (cookies. Value)) {stringName ="www.tracefact.net";//You should actually get from the database based on the Name propertyCookie =NewHttpCookie ("Nickname", name); Cookies. Expires= DateTime.Now.AddDays (1); Context.            RESPONSE.COOKIES.ADD (cookie); }            returncookies.        Value; }} note the homepage and email these two properties, which carry our user data, here I just have a simple assignment, the actual value should be from the database. It is also important to note that the values obtained are stored in the cookie to avoid frequent access to the database. After we have defined the objects that implement both interfaces, we also need to embed it in the life cycle of the application, The specific practice is to hook up to HttpModule or to rewrite the events in the Global.asax, where I take the way to rewrite the Global.asax event, so create a Global.asax file and add the following code:voidApplication_onpostauthenticaterequest (Objectsender, EventArgs e) {IPrincipal User=HttpContext.Current.User; if(user. Identity.isauthenticated&& user. Identity.authenticationtype = ="Forms") {formsidentity formidentity= user. Identity asformsidentity; Customidentity Identity=Newcustomidentity (Formidentity.ticket); CustomPrincipal principal=NewCustomPrincipal (identity); HttpContext.Current.User=principal; Thread.CurrentPrincipal=principal; }} This piece of code is well understood, It simply replaces the default IPrincipal and IIdentity implementations with our custom CustomPrincipal and customidentity in the Postauthenticaterequest event of the application. Default.aspx page Preview once again, we have modified the Default.aspx to add two literal controls to display our custom values: The value in custom identity:&LT;BR/><strong>email:</strong><asp:literal id="LtrEmail2"runat="Server"&GT;&LT;/ASP:LITERAL&GT;&LT;BR/><strong>homepage:</strong><asp:literal ID="Ltrhomepage"runat="Server"></asp:literal><br/>then modify the page's code, use our custom customidentity, and get the custom property values from it:protected voidPage_Load (Objectsender, EventArgs e) {    if(!IsPostBack) {        if(request.isauthenticated) {customidentity identity= User.Identity ascustomidentity; if(Identity! =NULL) {                //get the value in UserData                stringUserData =identity.                Ticket.userdata; Literal Lbuserdata= Loginview1.findcontrol ("Lbuserdata") asLiteral; Lbuserdata.text=UserData; //get the value in the identityLtremail2.text =identity.                Email; Ltrhomepage.text=identity.            Homepage; If you open the page now, you will see a page similar to the following: You can see that we have a property defined in Customidentity. Note Here I just did a demonstration, so only in the customidentity contains the email and homepage Two attribute values, if you see here you think it's done, and then add all the outstanding properties to the customidentity is a big mistake. The purpose of identity is simply to provide you with the name of a logged-in user, rather than carrying all the user information, which should be provided by other types. So Microsoft defines the MembershipUser type and profile. From this point of view, customizing IPrincipal and IIdentity is not much of a significance. Here, we'd better define a type of our own to host the user data, and below we'll look at how to do it. Custom types carrying user data create a new SiteUser class in App_Code, which is implemented as follows, and I use public fields instead of attributes for simplicity: Public classsiteuser{ Public stringName;  Public stringUserimage;  PublicDateTime registerdate;  Public stringEmail;  Public stringhomepage;  Public intPostcount;  Public intReplycount;  Public byteLevel ;  PublicSiteUser (Authdataset.userrow userrow) { This. Email =Userrow.email;  This. Homepage =Userrow.homepage;  This. Level =Userrow.level;  This. Name =Userrow.name;  This. Postcount =Userrow.postcount;  This. Registerdate =userrow.registerdate;  This. Replycount =Userrow.replycount;  This. Userimage =Userrow.userimage; }    //should actually be obtained from the database     Public StaticSiteUser GetUser (stringname) {Authdatasettableadapters.usertableadapter Adapter=NewAuthdatasettableadapters.usertableadapter (); Authdataset.userdatatable usertable=adapter.                Getusertable (name); if(UserTable.Rows.Count >0){            return NewSiteUser ((Authdataset.userrow) usertable.rows[0]); }        //because the name should be valid when calling this method ,//If name is not valid, throw an exception directly        Throw NewApplicationException ("User not Found"); }} its GetUser () static method obtains a SiteUser object based on the user's name, it is important to note that when this method is normally called, the user is already logged in, that is, the name parameter is always valid, so I simply throw an exception when the search database cannot find the record. 

Go ASP. NET user authentication (custom IPrincipal and IIdentity)

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.