Giter VIP home page Giter VIP logo

Comments (69)

bryannaegele avatar bryannaegele commented on August 19, 2024 3

Thank you, thank you @JulienCabanes. This was driving me insane.

I added the following to a boot script as a modification to user.

'use strict';

module.exports = function(app) {
  app.models.user.afterRemote('login', function(context, accessToken, next) {
    let res = context.res;
    let req = context.req;

    if (accessToken != null) {
      if (accessToken.id != null) {
        res.cookie('access_token', accessToken.id, {
          signed: req.signedCookies ? true : false,
          maxAge: 1000 * accessToken.ttl
        });
        res.cookie('userId', accessToken.userId.toString(), {
          signed: req.signedCookies ? true : false,
          maxAge: 1000 * accessToken.ttl
        });
      }
    }
    return next();
  });

  app.models.user.afterRemote('logout', function(context, result, next) {
    let res = context.res;
    res.clearCookie('access_token');
    res.clearCookie('userId');
    return next();
  });
};

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024 2

Thanks a lot @elropero , about 1 hour ago I made everything work, I forgot to add in passport.js configuration cookies:true for example, after I finally realize that the options parameter is needed (conclusion I got checking out the passport configurator js file in node modules) I was able to get my user succesfully loged in and recognized by the API end point, but after that, I got a Roles resolver problem and I manage to solve it too, then I had an angular issue sending the X-Access-Token header and I solved it too and now, I'm good to go with the 97% of the rest of my project.
TOTAL AMMOUNT OF DAYS GETTING AN STABLE PRODUCTION AND SECURED USER AUTHENTICATION SUBSYSTEM WITH ROLES SUPPORT FOR ME, A SUPER NEW USER OF LOOPBACK AND NODE?. 45 DAYS.
There are serious problems with loopback and basically all are product of lack of documentation, the api generator and the framework is great but the documentation is awfull and is really hard to get exactly what we need reading a document, there's a lot of time wasted in research and because of that, if a user don't know the framework, would be better and productive to change it's mind about using loopbak.
regards and thanks a lot... the community is the only great thing loopback has and it's very usefull.

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024 2

Well i don't have a very well documented procedure but i think everything
is up to configuration and the replace of the original loopback passport
component with the suggested repository forked. Let me get a procedure in
next days amd i'll post it. I have it working 100%
El 25/08/2016 10:47, "Dakotah North" [email protected] escribió:

Following @hackerunet https://github.com/hackerunet note above, I used
@jamesjjk https://github.com/jamesjjk "loopback-component-passport":
"git+https://github.com/jamesjjk/loopback-component-passport.git" and
have been able to get it to work 90% of the way. The last remaining issue
is that REST based calls for local logins don't authenticate.

Facebook and Google (both logging in and REST based calls) work like a
charm ... and local logins work except for when I login with a local user
and use the access_token to make a REST base call.

Any help would be greatly appreciated!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
#57 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AA2xqGobCw2Wr8fYUxtoClu9fquRrftOks5qjarkgaJpZM4EGysp
.

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024 1

@julien-sarazin I'm not part of the LB team and I don't have PR rights. Its good to share back with the community. Feel free to request from @superkhau @raymondfeng. Else use my repo as a source "loopback-component-passport": "git+https://github.com/jamesjjk/loopback-component-passport.git"

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024 1

Finally this issue is totally solved using this :
"loopback-component-passport": "git+https://github.com/jamesjjk/loopback-component-passport.git"
No more headaches.. thanks a lot @julien-sarazin , have spent so many hours looking around for solutions, I learned a lot, but you did it.. thanks a lot man...!!

from loopback-component-passport.

michaelfreund avatar michaelfreund commented on August 19, 2024 1

@bajtos Pull request sent. We have also added two examples of how to use the callbacks.

from loopback-component-passport.

AhtiAhde avatar AhtiAhde commented on August 19, 2024 1

I think I have managed to find a solution, which does not require forking any node modules or adding shady hacks.

The problem here is, that 3rd party authentications will use callbacks, while in the LoopBack examples, the Passport local authentication is misimplemented.

The correct way to implement it, is to POST request to the "/auth/local/callback" directly, instead of POSTing to "/auth/local". "auth/local" will skip the defaultCallback, which does all the heavy lifting. The problem exists because ExpressJS redirects do not support HTTP 307 and passing credentials as query parameters would cause log files to become a security risk, even when using HTTPS.

You need to add these two lines to your "local" provider config:

"callbackHTTPMethod": "post",
"setAccessToken": true

And do the following change in your login form (for example, the file server/pages/local.jade in the example loopback passport project):

-      form(role='form', action='/auth/local', method='post')
+      form(role='form', action='/auth/local/callback', method='post')

I have posted full details here:
strongloop/loopback-example-passport#99

from loopback-component-passport.

JulienCabanes avatar JulienCabanes commented on August 19, 2024

Same problem here :(

from loopback-component-passport.

JulienCabanes avatar JulienCabanes commented on August 19, 2024

I figured out what's going wrong and how to get around:

  • Local auth does generate an accessToken but it doesn't set the cookies accordingly as it does with facebook auth. The workaround is to get the last accessToken and set the cookies by hand inside the success callback.
res.cookie('access_token', accessToken.id, {
  signed: req.signedCookies ? true : false,
  maxAge: 1000 * accessToken.ttl
});
res.cookie('userId', user.id.toString(), {
  signed: req.signedCookies ? true : false,
  maxAge: 1000 * accessToken.ttl
});
  • There's also an issue with the local signup where req.login() does not generate any accessToken at all, the workaround is to use User.login() after it...

from loopback-component-passport.

adnanshatil avatar adnanshatil commented on August 19, 2024

It works fine for me during login ... but not in logout

This is because app.models.user.afterRemote method's callback function ...
context.result always returns null. as a result res.clearCookie fails.

Well, I was looking into some other issues related to mysql and I think that this is the same.
It worked nicely with built-in User model.

But I have created People model extended from User and mysql is the data storage. Then it is creating problem.

How can I solve this?

from loopback-component-passport.

gausie avatar gausie commented on August 19, 2024

I am currently not using sessions and would ideally like the accessToken to be appended to the success callback route in some way (in req.authInfo for example). Is that possible?

from loopback-component-passport.

superkhau avatar superkhau commented on August 19, 2024

@bajtos @raymondfeng @ritch I'm not sure about this one, PTAL.

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

+1 local login is not setting cookie for accesstoken or returning token req.accessToken. Does not allow for local-login to be used.

from loopback-component-passport.

phuongnl avatar phuongnl commented on August 19, 2024

Same problem, i dont know how to get access token when use passport local.

from loopback-component-passport.

phuongnl avatar phuongnl commented on August 19, 2024

I found the solution, install cookie-parser, add this line to server.js: app.middleware('session:before', loopback.cookieParser(app.get('cookieSecret')));.
after successRedirect to "/auth/account", in this router u can get accesstoken by req.cookies.accessToken.

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

@phuongnl but the cookie is not set client side. There is a problem with the callback for passport local

from loopback-component-passport.

phuongnl avatar phuongnl commented on August 19, 2024

@jamesjjk yes, we need other solution.

from loopback-component-passport.

gshireesh avatar gshireesh commented on August 19, 2024

i added the following change and it is working for me now.

master...gshireesh:master

then add

{
  "local": {
    "provider": "local",
    "module": "passport-local",
    "usernameField": "email",
    "passwordField": "password",
    "authPath": "/auth/local",
    "successRedirect": "/auth/account",
    "failureRedirect": "/local",
    "failureFlash": true,
    "setAccessToken" : true,
    "session" : true,
    "forceDefaultCallback" : true
  }
}

to the providers.json

the logout code will be

app.get('/auth/logout', ensureLoggedIn('/login'), function (req, res, next) {
  req.logout();
  var accessToken  = req.accessToken || "";
  if(accessToken){
    console.log('found access tocken', accessToken.id);
    var User = app.models.User;
    User.logout(accessToken.id, function (err) {
      console.log(err || 'Logged out');
    });
  }
  else{
    console.log("unable to find the access token");
  }
  res.redirect('/');
});

Hope it works for you too :)

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

@gshireesh I have implemented your fix from the PR, however req.accessToken still returns a null object for local passport. Also I see no reference to forceDefaultCallback in the code? Any ideas of what it could be

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

@gshireesh Thank you for your solution but there is an error. On line 470 it should be : info.accessToken.ttl (see comment). Also you have changed an earlier PR I noticed from (line 307):
userProfile.accessToken = accessToken;
done(null, user, {accessToken: accessToken});

from

userProfile.accessToken = accessToken;
done(null, userProfile, {accessToken: accessToken});

Why if I may ask?

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

I have an updated forked version here which also supports Email verification on the defaultCallback for those looking for that option. It requires the attribute "emailVerificationRequired" : true in your respective providers.json. https://github.com/jamesjjk/loopback-component-passport

from loopback-component-passport.

gustavomick avatar gustavomick commented on August 19, 2024

trying to understand here.. why do we need two tokens stored in two diferent places? .. thanks!

from loopback-component-passport.

amok avatar amok commented on August 19, 2024

@jamesjjk thank you, works for me.

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

@gustavomick can you expand?

from loopback-component-passport.

gustavomick avatar gustavomick commented on August 19, 2024

@jamesjjk

  1. i used both original and your solution but req.accessToken is still undefined after redirect (using setAccessToken:true). its ok to say that would be filled as facebook strategy? (req.user is filled)
    2 ) how do i read (after redirect) info accessToken filled on passport-configurator.
    thanks

from loopback-component-passport.

gustavomick avatar gustavomick commented on August 19, 2024

@jamesjjk @gshireesh okay after bbt2 .. i noticed that options.cookie must be true on yours, why isn't default option? thanks.

from loopback-component-passport.

julien-sarazin avatar julien-sarazin commented on August 19, 2024

@superkhau What is the state of this issue?

from loopback-component-passport.

jamesjjk avatar jamesjjk commented on August 19, 2024

@gustavomick Its simply a fix that @gshireesh kindly implemented, and I had done a similar job prior and decided to extend, yes it should be a default option - feel free to implement. We are just community members implementing a solution for these issues.

from loopback-component-passport.

julien-sarazin avatar julien-sarazin commented on August 19, 2024

@jamesjjk Thanks a lot. I don't want to be pushy but is there any pending PR?

from loopback-component-passport.

tiagolr avatar tiagolr commented on August 19, 2024

Thank you @bryannaegele your solution works really well.

from loopback-component-passport.

dineshvgp avatar dineshvgp commented on August 19, 2024

@bryannaegele @tiagolr I just copied those code and pasted it under boot directory by saving it as set-remove-cookie.js. But it is not working. Am I doing anything wrong or missing something?

from loopback-component-passport.

tiagolr avatar tiagolr commented on August 19, 2024

Well i place it pretty much at the end of boot scripts, after the following middleware:

  app.use(loopback.context());
  app.use(loopback.token());
  app.disable('x-powered-by');

edit - oops, wrong answer let me check it.

from loopback-component-passport.

tiagolr avatar tiagolr commented on August 19, 2024

I actually moved those remote hooks to inside common/model/user.js file.

Try using the loopback.context() and loopback.token() middleware, see if it that is what's causing the problem.

from loopback-component-passport.

dineshvgp avatar dineshvgp commented on August 19, 2024

@tiagolr I added app.use(loopback.context()); above

app.middleware('auth', loopback.token({
  model: app.models.accessToken
}));

and my common/model/user.js looks

module.exports = function(user) {
    user.afterRemote('logout', function(context, result, next) {
      console.log("====checking=======");
      var res = context.result;
      res.clearCookie('access_token');
      res.clearCookie('userId');
      return next();
    });
};

and in server/server.js I have this

//this part works fine  
app.get('/auth/logout', function (req, res, next) {
  req.logout();
  res.redirect('/');
});

still remote hook doesn't work.

from loopback-component-passport.

tiagolr avatar tiagolr commented on August 19, 2024

Does the console log anything? I'm using default 'users/api/login' and '/api/users/logout' from the component explorer. What is the error?

from loopback-component-passport.

rajeshi2i avatar rajeshi2i commented on August 19, 2024

@tiagolr I had the same problem and I didn't use api login and just learnt why remote hook is actually for. Thanks a lot.

from loopback-component-passport.

dineshvgp avatar dineshvgp commented on August 19, 2024

@tiagolr @RAJESHI2IT Thanks. That was the problem. It is works great if I use API login.

from loopback-component-passport.

jmwohl avatar jmwohl commented on August 19, 2024

@dineshi2it Sounds like you sorted things out, but regarding this:

module.exports = function(user) {
    user.afterRemote('logout', function(context, result, next) {
      console.log("====checking=======");
      var res = context.result;
      res.clearCookie('access_token');
      res.clearCookie('userId');
      return next();
    });
};

The line var res = context.result; should read var res = context.res;. If you're using the example provided way up there by @bryannaegele, that's the issue... after that change, logging out via the API will also clear the cookies.

from loopback-component-passport.

bryannaegele avatar bryannaegele commented on August 19, 2024

@jmwohl Good catch. I updated the example.

from loopback-component-passport.

yanalavishnu avatar yanalavishnu commented on August 19, 2024

Based on the code local config should be done like this

"local": {
  "provider": "local",
  "module": "passport-local",
  "usernameField": "username",
  "passwordField": "password",
  "authPath": "/api/users/login",
  "callbackPath": "/api/users/login/callback",
  "failureRedirect": "/local",
  "setAccessToken": true,
  "session" : true,
  "callbackHTTPMethod": "post"
}

from loopback-component-passport.

elropero avatar elropero commented on August 19, 2024

I've spent the last few days banging my head against this issue. I think it all just clicked for me, but wanted to recap for newcomers.

  1. The afterRemote('login') solution will only work if you adjust your providers.json to use /api/users/login (as opposed to the sample which uses /auth/local). When you use /auth/local the remote hook will NOT trigger (because you are not calling a remote method on the users model).

For this solution, to remove the cookies on logout you could theoretically make sure the caller calls directly to /api/users/logout and pass access_token, though I've run into other pitfalls there. So, I've left the GET /auth/logout route in place from the example and added the following cookie cleanup code:

app.get('/auth/logout', function (req, res, next) {
    if (!req.accessToken) return res.sendStatus(401); //return 401:unauthorized if accessToken is not present
    app.models.person.logout(req.accessToken.id, function(err) {
      if (err) return next(err);
      // Clear the session cookies
      res.clearCookie('access_token');
      res.clearCookie('userId');
      res.redirect('/'); //on successful logout, redirect
    });
});
  1. Alternatively, you can use the solution collaborated on by @jamesjjk and @julien-sarazin -- which lets you keep the sample providers.json in place and will set the access_token cookie for you as part of the response (from within our beloved passport-configurator.js). There are a few variations on this theme but this commit from @jamesjjk's repo seems best:
    jamesjjk@3b3f147
  • Bear in mind that for this solution you still have to manually remove the cookies -- you can use the same solution as above.

I feel either of these solutions is suboptimal, but at least here's something workable. Hope this saves the next person to arrive at this thread a couple of days.

from loopback-component-passport.

shuhankuang avatar shuhankuang commented on August 19, 2024

How can I get the auth-local work example, Now I can't get the accountToken from req.* .

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

I got to the same conclution after 2 days hitting my head against my laptop. If I don't have any remote hook called /auth/local how can this work?, I supposed passport-local strategy automatically posted the remote hook via providers.json which I think it does it. but I'm not very sure about it, so, I can see there are still problems with this component, so would be easier to use passport alone as it's supposed to be used normally with express? And maybe keep 2 authentication models, the passport based and the accesstoken based.

What's the fix for this issue?
I have this in my custom user account (smart_account.js)

module.exports = function(SmartAccount) {
  SmartAccount.beforeRemote('login', function(context,  accessToken, next){
    console.log('> remote hook triggered...');
    var res = context.res;
    var req = context.req;

    if (accessToken != null) {
      if (accessToken.id != null) {
        res.cookie('access_token', accessToken.id, {
          signed: req.signedCookies ? true : false,
          maxAge: 1000 * accessToken.ttl
        });
        res.cookie('userId', user.id.toString(), {
          signed: req.signedCookies ? true : false,
          maxAge: 1000 * accessToken.ttl
        });
      }
    }
    return next();
  });
};

and this is my providers.json configuration:

{
  "local": {
    "provider": "local",
    "module": "passport-local",
    "usernameField": "email",
    "passwordField": "password",
    "authPath": "/api/smart_account/login",
    "successRedirect": "/app",
    "failureRedirect": "",
    "failureFlash": true,
    "setAccessToken": true,
    "session" : true,
    "callbackHTTPMethod": "post"
  }
}

When I attempt to login from /login view I receive from the server:
{"id":"TillT7thnNhKEFE3BVWWEFHn2uoH33Daa9M0QO4synYNNUyKmJzwLCE33zsqke8f","ttl":1209600,"created":"2016-06-26T23:43:08.930Z","userId":"577068272aef5ba52800a3f8"}
userId is correct at last but I'm not redirected to /app , when I try to access to /app I got redirected to /login, this is my route for /app
What am I missing here to successfully log into my system?

app.get('/app', ensureLoggedIn('/login'), function(req, res, next) {
  res.render('private/app.ejs', {
    user: req.user,
    url: req.url
  });
});

I also found this article but seems to be a full authentication solution that basically I could aply and remove passport-loopback component as its apparently only usefull for external login, but if I modify my app with the instructions in that article I'm afraid I'll break passport functionality please HELP!!
article -> http://blog.digitopia.com/tokens-sessions-users/

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

I found the way to get passport installed and running using passport plugin as standalone and removed loopback-passport-component of course with a local strategy setup but totally ready to use 3rth party login as well , basically I got express session object access and serialize the token received after req.login procedure which is the standard loopback procedure to control access to the API.
So, due to the loopback component existent issues and the relatively differences between docs and examples I think I took the best choice in order to advance on this and solve the session persistency and MVC pattern support. if anyone can debate on this, is totally welcome so maybe we could improve the solution.

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

I'm sorry to insist on this, but I have a question to @julien-sarazin, the access_token stored in the cookies is hashed. How can I use it? should I decript/dehash the access_token first before sending the requests to my api server? or should I just send it like it is (hashed) and loopback will dehash the access_token for me? any docs about it?

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

Dear group, I'm still facing issues with this passport aproach even with the @julien-sarazin repository, after I successfully login I enabled the security debug mode to see why I get DENY response in every request made to the API.
The login works and I see in the browser cookies
access_token: ""s:Qte2qXpncpqe9vi9LduF78FjjMiCFrIGXGVBV4Uh8a1IelylFtgFdQj1xmKrFNGG.elA1qIs/QmUvaFYhx+lvn6jocYcPzQU2HOrsWUVAk1M""
and also connect.sid and userId all signed or crypted.
So I added 4 custom roles and test the ACL access using the API explorer directly and I successfully got access to all granted methods.
In the application ater I login and get redirected to the privated area and all cookies are available in the browser I sent an API request and this is what I got:

loopback:security:access-context accessType READ +1ms
  loopback:security:access-context accessToken: +0ms
  loopback:security:access-context   id "$anonymous" +1ms
  loopback:security:access-context   ttl 1209600 +0ms
  loopback:security:access-context getUserId() null +1ms
  loopback:security:access-context isAuthenticated() false +0ms

So if passport works I had to receive a respond like this:

loopback:security:access-context ---AccessContext--- +0ms
  loopback:security:access-context principals: +1ms
  loopback:security:access-context principal: {"type":"USER","id":"579be72e51e3c01d8a5da02e"} +0ms
  loopback:security:access-context modelName sentinel_account +0ms
  loopback:security:access-context modelId undefined +0ms
  loopback:security:access-context property find +0ms
  loopback:security:access-context method find +1ms
  loopback:security:access-context accessType READ +0ms
  loopback:security:access-context accessToken: +1ms
  loopback:security:access-context   id "WYl6TccBZ882lZNiaiCHjUMHzSj0l9OfAfFPjeMWWBGhG7pz1OZjGwPTf65HCF8J" +0ms
  loopback:security:access-context   ttl 1209600 +0ms
  loopback:security:access-context getUserId() 579be72e51e3c01d8a5da02e +2ms
  loopback:security:access-context isAuthenticated() true +0ms

Clearly the cookies and the repository are not doing anything at all over the API but passport granted access on LOGIN and successfully redirected to the private area.
So my concern here is how can I have this working ???? so, also in my request headers I see:

X-Access-Token: s:Qte2qXpncpqe9vi9LduF78FjjMiCFrIGXGVBV4Uh8a1IelylFtgFdQj1xmKrFNGG.elA1qIs/QmUvaFYhx+lvn6jocYcPzQU2HOrsWUVAk1M

So what's left to check is my server.js configuration:

'use strict';

var loopback = require('loopback');
var boot = require('loopback-boot');
var app = module.exports = loopback();
var bodyParser = require('body-parser');
var cookieParser = require('cookie-parser');
var session = require('express-session');
var flash = require('express-flash');
var secret = require('../config/secret.json').cookieSecret;

// Passport configurators..
var loopbackPassport = require('loopback-component-passport');
var PassportConfigurator = loopbackPassport.PassportConfigurator;
var passportConfigurator = new PassportConfigurator(app);

// attempt to build the providers/passport config
var config = {};
try {
  config = require('../config/passport.json');
} catch (err) {
  console.trace(err);
  process.exit(1); // fatal
}

// to support JSON-encoded bodies
app.middleware('parse', bodyParser.json());
// to support URL-encoded bodies
app.middleware('parse', bodyParser.urlencoded({
  extended: true,
}));

// The access token is only available after boot
app.middleware('auth', loopback.token({
  model: app.models.AccessToken
}));

app.middleware('session:before', cookieParser('secret'));
app.middleware('session', session({
  secret: 'secret',
  saveUninitialized: true,
  resave: true
}));
passportConfigurator.init();

boot(app, __dirname);

// We need flash messages to see passport errors
app.use(flash());

passportConfigurator.setupModels({
  userModel: app.models.sentinel_account,
  userIdentityModel: app.models.sentinel_identity,
  userCredentialModel: app.models.sentinel_credential
});
for (var s in config) {
  var c = config[s];
  c.session = c.session !== false;
  passportConfigurator.configureProvider(s, c);
}

require('../config/routes.js')(app);

app.start = function() {
  // start the web server
  return app.listen(function() {
    app.emit('started');
    var baseUrl = app.get('url').replace(/\/$/, '');
    console.log('Web server listening at: %s', baseUrl);
    if (app.get('loopback-component-explorer')) {
      var explorerPath = app.get('loopback-component-explorer').mountPath;
      console.log('Browse your REST API at %s%s', baseUrl, explorerPath);
    }
  });
};

// start the server if `$ node server.js`
if (require.main === module) {
  app.start();
}

Please can someone give me a hand on this? I have over 2 months trying to figure this out and I'm about to quit using all of this.
regards.

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

any thoughts?? can someone give me a hint or a hand?? please...

from loopback-component-passport.

elropero avatar elropero commented on August 19, 2024

Hey @hackerunet -- I went through a similarly frustrating process getting this component to behave as I liked. Like @julien-sarazin I forked the repo and customized it to do what I needed.

Could you create a public repo that demonstrates your specific issue? Would be easier for myself and/or others on this thread to debug. Also, the problem may make itself obvious if you try to create a trivial example that reproduces the issue.

from loopback-component-passport.

elropero avatar elropero commented on August 19, 2024

I hear you @hackerunet. I know they have been working hard on 3.0, I hope as you do that some of the documentation gaps will be filled in. A lot of the docs are decent, and I don't think this passport module is indicative of the broader set. However, this module has caused a lot of head-scratching from those on this thread. Agree that without the community it would have been very difficult to get things up and running. Good luck!

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

Thank you andrew. Well, that's why is a great community, people like you
are really y worried about strongloop programmers. Thanks a lot.
El 03/08/2016 07:10, "Andrew Roper" [email protected] escribió:

I hear you @hackerunet https://github.com/hackerunet. I know they have
been working hard on 3.0, I hope as you do that some of the documentation
gaps will be filled in. A lot of the docs are decent, and I don't think
this passport module is indicative of the broader set. However, this module
has caused a lot of head-scratching from those on this thread. Agree that
without the community it would have been very difficult to get things up
and running. Good luck!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
#57 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AA2xqJN8f1sWvG7HZ1LqKp-kFIBQyhRyks5qcFfXgaJpZM4EGysp
.

from loopback-component-passport.

dakotahNorth avatar dakotahNorth commented on August 19, 2024

@hackerunt ... that is awesome that you got it to work. So far I have been unsuccessful. Can you please provide details of what you did to get this working?

from loopback-component-passport.

dakotahNorth avatar dakotahNorth commented on August 19, 2024

Following @hackerunet note above, I used @jamesjjk "loopback-component-passport": "git+https://github.com/jamesjjk/loopback-component-passport.git" and have been able to get it to work 90% of the way. The last remaining issue is that REST based calls for local logins don't authenticate.

Facebook and Google (both logging in and REST based calls) work like a charm ... and local logins work except for when I login with a local user and use the access_token to make a REST base call.

Any help would be greatly appreciated!

from loopback-component-passport.

dakotahNorth avatar dakotahNorth commented on August 19, 2024

Note above about Facebook and Google both working like a charm ... they work if I force the cookies to be written not to be signed. So I forced signed to be false in the code below. Therefore, the token that is set can be used directly in the REST call. Otherwise ... I get authentication failed.

 function addCookies(req, res, user_id, access_token, ttl) {
 res.cookie('access_token', access_token,
    {
      signed: req.signedCookies ? true : false,
      // maxAge is in ms
      maxAge: 1000 * ttl
    });
   res.cookie('userId', user_id.toString(), {
   signed: req.signedCookies ? true : false,
  maxAge: 1000 * ttl
});

This issue goes into the ajax call that uses the token: #176

from loopback-component-passport.

dakotahNorth avatar dakotahNorth commented on August 19, 2024

Hey ... @hackerunet, any chance to upload that configuration?

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

Yes. I've been sick and not be able to open up my laptop again, ill upload
it as sooners as i get better.
El 13/09/2016 12:21, "Dakotah North" [email protected] escribió:

Hey ... @hackerunet https://github.com/hackerunet, any chance to upload
that configuration?


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
#57 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AA2xqEcab2nEJkscvxdIZkv0mrFdSrDbks5qps2UgaJpZM4EGysp
.

from loopback-component-passport.

dakotahNorth avatar dakotahNorth commented on August 19, 2024

Feel better and thanks!

from loopback-component-passport.

hackerunet avatar hackerunet commented on August 19, 2024

// Passport Configuration for Local provider

{
"local": {
"provider": "local",
"module": "passport-local",
"usernameField": "email",
"passwordField": "password",
"authPath": "/api/account/login",
"successRedirect": "/private",
"failureRedirect": "/login",
"failureFlash": true,
"setAccessToken": true,
"session" : true,
"callbackHTTPMethod": "post",
"flashResponse":true,
"cookie":true
}

On Tue, Sep 13, 2016 at 9:28 PM, Dakotah North [email protected]
wrote:

Feel better and thanks!


You are receiving this because you were mentioned.
Reply to this email directly, view it on GitHub
#57 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AA2xqEo11P-jKQxzAP7NvhZFkbyjQEw4ks5qp02lgaJpZM4EGysp
.

from loopback-component-passport.

dakotahNorth avatar dakotahNorth commented on August 19, 2024

Awesome ... thanks!

Cleared up all of the issues except for 1.

Rest based calls.

I discuss this over at #176. Basically, from the code below from passport-configurator.js, the cookies are being set as signed:

 function addCookies(req, res, user_id, access_token, ttl) {
 res.cookie('access_token', access_token,
     {
       signed: req.signedCookies ? true : false,
       // maxAge is in ms
       maxAge: 1000 * ttl
     });
 res.cookie('userId', user_id.toString(), {
   signed: req.signedCookies ? true : false,
   maxAge: 1000 * ttl
 });
 }

But REST isn't expecting a signed call and therefore tells me that authorization failed.

I set up tokens as such

app.middleware('session:before', loopback.cookieParser(app.get('cookieSecret'))); 
app.middleware('session', loopback.session({
   secret: 'cookieSecret',
   saveUninitialized: true,
   resave: true,
 }));

from loopback-component-passport.

chkuendig avatar chkuendig commented on August 19, 2024

Got it to work thanks to the branch of @jamesjjk - this is really something which should be fixed in mainline (or some easy explanation on how to access /api endpoints with the connect-sessions from passport in combination with the passport-local package)

from loopback-component-passport.

jdschreck avatar jdschreck commented on August 19, 2024

I have the following related problem... We have multiple services using passport authentication
with LDAP. Some use loopback and others don't. If a user logs into a loopback project they get
both the session and the access token and things are good. But if a user logs into a non-loopback
project first they obtain the passport session but not the access token. Is there some way that
when the user then comes to a loopback server with a valid passport session that the access token can be created?

from loopback-component-passport.

jdschreck avatar jdschreck commented on August 19, 2024

I have made some progress on this by using the code suggested above to use res.cookie, however,
it does not work for the immediate call but rather for the next call. I am presuming that this is
because setting in on res does not take effect until that response goes back to the browser and the
browser sends the new signed cookie with the the next request. Any ideas on how I can get this to take effect right away?

from loopback-component-passport.

stale avatar stale commented on August 19, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

from loopback-component-passport.

stale avatar stale commented on August 19, 2024

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.

from loopback-component-passport.

michaelfreund avatar michaelfreund commented on August 19, 2024

Reopening, as of today this is still not working. @superkhau @raymondfeng @bajtos Please, could you guys take a look or assign or mark as deprecated/unsupported? Thank you. @bajtos Maybe this has something to do with https://github.com/strongloop/loopback-context/issues?

from loopback-component-passport.

bajtos avatar bajtos commented on August 19, 2024

@michaelfreund I don't think this is related to loopback-context. I skimmed through the comments above and my understanding is that local login/logout endpoints are not setting/clearing the authentication cookie correctly. The built-in User model (/api/users/login) does not set cookies, this is by current design. If there are different endpoints provided by loopback-component-passport and they are not setting the cookie correctly, then it is probably a bug in the way how these endpoints are implemented.

I am afraid my knowledge of this component is pretty minimal and therefore I don't know how to help you.

from loopback-component-passport.

michaelfreund avatar michaelfreund commented on August 19, 2024

@bajtos That is correct. I know that the built-in model does not support cookie handling. Remote methods are also difficult to get up and running. We have been working on a solution that allows you to define a custom callback for Local Auth without breaking existing applications. We will also send a pull request for the email verification problem using a custom email verification callback.

from loopback-component-passport.

ataft avatar ataft commented on August 19, 2024

Would love to see @jamesjjk fork integrated in. In addition to this issue, it also adds/fixes customCallback to the local login, which is needed.

if (authType === 'local' || authType === 'ldap'){
    var authCallback = options.customCallback || defaultCallback;
    self.app.post(authPath, authCallback)

from loopback-component-passport.

stale avatar stale commented on August 19, 2024

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

from loopback-component-passport.

stale avatar stale commented on August 19, 2024

This issue has been closed due to continued inactivity. Thank you for your understanding. If you believe this to be in error, please contact one of the code owners, listed in the CODEOWNERS file at the top-level of this repository.

from loopback-component-passport.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.