【问题标题】:Unable to invalidate the Asp.Net cookies instantly after logout注销后无法立即使 Asp.Net cookie 无效
【发布时间】:2019-09-11 11:22:34
【问题描述】:

用户已从站点注销,但 API 可以从 POSTMAN 访问,并且标头中有 cookie?

退出

        public async Task OnPost(string returnUrl = null)
    {
        await _httpContextAccessor.HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme,
            new AuthenticationProperties
            {
                RedirectUri = returnUrl
            });

        await _signInManager.SignOutAsync();
        HttpContext.Response.Cookies.Delete(".AspNetCore.Cookies");
    }

启动

public class Startup
{
    public Startup(IConfiguration configuration, IHostingEnvironment env)
    {
        Configuration = configuration;
        HostingEnvironment = env;
    }

    public IConfiguration Configuration { get; }
    public IHostingEnvironment HostingEnvironment { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        //Https
        services.AddHsts(options =>
        {
            options.Preload = true;
            options.IncludeSubDomains = true;
            options.MaxAge = TimeSpan.FromDays(180);
            options.ExcludedHosts.Add("admission.just.edu.bd");
            options.ExcludedHosts.Add("www.admission.just.edu.bd");
        });

        services.AddHttpsRedirection(options =>
        {
            options.RedirectStatusCode = StatusCodes.Status301MovedPermanently;
            options.HttpsPort = HostingEnvironment.IsDevelopment() ? 5001 : 443;
        });

        services.AddMemoryCache();

        services.AddDbContext<AdmissionDbContext>(options =>
        {
            if (HostingEnvironment.IsDevelopment())
            {
                options.UseSqlServer(Configuration["DbConnection:Sql:Local"], x => x.MigrationsHistoryTable("__EFMigrationsHistory", Configuration["DbConnection:Sql:Schema"]));
            }
            else
            {
                options.UseSqlServer(Configuration["DbConnection:Sql:Cloud"], x => x.MigrationsHistoryTable("__EFMigrationsHistory", Configuration["DbConnection:Sql:Schema"]));
            }

        });

        services.AddIdentity<ApplicationUser, IdentityRole>(
            options =>
            {
                options.ClaimsIdentity.UserIdClaimType = ClaimTypes.NameIdentifier;
                options.Password.RequireDigit = false;
                options.Password.RequiredLength = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase = false;
                options.Password.RequireLowercase = false;
                options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromHours(2);
            })
            .AddEntityFrameworkStores<AdmissionDbContext>()
            .AddDefaultTokenProviders();

        services.AddAuthorization(opts =>
        {
            opts.AddPolicy("AuthenticatedUser", policy => policy.RequireAuthenticatedUser());
            opts.AddPolicy("SystemAdminOnly", policy => policy.RequireRole(SystemRole.Administrator));
            opts.AddPolicy("SupportOnly", policy => policy.RequireRole(SystemRole.Support));
            opts.AddPolicy("ApplicantOnly", policy => policy.RequireRole(SystemRole.Applicant));
        });

        services.AddScoped<IClaimsTransformation, ClaimsTransformation>();

        services.AddSession();

        services.AddMvc(
                options =>
                {
                    options.Filters.Add<ErrorExceptionFilter>();
                }
            ).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddRazorPagesOptions(options =>
            {
                options.AllowAreas = true;
                options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
                options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
            })
            .AddJsonOptions(opts =>
            {
                opts.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
                opts.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
                opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                opts.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                opts.SerializerSettings.DateTimeZoneHandling = DateTimeZoneHandling.Utc;

                if (HostingEnvironment.IsDevelopment())
                {
                    opts.SerializerSettings.Formatting = Formatting.Indented;
                }
            });

        services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        //app.UseDeveloperExceptionPage();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
            app.UseDatabaseErrorPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        app.UseHsts();

        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRequestLocalization();

        // app.UsePendingMigrations();

        app.UseDefaultRoles(SystemRole.All);
        app.UseDefaultUsers();

        //app.UseCookiePolicy();
        app.UseAuthentication();
        app.UseSession();

        app.UseMvc(routes =>
        {
            routes.MapRoute("areaRoute", "{area:exists}/{controller}/{action=Index}/{id?}");

            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

【问题讨论】:

  • 问题中没有注销代码。即使Response.Cookies.Delete(cookieKey); 删除了 cookie(它没有,它从 response 中删除它),也不会阻止 POSTMAN 或任何其他客户端发送 cookie再次
  • 它有await _signInManager.SignOutAsync();
  • 请只发布相关代码。
  • 好的。我已经编辑了我的代码。你现在能帮忙吗?
  • 您删除了相关部分 - LocalRedirect 并留下了不相关的配置。它是发送实际响应和 cookie 的重定向。我怀疑这是 ASP.NET Core Identity 2.0 SignoutAsync is not logging out user if the user signed in with Google 的副本

标签: c# asp.net-core-2.0


【解决方案1】:

我不知道为什么,但由于某种原因,Response.Cookies.Delete(cookieKey) 不适合我。我所做的是创建另一个具有相同 cookie 名称的 cookie,并将过期时间设置为过去的某个时间。例如:

var c = new HttpCookie("cookieKey");
c.Expires = DateTime.Now.AddDays(-1);
Response.Cookies.Add(c);

【讨论】:

    猜你喜欢
    • 2020-09-28
    • 1970-01-01
    • 2022-01-06
    • 2012-08-08
    • 1970-01-01
    • 2010-11-11
    • 2012-01-21
    • 2013-06-14
    • 1970-01-01
    相关资源
    最近更新 更多