功能:登录后,才能访问后续页面。
否则跳转到登录页
一,startup
public void ConfigureServices(IServiceCollection services)
{
services.AddSession();
services.AddControllersWithViews();
//添加 身份验证 服务
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).
AddCookie(CookieAuthenticationDefaults.AuthenticationScheme, o =>
{
o.LoginPath = new PathString("/Home/Login");// 登录页面的url
o.AccessDeniedPath = new PathString("/Login");//没有授权跳转的页面
o.ExpireTimeSpan = TimeSpan.FromHours(0.5); // cookies的过期时间
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseAuthentication(); //登录验证,要放在UseAuthorization之前!
app.UseAuthorization();
}
二,登录功能
Login是登录页
LoginAction是登录按钮触发的方法
LogoutAction是注销
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Login()
{
return View();
}
public IActionResult LoginAction(UserVO entity)
{
ClaimsIdentity identity = new ClaimsIdentity("Forms");
identity.AddClaim(new Claim(ClaimTypes.Sid, entity.account));
identity.AddClaim(new Claim(ClaimTypes.Name, entity.pwd));
ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(identity);
HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, claimsPrincipal);
return RedirectToAction("Index", "Email");
}
public IActionResult LogoutAction()
{
HttpContext.SignOutAsync().Wait();
return RedirectToAction("Login", "Home");
}
}
跳转页 -- [Authorize] 代表需要验证,
直接访问时,看看是不是会返回登录页
[Authorize]
public class EmailController : Controller
{
public IActionResult Index()
{
return View();
}
}