20 tips for ASP. net mvc 3 Development (I) [20 recipes for programming MVC 3]: Restrict Access To views through password verification

Source: Internet
Author: User

Topics

Create a website specific page that a user must register and log on to with the user name and password to access.

To create a page with permission control, you must register the page and log on with your username and password.

Solution

Accountcontroller and accountmodels and several verification views use membership and formsauthentication to create and verify users. Use authorizeattribute to control access permissions in ASP. NET.

 

Discussion

Microsoft's ASP. net mvc team made many improvements to accountcontroller, updated the formsauthentication class, used the membership object to create new users, verified existing users to create cookies, and checked the user status.

 

Unlike MVC 2, the new project dialog box is updated in the third edition, which provides three different applications.ProgramType: Empty application, Internet application, and intranet application. An empty application only creates the folder structure required by MVC in the project. Internet applications, set the default template, and create and pre-configure several features, including a basic layout template, as well as MVC applications for user registration and login through accountcontroller. The third template is an intranet application. Unlike an Internet application, the membership class is not used for authentication, but Windows authentication.

 

For most websites, use the default Internet application. Creating a new Internet application named mvc3 will generate accountcontroller, accountmodels, and several views about user accounts, including views about user registration, logon, and password modification.

 

To prevent users from accessing certain pages, MVC controls access through authorizeattribute on some specific controllers and actions. Open acctioncontroller. CS and we will see the following:

 
//

//Get:/account/changepassword



[Authorize]

PublicActionresult changepassword ()

{

ReturnView ();

}

When an unregistered user accesses the service through/account/changepassword, MVC automatically jumps to the logon page. If they have logged on, the page will not be redirected, but the view content will be displayed. The default redirected User Logon address can be set in the web. config file:

<AuthenticationMode= "Forms">

<FormsLoginurl= "~ /Account/logon"Timeout= "2880" />

</Authentication>

If the user has never registered before, it will be transferred to the registration page. By default, the following information must be collected during registration:

L logon Username

L email address

L logon Password

The Register Method in accountcontroller uses membership to create a new user account. The input parameter of the register method is a registermodel type object. For the registry list on the page, we defined an object named registermodel in accountmodels.

[Httppost]

Public Actionresult register (registermodel Model)
{
If (Modelstate. isvalid)
{
// Try to register a 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 );
Return Redirecttoaction ( " Index " ," Home " );
}
Else
{
Modelstate. addmodelerror ( "" , Errorcodetostring (createstatus ));
}
}
}

TheCode, Implements three important functions:

    1. After the user inputs the data, use the membership. createuser () method to create a new user;
    2. Make sure that the user has been created successfully. Use formsauthentication. setauthcookie to set the user logon status so that the user can verify the status when accessing the page in the future.
    3. If the user has been created successfully, the user will be redirected back to the home page. (If an error occurs during user creation, the error message is sent to the error view and the error message is displayed to the user ).

If you have installed the complete version of Visual Studio, you can create a database through the installed SQL Express. Alternatively, you can only install the basic version of Visual Studio, or download it from Microsoft's website to free SQL Express.

The SQL express database created in the app_data folder is added to Web. config. This SQL express database will contain various tables of user content to be stored in the membership class, such as user data and roles.

    connectionstrings  > 
Add name =" applicationservices "
connectionstring =" Data Source =. \ sqlexpress;
Integrated Security = sspi;
attachdbfilename = | datadirectory | aspnetdb. MDF;
user instance = true "
providername =" system. data. sqlclient " />
connectionstrings >

When the user visits the website again, the cookie set through fromsauthentication last time is still valid (probably because they selected the "remember me" option during login or some other pages are not closed ), the view you view does not require them to log on or register again. If the cookie does not exist and the user has completed registration, the page will be redirected to the logon page. Once the user enters the logon information and submits the information, accountcontroller verifies the user's logon through memership again. The Code is as follows:

[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 an error occurs somewhere at this step, the form is displayed again.
Return View (model );
}

The code automatically generated above implements three important functions:

    1. Use memership. validateuser () to verify the user's user name and password;
    2. If the logon succeeds, the logon information is set using the formsauthentication. setauthcookie method;
    3. If the user passes the verification, the user will be redirected to the homepage (or if the user fails the verification, the error message will be displayed to the user ).

Authorizeattribute not only allows some users to access specific pages, but also provides other restriction options. The usage is as follows:

         //  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 ();
}

These simple examples only introduce some entry-level content about restricted access. In the next section, we will study how to add a custom group access control controller.

References

Authorizeattribute, formsauthentication and membership

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.