title: Maintaining Secret key and Access Token for JWT in Express and NodeJS with Facebook in Rest API
body: <p>I have two applications:</p>
  
  <ul>
  <li>server ( REST API Server)
  <ul>
  <li>node js</li>
  <li>Express</li>
  <li>jsonwebtokens</li>
  <li>express-jwt</li>
  <li>mongoose</li>
  </ul></li>
  <li>client (Portable Front-end)
  <ul>
  <li>bootstrap </li>
  <li>Angular JS</li>
  <li>local-storage</li>
  <li>angular-facebook</li>
  <li>angular-jwt</li>
  </ul></li>
  </ul>
  
  <p>Lateron, the client app will be ported for android, iphone and other platforms using phonegap. For OAuth, I am using Facebook as the provider. Now, I just realized JSON Web Tokens are the way to go for this kind of set up. My question is an architectural one rather than syntactical one - how to manage a secret key when signing the facebook access token and user id with JWT in nodejs?</p>
  
  <p>So this is how the flow works in my app:</p>
  
  <ol>
  <li>Angular <strong>client</strong> has a Login button</li>
  <li>User Clicks the button > Facebook Auth starts</li>
  <li><strong>Client</strong> receives user_id and FB Access Token</li>
  <li><strong>Client</strong> sends[<em>POST json body</em>] both user_id and Access Token to <strong>Node+Express Server</strong> at <em>'<a href="http://server.com/auth/login">http://server.com/auth/login</a>'</em></li>
  <li><p><strong>Node Server</strong> has applied express-jwt to all routes except <em>/auth/login</em> with a <strong></strong></p>
  
  <p>var expressJwt = require('express-jwt');</p>
  
  <p>var jwt = require('jsonwebtoken');</p>
  
  <p>app.use(expressjwt({ secret: ''}).unless({path: ['/auth/login']}));</p></li>
  <li><p><strong>Node server</strong> receives data from <strong>req.body</strong>, fetches all profile details from facebook using the JavascriptSDK, and signs it using </p>
  
  <p>var token=expressjwt.sign({profile}, );</p></li>
  <li><strong>Node Server</strong> stores(updates, if user_id exists) the new token in db and sends it as response to <strong>client</strong></li>
  <li><strong>client</strong> stores the new token it received as json data in local-storage</li>
  <li><strong>client uses angular-jwt</strong> to fetch profile data from the new token and automatically attach the new token in Authorization header for all requests it sends to the server</li>
  </ol>
  
  <p>Now, my questions are:</p>
  
  <ol>
  <li>Do I really need to store the JWT tokens in database? I am certainly not comparing the tokens in request headers with database</li>
  <li>Do I need to generate random secret keys for security, each time a person logs in? If yes then how would that fit in both client and server?</li>
  <li>When and where do I need to check for token expiration? and How do I refresh it?</li>
  </ol>
  
  <p>I am kind of lost about the design flow and mechanism. </p>