【发布时间】:2020-11-30 10:41:47
【问题描述】:
我们正在使用 System.Web.Security.FormsAuthenticationTicket 为未登录的用户创建匿名 cookie。在 AspNetCore 中是否有等价物? 我很清楚 ASP.NET Core 不支持表单身份验证。新的做事方式是cookies。那么如何创建一个在新情况下做等价的cookie呢?
【问题讨论】:
标签: asp.net-core cookies anonymous
我们正在使用 System.Web.Security.FormsAuthenticationTicket 为未登录的用户创建匿名 cookie。在 AspNetCore 中是否有等价物? 我很清楚 ASP.NET Core 不支持表单身份验证。新的做事方式是cookies。那么如何创建一个在新情况下做等价的cookie呢?
【问题讨论】:
标签: asp.net-core cookies anonymous
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();
}
【讨论】: