【问题标题】:AspNetCore alternative for System.Web.Security.FormsAuthenticationTicketSystem.Web.Security.FormsAuthenticationTicket 的 AspNetCore 替代品
【发布时间】:2020-11-30 10:41:47
【问题描述】:

我们正在使用 System.Web.Security.FormsAuthenticationTicket 为未登录的用户创建匿名 cookie。在 AspNetCore 中是否有等价物? 我很清楚 ASP.NET Core 不支持表单身份验证。新的做事方式是cookies。那么如何创建一个在新情况下做等价的cookie呢?

【问题讨论】:

    标签: asp.net-core cookies anonymous


    【解决方案1】:

    Asp.net 核心不支持表单认证。我建议您使用基于 cookie 的身份验证。这个link 可以帮助你构建它。

    如果您想跳过需要授权访问的方法。您可以添加属性[AllowAnonymous]

        [AllowAnonymous]
        public IActionResult Privacy()
        {
            return View();
        }
    

    或者你可以参考这个link

    在 Startup.cs 中配置 cookie。

    services.AddAuthentication("auth")
                .AddCookie("auth",config=>
                {
                    config.Cookie.Name = "cookie.name";
                    config.LoginPath = "/home/login";
                });
    

    在此操作中生成令牌。您可以通过接收表单数据填写索赔。

    [HttpPost]
    public IActionResult login()
        {
            var claims = new List<Claim>
            {
                new Claim(ClaimTypes.Name,"myName"),
                new Claim(ClaimTypes.Role,"myRole")
            };
            var claimIdentity = new ClaimsIdentity(claims,"id card");
            var claimPrinciple = new ClaimsPrincipal(claimIdentity);
            var authenticationProperty = new AuthenticationProperties
            {
                IsPersistent = true
            };
            HttpContext.SignInAsync(claimPrinciple,authenticationProperty);
            
            return View();
        }
    

    【讨论】:

    • 当然,我正在寻找一种 cookie 替代品。我将编辑原始问题。
    • @MrFox,添加cookie配置,然后生成token。
    • @MrFox,你能接受这个答案,还是有其他问题?
    猜你喜欢
    • 1970-01-01
    • 2016-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-08
    • 2012-01-25
    • 2015-08-05
    • 2011-01-01
    相关资源
    最近更新 更多