Mehulkumar
Mehulkumar

Reputation: 866

How to authenticate/authorize express routes in loopback

I've just created a loopback app and extended User model for the user authentication/authorization.

I'm trying to check if the user is currently logged in or not from my express route so I could redirect user to /login if user is not logged in.

So far it seems loopback only authenticates/authorizes the exposed model methods like /user/update. I'm not able to find anything on how to get loopback to authenticate/authorize the express routes I've defined.

Thanks in advance

Upvotes: 1

Views: 971

Answers (2)

svershin
svershin

Reputation: 58

In order to enable authentication and authorization for Express routes in a LoopBack application you will need to do the following:

  1. Initialize Loopback Token middleware to use a cookie
  2. Set the signed access_token cookie after you have performed a login
  3. Add middleware to store request context (to enable steps 4 - 6 below)
  4. Add middleware to identify requesting user and store user info in the request context
  5. Add middleware to enable enforcement of login on selected routes
  6. Add login enforcement middleware calls to Express routes as required

If this looks mildly terrifying, fear not because someone has written an awesome blog post on this and provided sample code for all of the above middleware:

Tokens, Sessions and Users, oh my!

Things to note:

  • If you want your sessions to persist, make sure that LoopBack's AccessToken model is configured to use a data store other than memory. See here for more information: Allow loopback application to use previous access token

  • The request context middleware as implemented in the blog post does not work as a persistent session store (i.e. only the token persists), the rest is ephemeral.

Upvotes: 0

YLS
YLS

Reputation: 717

Here's the thing, I'm not very good at loopback but I do know a little about Expressjs.

In express, if you wanna do auth, you can use a middleware of your own and use it before other routes handle the request.

You might want to consider express-session as the login status storage.

When log in :

route.post('/login',function(req,res,next){
    //login here
    req.session.user = user
})

And your own middleware:

function auth(req,res,next){
  if(!req.session.user){
     res.redirect('/login')
  }
}

https://github.com/expressjs/session

Upvotes: 1

Related Questions