20 secrets of mvc3-(1) Use passwords to restrict access to Views

Source: Internet
Author: User
Tags connectionstrings

Scenario
You want to prevent users from accessing a specific page of your website, unless the user has been registered and logged in with the user name and password.
<! -- [If! Supportlinebreaknewline] -->

Solution

Use an accountcontroller, accountmodels, and several MVC views in combination with ASP. NET authorizeattribute features, formsauthentication and membership creation/validation

Discussion

Microsoft's MVC team has made many improvements to the account controller. It has been updated for form verification, along with the membership class to create new users, verify existing users, and create cookies to detect the user's login status.

Several default applications have been provided in MVC 3.ProgramTemplate. For example.

• Empty, an empty template will create some file structures required by MVC.

• Internet application. The default template of an Internet application will contain some pre-configuration: basic layout. An accountcontroller contains multiple actions (registration, login, and password change ).

• Intranet application: intranet application. It is similar to the second template. However, instead of using the membership class, he uses Windows authentication.

For most websites, we should use the second template by default. If you have not yet done so, you can create an MVC 3 Internet application.

This will generate accountcontroller, accountmodels, and views for several accounts (User Registration, login, and password change ).

To organize users to access specific views, MVC provides an authorizeattribute feature. Open accountcontroller and you can see the following:Code:

 
//Get:/account/changepassword

[Authorize]
PublicActionresult changepassword ()
{
ReturnView ();
}

The intention is that only login users can access the password modification page.

when a user accesses a page /account/changepassword, if it is not pre-logged in or registered. MVC automatically redirects requests to the logon page. Otherwise, MVC is forwarded to changepassword page. For Unauthenticated users, the redirect page is configured in Web. config .

<AuthenticationMode= "Forms">
<FormsLoginurl= "~ /Account/logon"Timeout= "2880"/>
</Authentication>

If the user has never registered, he can click "register" on the login page to go to the registration page. This page contains the following information:

• Username

• Email Address

• Password

The register action in accountcontroller receives a parameter of the registermodel type. In accountmodels, a type is defined as registermodel, which contains the variables (username, emailaddress, password) of the elements on the registration page ).

 

Register action:

View code

[Httppost]
Public Actionresult register (registermodel Model)
{
If (Modelstate. isvalid)
{
// Attempt to register the user
Membershipcreatestatus createstatus;
Membership. createuser (model. username,
Model. Password, model. email, Null , Null ,
True , Null , Out Createstatus );
If (Createstatus =
Membershipcreatestatus. Success)
{
Formsauthentication. setauthcookie (
Model. username,
False /* Createpersistentcookie */ );
Return Redirecttoaction ( " Index " , " Home " );
}
Else
{
Modelstate. addmodelerror ( "" ,
Errorcodetostring (createstatus ));
}
}
// If we got this far, something failed,
// Redisplay form
Return View (model );

 

The above code is automatically generated, and they do three important things.

    1. A new user is created using the membership. createuser () method.
    2. If it is successfully created, set a cookie to the user so that the user can access the subsequent page.
    3. If the creation is successful, the page will jump to the homepage (if the creation fails, the error message will be displayed to the specified view ).

If you have installed the full version of Visual Studio and SQL Express. You can see the user you created in the database.

You can view aspnetdb. MDF under appdata in solution manager. Open it directly. Is a user I just created.

The default database connection string is in webconfig.

<Connectionstrings>
<AddName= "Applicationservices"Connectionstring= "Data Source =. \ sqlexpress; Integrated Security = sspi; attachdbfilename = | datadirectory | aspnetdb. MDF;
User instance = true"Providername= "System. Data. sqlclient"/>
</Connectionstrings>

When a user accesses the website again in the future, if the formsauthentication cookie is still saved (assuming that the "remember me" option is selected during login or the browser is not closed), they do not need to log on again.

If the cookie is not saved. He will be directed to the logon page. Once the user enters the login information and submits the form. Accountcontroller verifies the user through the membership class. As follows:

 

View code

[Httppost]
Public Actionresult Logon (logonmodel model,
String Returnurl)
{
If (Modelstate. isvalid)
{
If (Membership. validateuser (model. username,
Model. Password ))
{
Formsauthentication. setauthcookie (
Model. username, model. rememberme );
If (URL. islocalurl (returnurl)
& Amp; returnurl. Length & gt; 1
& Returnurl. startswith ( " / " )
&&! Returnurl. startswith ( " // " )
&&! Returnurl. startswith ( " /\\ " ))
{
Return Redirect (returnurl );
}
Else
{
Return Redirecttoaction ( " Index " , " Home " );
}
}
Else
{
Modelstate. addmodelerror ("" ,
" The user name or password provided
Is Incorrect. " );
}
}
// If we got this far, something failed,
// Redisplay form
Return View (model );
}

The code page above is automatically generated. Three things are done:

1. Verify the user name and password through membership. validateuser ()

2. If the login succeeds, use formsauthentication. setauthcookie to save a cookie.

3. If the verification is successful, the system will navigate to the Home Page. Otherwise, an error message will be displayed on the logon page.

The authorizeattribute feature further limits a specific user group or user to access the specified action.

For example:

View code

 //  Retrieve a list of all users to allow an admin
// To manage them
[Authorize (roles = " Admin " )]
Public Actionresult useradmin ()
{
Membershipusercollection users =
Membership. getallusers ();
Return View (users );
}
// Create some M reports for me only
[Authorize (users = " Jamie " )]
Public Actionresult jamieadmin ()
{
// Perform some logic to generate usage reports
...
Return View ();
}

The preceding simple example is just the beginning of How to restrict access to content.

For more information, see

Authorizeattribute, formsauthentication, and membership



<! -- [Endif] -->

Related Article

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.