简体   繁体   English

Node表示验证已签名的cookie

[英]Node express verifying signed cookie

I am trying to use signed cookies in Node's express module, and have read the documentation, but am confused on how to verify them. 我正在尝试在Node的快速模块中使用已签名的cookie,并已阅读文档,但对如何验证它们感到困惑。 As I understand it, I must verify the cookies on the server. 据我了解,我必须验证服务器上的cookie。 However, how I do so is unclear to me. 但是,我怎么这样做对我来说还不清楚。 I will receive the cookie, and then what? 我会收到饼干,然后是什么? Must I run a function to verify it? 我必须运行一个函数来验证它吗? If so, what function? 如果是这样,有什么功能? If not, and its automatic, how do I program what to do if the cookie is indeed modified? 如果没有,并且它是自动的,我如何编程如果cookie确实被修改了怎么办? What code must I use to check for this? 我必须使用什么代码来检查这个? I intend to use these signed cookies for user authentication. 我打算使用这些签名的cookie进行用户身份验证。 So if I go to a page, and want to show different content depending on whether or not the user is authenticated, I'm not sure how to do this. 因此,如果我转到某个页面,并希望根据用户是否经过身份验证来显示不同的内容,我不知道该怎么做。 If the page renders before I verify the cookie, I don't see how this would be possible. 如果在我验证cookie之前页面呈现,我看不出这是怎么回事。 I therefore assume that I must verify the cookie before rendering the page, which leads me to ask this question, in order to figure out how to do so. 因此,我假设我必须在呈现页面之前验证cookie,这导致我提出这个问题,以便弄清楚如何这样做。

Essentially, I wish to do something like this: 基本上,我希望做这样的事情:

if(CookieIsVerified)
{
   .....
}
else if (!CookieIsVerified)
{
     .....
}

You don't need to verify the cookie yourself. 您无需自行验证cookie。 If you use the cookieParser middleware you can pass in a secret which will be used to sign the cookie. 如果您使用cookieParser中间件,您可以传入一个秘密,用于签署cookie。 This means that nobody can change it. 这意味着没有人可以改变它。

Secondly, use the cookieSession middleware. 其次,使用cookieSession中间件。 This will take anything that is in req.session and serialize it into the cookie. 这将采取req.session中的任何内容并将其序列化为cookie。

app.use(express.cookieParser('yoursecretkeyhere'));
app.use(express.cookieSession());

To check whether a user is authenticated, you can create your own middleware which checks that the current session has been authenticated. 要检查用户是否已通过身份验证,您可以创建自己的中间件,以检查当前会话是否已通过身份验证。 If it's not redirect to the login page or return a 401. This middleware should be used on all your routes except the login route. 如果它没有重定向到登录页面或返回401.应该在除登录路由之外的所有路由上使用此中间件。

Create a login route which takes credentials and doesn't use the above middleware. 创建一个获取凭据但不使用上述中间件的登录路由。 In here you can check username/password or tokens and if the user is a valid one, set an authenticated flag on the session. 在这里,您可以检查用户名/密码或令牌,如果用户是有效用户,请在会话中设置经过身份验证的标志。 You can check this flag in your above middleware. 您可以在上面的中间件中检查此标志。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM