ASP.NET Core 里,你可以使用 属性,要求用户在访问指定的 action 或整个控制器时,要事先登录过。要为 TodoController
里的所有 action 添加认证提示,在这个控制器的第一行上面添加这个属性:
在文件顶部添加这条 using
语句:
Require authentication
Often you’ll want to require the user to log in before they can access certain parts of your application. For example, it makes sense to show the home page to everyone (whether you’re logged in or not), but only show your to-do list after you’ve logged in.
Controllers/TodoController.cs
Add this statement at the top of the file:
The
[Authorize]
attribute is actually doing an authentication check here, not an authorization check (despite the name of the attribute). Later, you’ll use the attribute to check both authentication and authorization.