【发布时间】:2018-02-02 23:03:27
【问题描述】:
我正在尝试了解 cookie 身份验证,尤其是对于 ASP.NET Core。据我了解,cookie 身份验证的一般工作方式是会话 ID 存储在服务器端和客户端。发出请求时,会发送会话 ID,并与服务器端的 ID 进行检查。
我在 ASP.NET Core 中使用以下代码尝试了 cookie 身份验证中间件:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme,
AutomaticAuthenticate = true
});
在 AccountController 中,登录后:
var myUser = GetUser(email, password);
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, myUser.Name)
};
var props = new AuthenticationProperties
{
IsPersistent = persistCookie,
ExpiresUtc = DateTime.UtcNow.AddYears(1)
};
var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
await HttpContext.Authentication.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, new ClaimsPrincipal(identity), props);
我看到浏览器中有一个 cookie,但它存储在服务器端的什么位置?我想我需要将它存储在数据库中以检查是否有效,但它似乎已经存储在某个地方,因为我还没有完成任何数据库代码。还有,ASP.NET Core 怎么知道传递过来的 cookie 是有效的?
【问题讨论】:
-
Cookies 根本不存储在服务器上。服务器只是解码浏览器发送的内容。
-
@Bart Calixto:服务器如何知道 cookie 有效?
-
不要试图在技术上 100% 正确:cookie 是使用非公开的“机器密钥”加密的,只有您的服务器知道,当客户端发送 cookie 时,服务器会尝试使用它的机器密钥进行解码.如果无法解码,它将被丢弃(也称为无效)。
-
好吧,忘了这是aspnet-core。对于 aspnet-core 而不是机器密钥,有一个我不熟悉的
DataProtectionapi 负责。 github.com/aspnet/DataProtection
标签: authentication asp.net-core session-cookies