20150320--Security, Membership class

Source: Internet
Author: User

Security--authentication and authorization, membership and roles.

I. Membership and role,

First step: Register the database, run the DOS command window in VS, enter: Aspnet_regsql, build the database table.

How to launch the VS DOS command window in: \microsoft VS2012 x64-compatible tool command prompt in Visual Studio 2012\visual Studio Tools files

Input: Aspnet_regsql

Follow the prompts to complete the creation of the database.

Step Two: Configure the program, Web. config

SQL Connection statement:

< connectionStrings >     <  name= "conn"  connectionString= "server=.; database=imd;user=sa;pwd=123 "/></connectionStrings>

Membership settings:

<Membershipdefaultprovider= "AspNetSqlMembershipProvider">    <providers>        <Clear/>            <Addname= "AspNetSqlMembershipProvider"type= "System.Web.Security.SqlMembershipProvider, system.web, version=2.0.3600.0, Culture=neutral, publickeytoken= B03F5F7F11D50A3A "connectionStringName= "Conn"enablePasswordRetrieval= "false"enablePasswordReset= "true"requiresQuestionAndAnswer= "false"requiresUniqueEmail= "false"maxinvalidpasswordattempts= "5"minRequiredPasswordLength= "6"minRequiredNonalphanumericCharacters= "0"passwordAttemptWindow= "Ten"ApplicationName="/" />    </providers></Membership>

Name: Description
ApplicationName Gets or sets the name of the application whose membership information is to be stored and retrieved.
Description gets a short, easy-to-understand description that is suitable for display in Administrative tools or other user interface (UI).
enablePasswordReset gets a value that indicates whether the SQL Server membership provider is configured to allow users to reset their passwords.
enablePasswordRetrieval gets a value that indicates whether the SQL Server membership provider is configured to allow users to retrieve their passwords.
maxInvalidPasswordAttempts gets the number of invalid password or invalid password answer attempts allowed before locking the membership user.
minRequiredNonalphanumericCharacters gets the minimum number of special characters that must be included in a valid password.
minRequiredPasswordLength gets the minimum length required for the password.
Name gets a friendly name that is used to reference the provider during configuration.
passwordAttemptWindow gets the length of time to track the number of consecutive failed attempts that provide a valid password or password answer within that interval.
Passwordformat gets a value that represents the format used to store passwords in the SQL Server membership database.
passwordStrengthRegularExpression gets the regular expression used to calculate the password.
requiresQuestionAndAnswer gets a value that indicates whether the SQL Server membership provider is configured to require users to answer a password question when password reset and retrieval occurs.

requiresUniqueEmail gets a value that indicates whether the SQL Server membership provider is configured to require a unique e-mail address for each user name.

The third step: Program writing: Membership class,

Need to reference

using System.Web.Security;

1. Registered users

Membership.CreateUser ("qqq""qqqqqq" "[email Protected]");

2. Verify that the user

//Login Button protected voidButton_denglu_click (Objectsender, EventArgs e) {         bool IsOK =Membership.ValidateUser (Textbox_user. Text,textbox_pwd. Text);        if(IsOK = =true) {Response.Write ("Landing success!!! "); Label1.Text=Membership.getuser (Textbox_user. Text).        ToString (); }        Else{Response.Write ("shibai!! "); Label1.Text="not logged in"; }    }

Successful login:

3. Change the password

Use the Membership object instance method, GetUser ().

Modify button:

//Modify Password button    protected voidButton2_Click (Objectsender, EventArgs e) { MembershipUser user = Membership.getuser (Label1.Text); // Find a user         if(User! =NULL)        {            BOOLPwdok =user. ChangePassword (textbox_yuanpwd. Text, Textbox_newpwd. Text); // Change Password             if(Pwdok = =true) {Response.Write ("<script>alert (' modified successfully! ');</script>"); }            Else{Response.Write ("<script>alert (' Modify failed! ');</script>"); }            //user. ChangePassword (textbox_yuanpwd. Text,textbox_newpwd. Text);//Change Password        }    }

4. Get (Find) the User:

Design a page in the following format

C # code:
To get a single single user:

// Single User button    protected void Button1_Click (object  sender, EventArgs e)    {       = Membership.getuser ( TextBox1.Text); // Get Data         for a single user Label1.Text = user. Email;    }

Get all Users:

 //all   user button  protected  void  Button2_Click (object   sender, EventArgs e) {
    
     membershipusercollection users  
      = Membership.getallusers ();    Get all users   //checkbox data binding. 
        Checkboxlist1.datasource = users;         " Email " ;         " UserName " ;        Checkboxlist1.databind ();    }

Get single User:

Get all Users:

5. Delete User: Membership.deleteuser (userName);

Add a Delete button to delete the button code:

protected voidButton3_Click (Objectsender, EventArgs e) {        //Delete        stringUserName =Checkboxlist1.selectedvalue; Membership.deleteuser (userName);//Delete//re-query displayMembershipusercollection users =membership.getallusers (); Checkboxlist1.datasource=users; Checkboxlist1.datatextfield="Email"; Checkboxlist1.datavaluefield="UserName";    Checkboxlist1.databind (); }

Select User

Click Delete to delete the success:

6. Disable or enable:

Before you do this, learn about the two column names of the tables in SQL: isapproved (whether validated), islockedout (whether locked)

IsApproved can be modified by an administrator to determine whether a new user has passed the audit.

Islockedout is when the user attempts to log in the wrong password multiple times, the account will be locked, the administrator can only unlock, unable to actively lock.

Users will not be able to log in properly if they fail to approve or be locked. Can only be used if approved and unlocked

//Disable button    protected voidButton4_Click (Objectsender, EventArgs e) {        stringUserName =Checkboxlist1.selectedvalue; //FindMembershipUser user =Membership.getuser (userName); //changed (not yet sent back to the database)        user. isapproved = false ;        //Save (send back to database) membership.updateuser (user); }            //Enable button    protected voidButton5_click (Objectsender, EventArgs e) {        stringUserName =Checkboxlist1.selectedvalue; //FindMembershipUser user =Membership.getuser (userName); //changed (not yet sent back to the database)        user. isapproved = true ;        //Save (send back to database) membership.updateuser (user); }        

You must remember to rewrite the database, that is, UpdateUser (user name) after modification.
7. Unlock the User:

// Unlock button    protected void Button6_click (object  sender, EventArgs e)    {        string userName =  Checkboxlist1.selectedvalue;         // Find        MembershipUser user = Membership.getuser (userName);         // Unlock         user. Unlockuser ();    }
The Unlockuser () statement can directly overwrite the database and unlock the user.

20150320--Security, Membership class

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.