How to store the access_token gained from OAuth for later use?

1.3k Views Asked by At

I'm attempting to get and store an access token from the Pocket API using Node.js. I am able to get the request token, redirect to the Pocket login page, redirect back to my site, and finally able to exchange the request token for an access token.

But that's where my problem lays. I don't know how I should go about actually storing the token, and without it I am unable to make API calls (of course). Here's the relevant code:

//called when Pocket API redirects back to /getAccessToken
function getAccessToken(response, requestToken) {
    restler.post("https://getpocket.com/v3/oauth/authorize", {
        headers: { "Content-Type" : "application/json",
                   "X-Accept" : "application/json" },
        data : JSON.stringify({consumer_key:CONSUMER_KEY,code:requestToken})
    }).on("complete", function(data, res) {
        if(res.statusCode == 200) {
            var accessToken = data.access_token;
            console.log("Access granted: " + accessToken);
            //BUT HOW DO I STORE THE ACCESS TOKEN FOR USE OF API CALLS ??
        }
        response.writeHead(307, {Location: DNS}); //go back to site
        response.end();
    });

};

I was thinking I should store the accessToken on the client side, but I don't actually know how to go about doing that. I've tried using cookies, but that didn't seem to work. Of course, I may have just implemented them wrong.

Your help is much appreciated.

2

There are 2 best solutions below

0
On

you should probably make the cookies thing work. option 2 is to use localStorage but if you're struggling with cookies i wouldn't try going down that path - it gives you more control of when the tokens are sent across the wire but also requires a lot more work to make your serverside and clientside code coordinate.

0
On

How you store the access token usually depends on where you will be using the API.

I usually like to persist tokens in the database (like MongoDB) on the User document they are associated with, and then my web client can ping my server (via a RESTful endpoint) if it needs the token for anything. This way if the user clears all that state on the browser you don't have to go through the entire OAuth flow again.