ASP.NET CORE MVC使用身份验证
·
使用权限验证,阻止匿名访问
在 Startup 文件中加入
public void ConfigureServices(IServiceCollection services)
{
//添加用户验证,防止匿名登录
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
//登录路径:这是当用户试图访问资源但未经过身份验证时,程序将会将请求重定向到这个相对路径
o.LoginPath = new PathString("/Account/Login");
//禁止访问路径:当用户试图访问资源时,但未通过该资源的任何授权策略,请求将被重定向到这个相对路径。
o.AccessDeniedPath = new PathString("/Home/Privacy");
});
}
然后下面在 Configure方法 中加入中间件
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
{
// ...其他代码
//在请求管道之前进行身份验证
app.UseAuthentication();
//验证身份后再验证资格
app.UseAuthorization();
}
编译运行,发现一点效果都没有,才知道。漏了在其他控制器上面加
[Authorize]
在Account控制器上面加
[AllowAnonymous]

最后,完美解决
运行效果
更多推荐
所有评论(0)