示例
1、Program.cs中添加app.UseAuthorization();
app.UseRouting(); //Identifying action method based route
app.UseAuthentication(); //Reading Identity cookie
app.UseAuthorization(); //Validates access permissions of the user
app.MapControllers(); //Execute the filter pipiline(action + filters)
2、ConfigureServicesExtension.cs
services.AddAuthorization(options =>
{
options.FallbackPolicy = new
AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build(); //enforces
authorization policy (user must be authenticated) for all the action methods
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = "/Account/Login";
});
3、允许匿名登录Login界面
[AllowAnonymous]
public class AccountController : Controller
报错界面也应该不用登录即可访问
[AllowAnonymous]
public class HomeController : Controller
程序运行后进入Login界面
Gitee获取源码: