Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

nodejs passport authentication token

nodejs passport authentication token

Problem

I am writing a nodejs application that I would like to use as both a web application, as well as an API provider. Once a user is authenticated, I want to assign that user a Token to be used for subsequent requests. This works great with passport for the web application, as I just serialize and deserialize the user with the token in the session. However, when responding to API requests, there is no cookie to set to store the session information. Ideally, passport would look for the token both in session and the request body. Is there any way to configure passport to accomplish this?

Problem courtesy of: Austin

Solution

Simply use the access token on every request. Using a session is NOT needed. The following is the workflow:

POST /signin
  1. The username and password are posted in the client request.
  2. The server authenticates the user by using passport's Local Strategy. See passport-local.
  3. If the credentials represent a valid user, the server returns the access token generated by some generator. node-jwt-simple is a good choice.
  4. If the credentials are invalid, redirect to /signin.

When the client receives the access token from the authorization server, it can then make requests to protected resources on the server. For example:

GET /api/v1/somefunction?token='abcedf'

  1. The client calls some server api with the token argument.
  2. The server authenticates the token by using passport's Bearer Strategy. See passport-http-bearer.

References

Make a secure oauth API with passport.js and express.js (node.js)

Solution courtesy of: bnuhero

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

nodejs passport authentication token

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×