Giter VIP home page Giter VIP logo

Comments (49)

sanandrea avatar sanandrea commented on August 19, 2024 12

npm install --save passport-facebook-token
Then add this entry in providers.json:

"facebook-mobile" : {
    "provider": "facebook-token",
    "module": "passport-facebook-token",
    "strategy": "FacebookTokenStrategy",
    "clientID": "XXXXXXX",
    "clientSecret": "XXXXXXX",
    "callbackPath": "/auth/facebook-token/callback",
    "session" : false,
    "json":true,
    "scope": ["email"]
  }

then you are ready to go with a rest call at /auth/facebook-token/callback?access_token=CAAGqQJa4ShcB...

from loopback-component-passport.

eriklovdahl avatar eriklovdahl commented on August 19, 2024 5

@whispers16 If I understand you correctly, you can set "json": true in you provider config. Doing so will return a JSON object with the access token and user id instead of a cookie.

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024 4

Using passport-facebook-token is very straight forward....just npm install it and add another entry to your providers.json with

    "provider": "facebook-token",
    "module": "passport-facebook-token",
    "strategy": "FacebookTokenStrategy",
    "clientID": "XXXXXXXXXXX",
    "clientSecret": "XXXXXXXXXXXXXXXXXXXXXXXXXX",
    "callbackURL": " /auth/facebook-token/callback",

Since the actual auth is handled by the Facebook Android SDK (which provides your app with a facebook access token) the auth part of passport is irrelevant.

You only need the callback so assuming you define callbackURL in providers.json as /auth/facebook-token/callback you call that URL passing access_token=FB_ACCESS_TOKEN_FROM_FB_SDK_LOGIN to get a loopback cookie with your loopback access token and id

As far as sample android code is concerned, I've only got a rough demo so far (been swamped with work so haven't really touched it since I wrote the post above)

I've set up the token retrieval as an async task within my main app class which implements a listener for the task end.

Basically, user hits fb login button...authenticates with fb...fb returns a token ,we set up a new async task to call the callbackURL above with that token...we read the cookie set by loopback , initialise the LB rest adapter with that access token (using: adapter.setAccessToken()) and copy the userID to the app shared preferences where the Loopback SDK expects to find it.

It's all a bit of a mess so I'll copy the relevant bits (CustomerRepository & Customer are my extended LB SDK models)

Task listener interface

public interface TokenRetrieveEnd {
    void tokenRetrieveEnd(String response);
}

AppActivity Class definition

import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.strongloop.android.loopback.RestAdapter;
import com.strongloop.android.loopback.callbacks.ObjectCallback;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpCookie;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

public class YourAppClassName extends AppCompatActivity implements TokenRetrieveEnd{

    static java.net.CookieManager msCookieManager = new java.net.CookieManager();
    RestAdapter adapter;
    CustomerRepository  custRepo;

FB Login button handler

        callbackmanager = CallbackManager.Factory.create();

        // Set permissions
        LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "user_photos", "public_profile"));

        LoginManager.getInstance().registerCallback(callbackmanager,
                new FacebookCallback<LoginResult>() {
                    @Override
                    public void onSuccess(LoginResult loginResult) {

                        System.out.println("Success");
                        new TokenRetrievalTask(YourAppClassName.this).execute(loginResult.getAccessToken().getToken());

                    }

                    @Override
                    public void onCancel() {
                        Log.d(TAG_CANCEL, "On cancel");
                    }

                    @Override
                    public void onError(FacebookException error) {
                        Log.d(TAG_ERROR, error.toString());
                    }
                });

TokenRetrieval Task

private class TokenRetrievalTask extends AsyncTask<String, String, String> {
        private TokenRetrieveEnd tokenRetrieved;
        public TokenRetrievalTask(TokenRetrieveEnd activityContext) {
            this.tokenRetrieved=activityContext;
        }
        protected String doInBackground(String... tokens) {
            String result="";
            try {
                URL url = new URL("http://loopback.url:3000/auth/facebook-token/callback?access_token=" + tokens[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setInstanceFollowRedirects(false);
                urlConnection.connect();

                Map<String, List<String>> headerFields = urlConnection.getHeaderFields();
                List<String> cookiesHeader = headerFields.get(COOKIES_HEADER);
                System.out.println(urlConnection.getHeaderFields().toString());
                if (cookiesHeader != null) {
                    for (String cookie : cookiesHeader) {
                        msCookieManager.getCookieStore().add(null, HttpCookie.parse(cookie).get(0));

                        if (HttpCookie.parse(cookie).get(0).getName().equalsIgnoreCase("access_token")) {
                            adapter.setAccessToken(java.net.URLDecoder.decode(HttpCookie.parse(cookie).get(0).getValue(),"UTF-8").split("\\.")[0].split(":")[1]);
                        }
                        if (HttpCookie.parse(cookie).get(0).getName().equalsIgnoreCase("userId")) {
                            result=java.net.URLDecoder.decode(HttpCookie.parse(cookie).get(0).getValue(),"UTF-8").split("\\.")[0].split(":")[1];
                        }
                    }
                }
                urlConnection.disconnect();

            }catch(Exception e) {
                String msg = "Messup when calling home";

                Log.e("LoopBack", msg, e);
            }
            return result;
        }

        protected void onPostExecute(String result) {
            SharedPreferences.Editor editor = getApplicationContext().getSharedPreferences(CustomerRepository.SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE).edit();
            String json = new JSONArray().put(result).toString();
            editor.putString(CustomerRepository.PROPERTY_CURRENT_USER_ID, json);
            editor.commit();
            tokenRetrieved.tokenRetrieveEnd("Success");
        }
    }

and the callback

@Override
    public void tokenRetrieveEnd(String response) {
        custRepo.findCurrentUser(new ObjectCallback<Customer>() {
            @Override
            public void onSuccess(Customer customer) {
                if (customer != null) {
                    System.out.println(customer.toMap());
                } else {
                    // anonymous user
                }
            }
            @Override
            public void onError(Throwable t) {
                String msg = "Messed up on Customer Retrieve";
                Log.e("LoopBack", msg, t);
            }
        });
    }

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024 2

This is just off the top of my head for android

Authenticating using the FB sdk should be as simple as using the method described in the FB docs for any other app, getting the code and calling /auth/facebook/callback with the code using HttpClient or something.

That should give you a valid accessToken and userId in the cookie returned.

The problem is with the LoopBack Android SDK which as far as I can see does not let you create a "blank" User and set the accessToken and userId yourself.

So I'm guessing if you need to go down that road you need to write the whole interface yourself.

----------------EDIT----------

Did some reading. It's actually more complex.
FB SDK does not return the code to client apps but only returns a short lived access Token which can be exchanged server side for a long-lived token (seeing as your app secret should only live there).

There is this: https://github.com/drudge/passport-facebook-token

Which I believe will allow passport to auth using the short lived token you receive on your client app from FB if configured right. Need to set it up and see exactly how it works.

This is probably required reading as well.
https://developers.facebook.com/docs/facebook-login/access-tokens/expiration-and-extension

(The following is for android...)

As far as using loopback's SDK is concerned, looking at the source code, it seems as if you can simply define everything as if using local login and (assuming you have solved the previous issues and have a valid access token and user_id in your client app) using:
getRestAdapter().setAccessToken()
and adding PROPERTY_CURRENT_USER_ID with your user_id to the shared preferences.

I have not implemented or tested any of this but it seems like it should allow the SDK to function as if a user was logged in in the past and his credentials cached therefore working as expected from then on.

Maybe one of the maintainers can jump in with more.

I hope this helps to get you on the right track.

I will be needing this functionality soon so once I get started with an implementation I'll share any new findings here.

-------FURTHER EDIT

https://github.com/drudge/passport-facebook-token works fine.

Just set it up in providers.json.

Due to how PassportConfigurator is setup (it expects a redirect to FB/Google etc. and then a callback) you dont need the actual auth path.

Just call the callbackURl (e.g. /auth/facebook-token/callback) passing access_token=YOUR_FB_ACCESS_TOKEN and you will get a response with a cookie set with your LB access_token and user_id.

This answers authenticating on mobile. Haven't got to the part of using this with the LoopBack mobile SDKs yet

----------FINAL EDIT

using:
getRestAdapter().setAccessToken()
and adding PROPERTY_CURRENT_USER_ID with your user_id to the shared preferences.

with the id and token you get from the cookie in the method described above works..

It's native.. But NOTcalling it a hack is a bit of a stretch :)

hope it helps someone. It works for my needs anyway

from loopback-component-passport.

kwiky avatar kwiky commented on August 19, 2024 2

It was fixed by #116

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024 1

Not sure what you mean. Those instructions are for local users.

If you're using facebook to login (or any other 3rd party provider) passport will create a new user if one doesn't exist upon login.

Specifically for FB , passport gets the app_scoped_user_id from FB for your FB app (the one configured with clientID/clientSecret) and checks for a user named facebook.!app_scoped_user_id! . If one exists, it logs you in as that user or it creates it and also creates a facebook useridentity belonging to that user as described here: https://docs.strongloop.com/pages/releaseview.action?pageId=3836277#Third-partylogin(Passport)-Thirdpartylogin

If you want some extra control or to perform some custom tasks upon user creation you can use the normal LB hooks.

As far as the long term FB token is concerned, why do you need it? You are not using the fb token to auth against LB but loopback's own token. The FB token is used momentarily upon login/auth and that's it.

from loopback-component-passport.

lemoncola avatar lemoncola commented on August 19, 2024

+1

from loopback-component-passport.

vincentpotato avatar vincentpotato commented on August 19, 2024

+1 on that

from loopback-component-passport.

loay avatar loay commented on August 19, 2024

Hi @bachirelkhoury
Did you have a look at this document:
https://docs.strongloop.com/display/public/LB/Android+SDK
Also for the authentication part:
https://docs.strongloop.com/display/public/LB/Android+SDK#AndroidSDK-Usersandauthentication

Same for iOS:
https://docs.strongloop.com/display/public/LB/iOS+SDK

For Cross platform, there is the Xamarin SDK:
https://docs.strongloop.com/display/public/LB/Xamarin+SDK

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

@clockworkgr , could you provide a working example of providers.json with passport-facebook-token and other code to authorise mobile app user .

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

@clockworkgr , thanks! I actually have no problem with client-side getting temporary token (I'm not using LB Android SDK, though).
I'm having difficulty of figuring how to integrate passport-facebook-token with loopback-passport and its models (userCredentials, userIdentity, accessToken).

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

Oh ok...TBH I Haven't looked at that part much but i think it just works.

At least for me it correctly creates the facebook-token identity entry for the user etc without doing anything more.

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

@clockworkgr could you copy-paste that part of the code (that, I suppose, goes to server.js) ?

I assume this is the code https://github.com/clockworkgr/remindme/blob/master/server/server.js ?

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

that's what I'm saying...I havent changed anything there from the default passport stuff.

I am however using my fix for using extended models with passport from here: #93

You might want to use @jonathan-casarrubias fork which is more polished than mine

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

@clockworkgr , for me
passportConfigurator.configureProvider(s, c);
gives an error

passport.use(name, new AuthStrategy(_.defaults({

TypeError: AuthStrategy is not a function


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

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

Ah yes...That rings a bell...It's the way passport-facebook-token exports the strategy

In order to keep all your changes in a single place and not modify multiple packages try changing this in passport-configurator.js

 AuthStrategy = require(options.module)[options.strategy || 'Strategy'];

to

  if (options.strategy=="FacebookTokenStrategy") {
    AuthStrategy = require(options.module);
  }else{
    AuthStrategy = require(options.module)[options.strategy || 'Strategy'];
  }

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

Thanks, that works. But still leaves handling user creation in myst
As you suggest : "loopback cookie with your loopback access token and id " . Should I follow these instructions https://docs.strongloop.com/display/public/LB/Logging+in+users to create/login a new user?

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

Also, have you tried implementing getting long term password from Facebook?

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

I had to create custom route handling because for some reason callbackUrl ( "callbackURL": "/auth/facebook-token/callback" ) hasn't registered.

404 Error: Cannot GET /auth/facebook-token/callback?access_token=3242435
at raiseUrlNotFoundError (node_modules/loopback/server/middleware/url-not-found.js:15:17)

UP: Got it. Had to include all fields
"provider": "facebook-token",
"module": "passport-facebook-token",
"strategy": "FacebookTokenStrategy",
"clientID": "XXXX",
"clientSecret": "XXXX",
"callbackURL": "/auth/facebook-token/callback",
"authPath": "/auth/facebook-token",
"callbackPath": "/auth/facebook-token/callback",

from loopback-component-passport.

valentinmaxime avatar valentinmaxime commented on August 19, 2024

OK I managed to make it work
Here the steps I followed :

Step 1 : retrieving a loopback example with passport to have a pre-configured environment

$ git clone [email protected]:strongloop/loopback-example-passport.git
$ cd loopback-example-passport
$ npm install
$ npm install passport-facebook-token

Step 2 : Set the provider file
rename providers.json.template ==> providers.json

change providers.json to
"facebook-token": {
"provider": "facebook-token",
"module": "passport-facebook-token",
"strategy": "FacebookTokenStrategy",
"clientID": "XXXXX",
"clientSecret": "XXXX",
"callbackURL": "/auth/facebook-token/callback"
}

Step 3 : configure passport-facebook-token module
add to server.js
var passport = require('passport');
var FacebookTokenStrategy = require('passport-facebook-token');

passport.use(new FacebookTokenStrategy({
clientID: FACEBOOK_APP_ID,
clientSecret: FACEBOOK_APP_SECRET
}, function(accessToken, refreshToken, profile, done) {
User.findOrCreate({facebookId: profile.id}, function (error, user) {
return done(error, user);
});
}
));

Step 4 : @clockworkgr solution to fix module export
update passport-configurator.js in node_modules/loopback-component-passport/lib :

AuthStrategy = require(options.module)[options.strategy || 'Strategy'];

to

if (options.strategy=="FacebookTokenStrategy") {
AuthStrategy = require(options.module);
}else{
AuthStrategy = require(options.module)[options.strategy || 'Strategy'];
}

Step 5 : start server
node .

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

Wonder why do you need step 3. Is it because you don't use passportConfigurator ?

passportConfigurator.init();

passportConfigurator.setupModels({
userModel: app.models.Customer,
userIdentityModel: app.models.userIdentity,
userCredentialModel: app.models.userCredential
});
// Configure passport strategies for third party auth providers
for (var s in config) {
var c = config[s];
c.session = c.session !== false;
passportConfigurator.configureProvider(s, c);
}

from loopback-component-passport.

valentinmaxime avatar valentinmaxime commented on August 19, 2024

Because I'm lazy.
When I git clone [email protected]:strongloop/loopback-example-passport.git I have it in server.js :

passportConfigurator.setupModels({
    userModel: app.models.user,
    userIdentityModel: app.models.userIdentity,
    userCredentialModel: app.models.userCredential
});
for (var s in config) {
    var c = config[s];
    c.session = c.session !== false;
    passportConfigurator.configureProvider(s, c);
}
var ensureLoggedIn = require('connect-ensure-login').ensureLoggedIn;

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

Guys, how would you set the Role ($authenticated in this particular case) to the user who's logged in through Facebook?

Was easier than I thought. Just added role-resolver.js to /boot with code. I wish it was stated clearly somewhere in the docs. Please, please, do update the docs.

module.exports = function (app) {
  var Role = app.models.Role;
  Role.registerResolver('$authenticated', function (role, context, cb) {
    function reject(err) {
      if (err) {
        return cb(err);
      }
      cb(null, false);
    }
    var userId = context.accessToken.customerid; //using Customer my my custom model based on User
    if (!userId) {
      return reject(); // do not allow anonymous users
    }
    cb(null, true);
  });
};

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

@valentinmaxime I followed the steps you described.
I want to auth the user through an iOS app.

when I send the request to get /auth/facebook-token/callback?access_token=..... i got a cookie with an access_token inside.

Thank you at least the login works :-)

Then I try though the strongloop explorer to get user info based on this access_token I got the following error :

{
"error": {
"message": "Cannot GET /api/users/1?access_token=s%3XXXXXXXXX%20XXXXXX",
"stack": "Error: Cannot GET /api/users/1?access_token=s%3XXXXXXXXX%20XXXXXX"\n at raiseUrlNotFoundError (/app/node_modules/loopback/server/middleware/url-not-found.js:15:17)\n at Layer.handle as handle_request\n at trim_prefix (/app/node_modules/express/lib/router/index.js:312:13)\n at /app/node_modules/express/lib/router/index.js:280:7\n at Function.process_params (/app/node_modules/express/lib/router/index.js:330:12)\n at next (/app/node_modules/express/lib/router/index.js:271:10)\n at SendStream.error (/app/node_modules/serve-static/index.js:120:7)\n at emitOne (events.js:77:13)\n at SendStream.emit (events.js:169:7)\n at SendStream.error (/app/node_modules/send/index.js:245:17)",
"status": 404
}
}

I think it's because I'm using a signed value of the acess_token but I don't know how to unsign the cookie.

Any idea ?

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

What's the %20XXXXXX part?

from loopback-component-passport.

valentinmaxime avatar valentinmaxime commented on August 19, 2024

@grimabe You have to add route to provide an access to the users.
example :

app.get('/signup', function (req, res, next){ ....

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

@skolesnyk

%20XXXXXX

"XX" are placeholder for my access_token.

@valentinmaxime
If I got a cookie with the access_token that's because the user has been created when I sent the facebook-token request. right ? so why do I need a /signup ?
there are already routes defined in the project by default :

screen shot 2015-12-08 at 14 23 40

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

Is that screenshot all your "public" API methods?

If so there is no /users/{id} method to match your:

/users/1?access_token=s%3XXXXXXXXX%20XXXXXX"

request.

Hence the not found error

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

@clockworkgr

no, it was just a sample see below :

screen shot 2015-12-08 at 15 00 59

I'm pretty sure that s%3XXXXXXXXX%20XXXXXX" (value of access_token in the cookie) is signed .
So i'm sending a signed value instead of the unsigned value ? Am I wrong ?

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

not sure if that is your issue, however the relevant code to "unsign" the access_token can be found here:

https://gist.github.com/eugenehp/e45537b73d58db33cd80

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

Ok i guess it's the split function on the "." but as you said it is not fixing the issue :D

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

It's both these lines:
accessTokenId = accessTokenId.split('.')[0];
accessTokenId = accessTokenId.split(':')[1];

(everything after the : and before the . )

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

Although to be honest, something seems wrong with the token you're copy pasting..

the signed token is something like this:

s:ACCESS_TOKEN.SIGNATURE

this urlencodes as
s%3BACCESS_TOKEN.SIGNATURE

the . is a valid url character and thus does not get url encoded

the %20 is a url encoded space character. It shouldn't be there.

If you're only testing your system, output the cookie you get from loopback in your app in a console/log somewhere, it should have the format above...copy the string between : and . ONLY and paste it in the set access token box in the explorer. and try again

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

As you said I tried to log when the cookie is created, I got the following access_token id in the log :

 55RV1EHTJhA88oHOyPk31DfDOUfqCrbIYobJ1o2VYTdyArjkzLQf6CpfY2xhh2EV

and inside the cookie I got this :

 s%3A55RV1EHTJhA88oHOyPk31DfDOUfqCrbIYobJ1o2VYTdyArjkzLQf6CpfY2xhh2EV.cHGPZCx%2F6uWK3y7Fh%2FD78yVVRDOwcGbA0ue%2BPCFOA2A 

So I tried through the explorer with this as token

55RV1EHTJhA88oHOyPk31DfDOUfqCrbIYobJ1o2VYTdyArjkzLQf6CpfY2xhh2EV

And I still got the same error.

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

Do you get an error if you simply try requesting /api/Users/1 no token or nothing? maybe it's something with your LB configuration in general and not with passport

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

It appears to be on every request event POST /api/users with to without token set so.

I just followed @valentinmaxime steps to get Facebook login working first.

from loopback-component-passport.

clockworkgr avatar clockworkgr commented on August 19, 2024

Are you making all these requests through the explorer?

from loopback-component-passport.

grimabe avatar grimabe commented on August 19, 2024

Even from postman or even if I visit example.com/users/ to get the list I got the error.

from loopback-component-passport.

pakoquijano avatar pakoquijano commented on August 19, 2024

@grimabe Did you find a solution to your 404 response error? I have the same issue.

from loopback-component-passport.

buildtheui avatar buildtheui commented on August 19, 2024

@grimabe Hi did you find any solution to the access token problem?? I got the same problem...and strongloop is not accepting the token I get from this strategy...

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

Works for me:
var arr = req.headers["cookie"].split(";");
var at = arr[0].split("=");
var userid = arr[1].split("=");
res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({accesstoken: at[1], userid: userid[1]}));

from loopback-component-passport.

buildtheui avatar buildtheui commented on August 19, 2024

@skolesnyk thank you! sorry I'm new at this, but what specific part do you implement that code in?, all I need is to return a JSON with the facebook profile data and access token to strongloop.

in the providers.json I put a "successRedirect": "/auth/redirect/facebook"
and then in passport.js I put:

app.get('/auth/redirect/facebook', ensureLoggedIn('/'), function(req, res, next) { return res.status(200).json({"access_token": req.signedCookies['access_token'], "user": req.user }); });

and I get the JSON that I want, but the problem is that I'm being redirected to another link, and what I really need is return a JSON from the principal request, and not return a cookie or redirect to another link...

thanks! do you have any idea?

from loopback-component-passport.

buildtheui avatar buildtheui commented on August 19, 2024

@eriklovdahl thanks I didn't know that way, that worked! I'd hacked passport-configurator.js and also worked for me, but this is a cleaner way thanks!

from loopback-component-passport.

hristo-vrigazov avatar hristo-vrigazov commented on August 19, 2024

How to enable google authentication in a similar way? I tried the answer of @sanandrea , just replacing everywhere Facebook with Google, but nothing happens.

from loopback-component-passport.

musghost avatar musghost commented on August 19, 2024

I had a problem with the FacebookTokenStrategy strategy. The application threw this error message: InternalOAuthError: Failed to fetch user profile. Browsing the code and writing a console.log to print the error I realized that it was caused by a GraphMethodException. The console was logging this error: { statusCode: 400, data: '{"error":{"message":"Invalid appsecret_proof provided in the API argument","type":"GraphMethodException","code":100,"fbtrace_id":"GQVRNhI1XNi"}}' }.

After some frustrating hours I found out that I had to set "enableProof":false in the providers.json file. I don't know if I'm missing something or I haven't figured out how this works, but, I wanted to write it hoping that could bring some help to someone that has the same problem.

from loopback-component-passport.

skolesnyk avatar skolesnyk commented on August 19, 2024

@musghost , I think this option isn't required and if not set to true, it won't be used. You've probably first set 'Require App Secret' to YES in your Facebook app settings?

drudge/passport-facebook-token@d98bb85

from loopback-component-passport.

johnshardman avatar johnshardman commented on August 19, 2024

If Facebook is configured to have "Require App Secret" set to Yes, how do we pass the hashed appsecret_proof?

I tried the following, but get "Invalid appsecret_proof provided in the API argument" reported. I can turn off "Requires App Secret" and remove this code, but would like to get this working if possible.

            byte[] key = Encoding.ASCII.GetBytes(app_secret);
            byte[] access_token = Encoding.ASCII.GetBytes(app_access_token);

            var hasher = new HMACSHA256(key);
            byte[] hash = hasher.ComputeHash(access_token);

            arguments.Add("appsecret_proof", Encoding.ASCII.GetString(hash));

            OAuth2Request request = new OAuth2Request(
                "GET",
                new Uri(requestString),
                arguments,
                account);

from loopback-component-passport.

lbcsy avatar lbcsy commented on August 19, 2024

@hristo-vrigazov, have you been able to use passport-google-token yet? If yes, could you share with me?

from loopback-component-passport.

ravitomar7 avatar ravitomar7 commented on August 19, 2024

@whispers16 If I understand you correctly, you can set "json": true in you provider config. Doing so will return a JSON object with the access token and user id instead of a cookie.

You made my day, was stuck since last one week getting it !! Thankyou soo much.

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.