(尝试使用户保持登录状态,直到cookie不会过期)在dotnet core 3.1中cookie过期之前的会话注销

时间:2020-06-26 08:36:45

标签: .net asp.net-core-3.1

公共异步任务TwoFactorAuthenticationResponse(字符串sig_response,字符串用户名,字符串角色) { 字符串ikey = _configuration.GetSection(“ appSettings”)。GetSection(“ IntegrationKey”)。Value; 字符串skey = _configuration.GetSection(“ appSettings”)。GetSection(“ SecretKey”)。Value; 字符串akey = _configuration.GetSection(“ appSettings”)。GetSection(“ AplicationKey”)。Value; 字符串authenticated_username = Duo.Web.VerifyResponse(ikey,skey,akey,sig_response); 用户名= Encryption.DecryptText(用户名); 如果(authenticated_username!= null && authenticated_username.Equals(username)) { // var identity = new ClaimsIdentity(new [] { // new Claim(ClaimTypes.Name,username), // new Claim(ClaimTypes.Role,role) //},CookieAuthenticationDefaults.AuthenticationScheme); // varPrincipal = new ClaimsPrincipal(identity); // var authProperties =新的AuthenticationProperties // { // IsPersistent = true, // ExpiresUtc = DateTimeOffset.UtcNow.AddDays(365),

            //};
            //HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal,authProperties).Wait();

            #region New Test Claim
            var claims = new List<Claim>

{ 新的Claim(ClaimTypes.Name,用户名),

new Claim("FullName", username),
new Claim(ClaimTypes.Role, role),

};

            var claimsIdentity = new ClaimsIdentity(
                claims, CookieAuthenticationDefaults.AuthenticationScheme);

            var authProperties = new AuthenticationProperties
            {
                //AllowRefresh = <bool>,
                // Refreshing the authentication session should be allowed.
                AllowRefresh = true,
                // ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(40),

                ExpiresUtc = DateTime.UtcNow.AddMinutes(120),
                IsPersistent = true,

                // The time at which the authentication ticket expires. A 
                // value set here overrides the ExpireTimeSpan option of 
                // CookieAuthenticationOptions set with AddCookie.

                // IsPersistent = true,
                // Whether the authentication session is persisted across 
                // multiple requests. When used with cookies, controls
                // whether the cookie's lifetime is absolute (matching the
                // lifetime of the authentication ticket) or session-based.

                //IssuedUtc = <DateTimeOffset>,
                // The time at which the authentication ticket was issued.

                //RedirectUri = <string>
                // The full path or absolute URI to be used as an http 
                // redirect response value.
            };

          await  HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(claimsIdentity),
               authProperties);
            #endregion


            return RedirectToAction("Index", "sales");
        }
        else
        {
            return RedirectToAction("LogOut");
        }
    }
    #endregion

    public async Task<IActionResult> Logout()
    {
        await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);
        return RedirectToAction("Login", "account");
    }

AND startup.cs代码是 公共无效ConfigureServices(IServiceCollection服务) {

        services.Configure<AppSettings>(Configuration.GetSection("connectionStrings"));
    
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
       
        services.ServiceResolver();
        services.RepositoryResolver();

      
        services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
  .AddCookie(
           options => { options.ExpireTimeSpan = TimeSpan.FromMinutes(120);
              // options.LoginPath = "/Account/Login/";
           }
           
           );
           
        services.AddControllersWithViews();
        services.AddRazorPages();

        
       
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        //PathString.FromUriComponent("/controllerName/actionName");
        if (env.EnvironmentName == Microsoft.Extensions.Hosting.Environments.Development)
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Shared/Error");
            app.UseHsts();
        }

        app.UseHttpsRedirection();

        app.UseStaticFiles();

        app.UseCors();           
       
        app.UseRouting();

        app.UseAuthentication();
       
        app.UseAuthorization();app.UseCookiePolicy();
        
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapRazorPages();
            endpoints.MapControllerRoute("default", "{controller=Account}/{action=Login}/{id?}");
        });
    }

0 个答案:

没有答案