首页 新闻 赞助 找找看

.Net Core Cookie 验证,没有设置Cookie过期日期,关闭浏览器 Cookie 不失效

0
[已解决问题] 解决于 2018-06-27 14:08

Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
        .AddJsonOptions(options => { options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss"; });

    //添加 Cookie 认证信息
    services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
        .AddCookie(options =>
        {
            options.Cookie.Name = "TestCookie";
            options.LoginPath = new PathString("/Account/Login");
            options.AccessDeniedPath = new PathString("/Account/Denied");
        });
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    app.UseStaticFiles();
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
}

登录代码:

[HttpPost]
public async Task<IActionResult> LoginAsync([FromBody] dynamic loginInfo)
{
    var userList = new List<dynamic>
    {
            new { LoginId = "1", UserName = "1Name", Password = "2", Role = "admin" },
            new { LoginId = "2", UserName = "2Name", Password = "2", Role = "system" }
    };
    string loginId = loginInfo.LoginId;
    string password = loginInfo.Password;

    var user = userList.FirstOrDefault(s => s.LoginId == loginId && s.Password == password);
    if (user != null)
    {
        //用户标识
        var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
        identity.AddClaim(new Claim(ClaimTypes.Sid, user.LoginId));
        identity.AddClaim(new Claim(ClaimTypes.Name, user.UserName));
        identity.AddClaim(new Claim(ClaimTypes.Role, user.Role));
        await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme,
            new ClaimsPrincipal(identity)
            //, new AuthenticationProperties() { IsPersistent = true } , ExpiresUtc = DateTime.UtcNow.AddDays(1) }
            );

        return Json(new { result = "OK" });
    }
    else
    {
        return Json(new { result = "Error" });
    }
}

Home/Index:

public class HomeController : Controller
{
    [Authorize]
    public IActionResult Index()
    {
        if (User.Identity.IsAuthenticated)
        {
            string loginId = User.Claims.SingleOrDefault(s => s.Type == ClaimTypes.Sid).Value;
            string name = User.Identity.Name;
        }
        return View();
    }
}

登录后,关闭浏览器,再次打开 Home/Index,User.Identity.IsAuthenticated 仍然是 True。 没有设置 Cookie 过期日期,关闭浏览器 Cookie 不是应该自动失效了吗?

大豆男生的主页 大豆男生 | 小虾三级 | 园豆:608
提问于:2018-06-27 11:40
< >
分享
最佳答案
0
  • 建议在浏览器中看一下cookie的过期时间
  • “关闭浏览器”是关闭了浏览器窗口还是退出了整个浏览器程序?
奖励园豆:5
dudu | 高人七级 |园豆:31075 | 2018-06-27 13:23

解決了,是我的錯!

我是关闭了浏览器(不是浏览器里的Tab)。但是,原因还是我没“彻底”关闭浏览器:一上班就用谷歌浏览器打开了博客园,浏览了博客园最新更新的文章,然后打开vs2017 coding...,按F5调试运行,vs自动开启了另一个谷歌浏览器实例(不是Tab)显示网页,于是就发现这个问题,发现“关闭浏览器”,cookie没自动清空。。。其实,我只是关闭了调试程序的谷歌浏览器实例,早上打开博客园的谷歌浏览器实例一直没关。。。。要关闭浏览器所有Tab、所有实例,下次启动浏览器才会清除Session Cookie. 是我太粗心了,急于看到结果,对cookie的机制理解的不够深刻!

大豆男生 | 园豆:608 (小虾三级) | 2018-06-27 13:59
其他回答(2)
0

学编程你要记住一点,所有的自动都是别人自己动手完成的。

你的岁月静好,那是因为有人在那儿默默的编程....

爱编程的大叔 | 园豆:30839 (高人七级) | 2018-06-27 12:02
0

好文,这个问题我也遇到了,谢谢解答

怀恋小时候 | 园豆:202 (菜鸟二级) | 2019-07-02 16:52
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册