Reputation: 3253
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. As I understand it, I must verify the cookies on the server. 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? What code must I use to check for this? I intend to use these signed cookies for user authentication. 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. 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.
Essentially, I wish to do something like this:
if(CookieIsVerified)
{
.....
}
else if (!CookieIsVerified)
{
.....
}
Upvotes: 0
Views: 1185
Reputation: 5385
You don't need to verify the cookie yourself. If you use the cookieParser middleware you can pass in a secret which will be used to sign the cookie. This means that nobody can change it.
Secondly, use the cookieSession middleware. This will take anything that is in req.session and serialize it into the 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.
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.
Upvotes: 3