-1

I am building a rest api using asp.net & identity 2. This is my primary data api.

I am also building another api using expressjs for searching data stored in a search index.

Angular spa will be consuming both these apis for data and searching needs.

How can I secure expressjs api calls using the bearer token that asp.net identity is already providing to angular when a user logs in?

Chirdeep Tomar
  • 4,281
  • 8
  • 37
  • 66

2 Answers2

3

To achieve this you need to have a token consumption middle ware in your expressjs API. I have done this as below

  1. Built a authorization server using JWT with WEB API and ASP.Net Identity as explained here http://bitoftech.net/2015/02/16/implement-oauth-json-web-tokens-authentication-in-asp-net-web-api-and-identity-2/
  2. Write a consumption logic (i.e. middleware) in all my other APIs (Resource servers) that I want to secure using same token. Since you have another API in expressjs you need to do something like below

npm install jsonwebtoken

Refer - https://jwt.io

    var apiRoutes = express.Router(); 
    apiRoutes.use(function(req, res, next) 
    {      
    // check header or url parameters or post parameters for token
    var token = req.body.token || req.query.token || req.headers['x-access-token'];

    // decode token
    if (token) {

      // verifies secret and checks exp
      jwt.verify(token, app.get('superSecret'), function(err, decoded) 
    {      
        if (err) 
      {
          return res.json({ success: false, message: 'Failed to authenticate token.' });    
        } 
      else 
      {
          // if everything is good, save to request for use in other routes
          req.decoded = decoded;    
          next();
        }
      });    
    } 
    else 
    {

      // if there is no token
      // return an error
      return res.status(403).send({ 
          success: false, 
          message: 'No token provided.' 
      });

    }
  });

Refer - https://scotch.io/tutorials/authenticate-a-node-js-api-with-json-web-tokens

P.S. - I have done this with a web API issuing JWT (Authorization server or Auth & resource server) and successfully able to secure APIs built in python (resource server) and spring (resource server).

Ravi A.
  • 2,163
  • 2
  • 18
  • 26
  • Ravi A I am sticking with doing everything in .net for now but I really appreciate your time. When, I convert into micro services, I will definitely follow this. – Chirdeep Tomar May 31 '16 at 15:41
0

Try express-bearer-token. This seems to fit your description

https://www.npmjs.com/package/express-bearer-token

Nicolai Kant
  • 1,391
  • 1
  • 9
  • 23