Listing 14-22. Restricting Access in the RoleAdminController.cs File
清单14-22. 在RoleAdminController.cs文件中的限制访问
namespace Users.Controllers {
[Authorize(Roles = "Administrators")] public class RoleAdminController : Controller { // ...statements omitted for brevity... // ...出于简化,忽略了这里的语句... } }
The database is seeded only when the schema is created, which means I need to reset the database to complete the process. This isn’t something you would do in a real application, of course, but I wanted to wait until I demonstrated how authentication and authorization worked before creating the administrator account.
只有在创建架构时才会种植数据库,这意味着需要重置数据库才能完成这一过程。当然,这不是在实际项目中可能要做的事情,但我希望等一等,在创建管理员账号之前,完成认证与授权的演示。
To delete the database, open the Visual Studio SQL Server Object Explorer window and locate and right-click the IdentityDb item. Select Delete from the pop-up menu and check both of the options in the Delete Database dialog window. Click the OK button to delete the database.
为了删除数据库,请打开Visual Studio中的“SQL Server对象资源管理器”窗口,找到并右击“IdentityDb”条目。从弹出菜单选择“Delete(删除)”,并在“Delete Database(删除数据库)”窗口选中那两个选项。点击“OK”按钮,删除该数据库。
Now create an empty database to which the schema will be added by right-clicking the Databases item, selecting Add New Database, and entering IdentityDb in the Database Name field. Click OK to create the empty database.
现在,右击“Databases(数据库)”条目,选择“Add New Database(添加新数据库)”,并在“Database Name(数据库名称)”字段中输入IdentityDb。点击OK,创建一个空数据库。
Tip There are step-by-step instructions with screenshots in Chapter 13 for creating the database.
提示:第13章有创建数据库的逐步说明和屏幕截图。
Now start the application and request the /Admin/Index or /RoleAdmin/Index URL. There will be a delay while the schema is created and the database is seeded, and then you will be prompted to enter your credentials. Use Admin as the name and MySecret as the password, and you will be granted access to the controllers.
现在,启动应用程序,请求/Admin/Index或/RoleAdmin/Index URL。在创建数据库架构以及植入数据库期间会有一点延时,然后将提示你输入凭据。使用Admin作为用户名,MySecret作为口令,将会获得对该控制器的访问。
Caution Deleting the database removes the user accounts you created using the details in table 14-10, which is why you would not perform this task on a live database containing user details.
警告:删除数据库也删去了你用表14-10所创建的用户账号,正是这一原因,一般不会在一个含有用户细节的活动数据库中执行此项任务。
14.5 小结
In this chapter, I showed you how to use ASP.NET Identity to authenticate and authorize users. I explained how the ASP.NET life-cycle events provide a foundation for authenticating requests, how to collect and validate credentials users, and how to restrict access to action methods based on the roles that a user is a member of. In the next chapter, I demonstrate some of the advanced features that ASP.NET Identity provides.
在本章中,我演示了如何使用ASP.NET Identity进行用户认证与授权。解释了ASP.NET生命周期事件如何提供认证基础,如何收集和检验用户凭据,以及如何根据用户的成员角色限制对动作方法的访问。下一章将演示ASP.NET Identity所提供的一些高级特性。
看完此文如果觉得有所收获,请给个。
你的推荐是我继续下去的动力,也会让更多人关注并获益,这也是你的贡献。