Search code examples
node.jsrestjwtloopbackjs

How to implement JWT auth on Loopback REST API?


I´m pretty new at nodejs, so I tried to implement an REST API with the loopback framework to try to simplify a bit the building process. I did correctly the models, also cusomized some endpoints, but, when connecting with the frontend (AngularJS), all the code I find, also the code I know to build, requires an JWT token to do any task that requires authorization/authentication, but it seems that loopback sends an uid2 token when I log in. I searched a lot, in stackoverflow and Github, the nearest thing I found is this (https://github.com/strongloop/loopback/issues/1905#issuecomment-310382322) but the code seems to fail here:

const data = jwt.verify(id, secretKey);
        cb(null, {userId: data.id});

Any idea?


Solution

  • In simple words, you need to know who is making the call. If you'd use the default loopback authentication you would see that in the req object there is accessToken property which identifies the user. If you want to use JWT there are plenty of ready modules you could use, eg. loopback-jwt or loopback-jwt-advanced.

    In general, what you need to do is to apply a middleware that will be responsible for authorization of your user( I strongly recommend you to get familiar with the middleware term). In simple words, middleware is a layer that your requests are going through and you can modify it's a body or reject the request.

    In abstract steps, in your middleware you would have to:

    1. get the token from the request
    2. verify the token
    3. identify the user based on the token
    4. create the loopback AccessToken entity for that given user
    5. put the token in the req.accessToken so now loopback will know who you are and you could use the ACL.

    So this is more or less what those extensions are doing.