2017-08-24 125 views
0

我想了解cookie身份验证,特别是对于ASP.NET Core。据我所知,Cookie认证通常如何工作的是,会话ID存储在服务器端以及客户端。在发出请求时,会话ID将被发送,并会在服务器端进行检查。ASP.NET Core如何知道Cookie在cookie身份验证中有效?

我试图cookie认证中间件在ASP.NET核心使用此代码如下:

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是有效的?

+2

Cookie根本没有存储在服务器上。服务器只是解码浏览器发送的内容。 –

+0

@Bart Calixto:服务器如何知道cookie有效? –

+0

不要试图在技术上100%正确:cookie是使用非公开的“机器密钥”加密的,只有服务器知道,当客户端发送cookie时,服务器会尝试使用机器密钥进行解码。如果它不能被解码,它将被丢弃(又称无效)。 –

回答

1

在此设置中,服务器上不存储任何内容。该cookie包含完整的序列化,加密的ClaimsPrincipal和AuthenticationProperties。

有一种参考模式,可以像您所描述的那样工作,如果身份过大可以使用。在那种情况下,你确实需要建立一个数据存储。没有提供默认实现。 https://github.com/aspnet/Security/blob/5b29bced0d2f1cfc78843bcd9ec9a828c6fb5fef/src/Microsoft.AspNetCore.Authentication.Cookies/CookieAuthenticationOptions.cs#L138

+0

谢谢,那么服务器如何知道cookie有效?我可能错过了一些东西,对不起,我不清楚。 –

+0

Cookie认证中间件使用它的私钥对其进行解密,检查到期等。 – Tratcher