[Question] Where to store the CSRF state token when performing OAuth login?

Hey all,

I am following the code in this article where in order to login with GitHub, a handleGitHubLogin handler is used for the Oauth request and handleGitHubCallback handler for the callback.

In this example, the oauthStateString state token is stored as a global value in the program. Even if the program creates a new random state token on restart, is it safe to use the same state token for all github logins as long as the server is running?

I thought that it might be better if handleGitHubLogin creates the state token per request but then my question is, how will handleGitHubCallback be able to check if the state token is the same as the one returned from GitHub?

Thank you

iirc using a global CSRF token kinda defeats the purpose, so you probably don’t want to do that.

I believe the simplest way to do this would be to generate a CSRF token for that user, then store it in a cookie/session that only your application can access. Do this before redirecting the user to the Github login page, and then when the user is redirected to your site with the CSRF token you can check to see if it is the same one you stored in the user’s cookie before sending them off to the github login page.

Hey thanks for your reply!

I was suggested by another thread that I need to also implement a way to prevent replay attacks. I’ve made a simple thread safe in memory map that keeps the token upon creation and deletes it when it gets received in the callback so it can only be used once. Do you think that suffices?

I would also like to ask how safe it is to store the token in a cookie. Currently I am using HTTPS, and cookie that has the Secure and HttpOnly flags on with 2 minutes of expiration. Do you think those measures are enough or should I encrypt the cookie too?

Thanks again!

Those sound like enough. I don’t know exactly how much safety the single-use aspect adds, but it shouldn’t hurt to implement it. You just may need to clean out unused tokens every so often.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.