Currently, our Store Manager can be accessed by anyone. Let's restrict access to site management.
Add AccountController and corresponding View
In the full-featured ASP. NET MVC3 Wb application and empty ASP. the difference between the NET MVC3 application templates is that the empty application template does not contain the account controller. We can create a new full-featured ASP.. net mvc application to add an account controller.
In addition, the MvcMusicStore-Assets.zip file you downloaded also contains the Account Management file.
Copy the following content to your website.
- Copy AccountController. cs to the Controllers directory.
- Copy AccountModels. cs to the Models directory.
- Create the Account directory in the Views directory and copy the corresponding four Views.
Note that the namespace of the controller and model classes is MvcMusicStore. The AccountController class should be the MvcMusicStore. Controllers namespace, And the AccountModels class application uses the MvcMusicStore. Models namespace.
The updated solution looks as follows:
Add an administrator account using ASP. NET Site Configuration Tool
Before authorizing access to a website, you need to create an administrator account. The simplest way is to use the built-in ASP. NET site management tool to create an account.
On solution manager, click site configuration tool
Wait a moment. a browser window will pop up. Click the Security tab on the home page, and then click the "enable role" link in the middle of the screen.
Click "create or Manage Roles.
Enter "Administrator" in the role name input box and click "add role.
Click "back" and click "create user" on the left of the screen.
Fill in the user information with the following information.
Field Value
User Name Administrator
Password password123!
Confirm Password password123!
E-mail (any e-mail address will work)
Security Question (whatever you like)
Security Answer (whatever you like)
Note: You can use any password you want. However, the default password rule requires that the password contain at least seven characters, including at least one non-letter or number.
Select the Administrator role,
The user has been created successfully.
Now, you can close this window.
Role-based authorization
Now, we can use the [Authorize] annotation to restrict access to the StoreManager controller. Users who access any Action of StoreManager must have the Administrator role.
[Authorize(Roles = "Administrator")]public class StoreManagerController : Controller{// Controller code here}
Note: [Authorize] can also be used in the Action method.
Now browsing/StoreManager will be directed to the login page.
After logging in with an account with the Administrator role, you can access StoreManager.
Author champion