public void ConfigureServices(IServiceCollection services)
{
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.LoginPath = new PathString("/Fourth/Login");// No login will redirect to this address
            options.AccessDeniedPath = new PathString("/Home/Privacy");
        });// Initialize the login address by using cookies
}
Copy the code
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory loggerFactory)
{
	app.UseAuthentication();// Check whether there is a login, who is logged in, assign the value to User
    app.UseAuthorization();// Check permissions
}
Copy the code

Use in controller

Add user cache at login

[HttpPost]
public ActionResult Login(string name, string password, string verify)
{
    string verifyCode = base.HttpContext.Session.GetString("CheckCode");
    if(verifyCode ! =null && verifyCode.Equals(verify, StringComparison.CurrentCultureIgnoreCase))
    {
        if ("Genius".Equals(name) && "123456".Equals(password))
        {
            CurrentUser currentUser = new CurrentUser()
            {
                Id = 123,
                Name = "Genius",
                Account = "Administrator",
                Email = "57265177",
                Password = "123456",
                LoginTime = DateTime.Now
            };
            #regionThe Cookie/Session to write their own
            //base.HttpContext.SetCookies("CurrentUser", Newtonsoft.Json.JsonConvert.SerializeObject(currentUser), 30);
            //base.HttpContext.Session.SetString("CurrentUser", Newtonsoft.Json.JsonConvert.SerializeObject(currentUser));
            #endregion
            // Set expiration time globally

            #region MyRegion
            var claims = new List<Claim>()
            {
                new Claim(ClaimTypes.Name,name),
                new Claim("password",password),// Can write arbitrary data
                new Claim("Account"."Administrator")};var userPrincipal = new ClaimsPrincipal(new ClaimsIdentity(claims, "Customer"));
            HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, new AuthenticationProperties
            {
                ExpiresUtc = DateTime.UtcNow.AddMinutes(30),
            }).Wait();It's no use / / await
            // Cookie policy -- user information -- expiration time
            #endregion

            return base.Redirect("/Home/Index");
        }
        else
        {
            base.ViewBag.Msg = "Incorrect account password"; }}else
    {
        base.ViewBag.Msg = "Verification code error";
    }
    return View();
}

[HttpPost]
public ActionResult Logout()
{
    #region Cookie
    base.HttpContext.Response.Cookies.Delete("CurrentUser");
    #endregion Cookie

    #region Session
    CurrentUser sessionUser = base.HttpContext.GetCurrentUserBySession();
    if(sessionUser ! =null)
    {
        this._logger.LogDebug(string.Format("User ID ={0} Name={1} exit system", sessionUser.Id, sessionUser.Name));
    }
    base.HttpContext.Session.Remove("CurrentUser");
    base.HttpContext.Session.Clear();
    #endregion Session

    #region MyRegion
    / / HttpContext. User. Claims / / other information
    HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme).Wait();
    #endregion
    return RedirectToAction("Index"."Home"); ;
}
Copy the code

Obtaining User information

CurrentUser currentUser = base.Context.User.Identity.Name == null ? null : new CurrentUser()
Copy the code

User authentication adds the following features to a controller or method

[Authorize]
Copy the code