passport-google-auth + aws cognito + nodejs - node.js

I am using passport-google-auth to authenticate google users, and it returns me access_token that I am using to get aws Cognito credentials, but it throws an error:
NotAuthorizedException: Invalid login token. Not a valid OpenId Connect identity token.
my code snippet:
passport.use(new GoogleStrategy(googleDeveloperDetails, getUserDetails));
app.get("/auth/google", passport.authenticate("google", { scope: ['email'] }));
var authGoogle = passport.authenticate("google", {
failureRedirect: "/auth/google"
});
app.get("auth/google/callback", authGoogle, controller.successRedirect);
getUserDetails = function(accessToken, refreshToken, params, profile, done) {
profile.token = accessToken;
done(null, profile);
}
googleDeveloperDetails = {
clientID: "google cleint ID",
clientSecret: "google client secret",
callbackURL: "https://localhost:3000/auth/google/callback",
profileFields: ["emails", "profile"]
}

Solved
Solved by using params.id_token which is received from Google.
Google passport returns accessToken, refreshToken and params.id_token, after searching and reading open-id-connect providers I got the solution.
Here's the solution:
passport.use(new GoogleStrategy(googleDeveloperDetails, getUserDetails));
app.get("/auth/google", passport.authenticate("google", { scope: ['email'] }));
var authGoogle = passport.authenticate("google", {
failureRedirect: "/auth/google"
});
app.get("auth/google/callback", authGoogle, controller.successRedirect);
getUserDetails = function(accessToken, refreshToken, params, profile, done) {
if(profile.provider == "google") {
// params.id_token to be used to get cognito credentials
profile.token = params.id_token;
} else {
profile.token = accessToken;
}
done(null, profile);
}
googleDeveloperDetails = {
clientID: "google cleint ID",
clientSecret: "google client secret",
callbackURL: "https://localhost:3000/auth/google/callback",
profileFields: ["emails", "profile"]
}

Related

How to use passport.js github strategy to get emails of users instead of null

I successfully got the user details but the email field is null.After some time got to know that I need to fetch it from "https://api.github.com/user/emails".I used axios and also provided accesstoken as header but it is giving me "▼♥��A�#►���\�%♥+=y��5"V↔ubWevW�迧F�¶◄t��☻�%)H�ɢ�k��♥葩$,�7↓�H�↔?��^Z�k�r���:��x�▬♣▬NP������҇�C�v�C▼o.�pK~☺" instead of emails.
passport.use(new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "/callbackurl"
},
function(accessToken, refreshToken, profile, done) {
User.findOrCreate({ githubId: profile.id }, function (err, user){ //I am using mongoose-findorcreate npm
axios.get('https://api.github.com/user/emails', {
headers: {
"Authorization": "Bearer "+ accessToken,
}
}).then((res)=>{
console.log(res.data);
})
return done(err, user);
});
}
));
It's because you have not specified scope inside your strategy so Inside your github Strategy , also include scope key:
scope: ["user:email"],
As:
`new GitHubStrategy({
clientID: process.env.GITHUB_CLIENT_ID,
clientSecret: process.env.GITHUB_CLIENT_SECRET,
callbackURL: "/callbackurl",
scope: ["user:email"]
}`

TypeError: MicrosoftStrategy is not a constructor

I'm trying to authenticate my web app with Passport Microsoft. Below is my code:
const MicrosoftStrategy = require('passport-microsoft').MicrosoftStrategy
const passport = require("passport")
passport.use(new MicrosoftStrategy({
clientID: process.env.REACT_APP_MICROSOFT_APP_ID,
clientSecret: process.env.REACT_APP_MICROSOFT_APP_SECRET,
callbackURL: "/auth/microsoft/callback",
scope: ['user.read'],
tenant: 'common',
authorizationURL: 'https://login.microsoftonline.com/common/oauth2/v2.0/authorize',
tokenURL: 'https://login.microsoftonline.com/common/oauth2/v2.0/token',
},
function(accessToken, refreshToken, profile, done) {
return done(null, profile)
}
))
passport.serializeUser((user,done) => {
done(null, user)
})
passport.deserializeUser((user,done) => {
done(null, user)
})
This is my error:
TypeError: MicrosoftStrategy is not a constructor
Per the doc, change this:
const MicrosoftStrategy = require('passport-microsoft').MicrosoftStrategy
to this:
const MicrosoftStrategy = require('passport-microsoft').Strategy;

How to make Passport Google OAuth2.0 work with react-google-login?

My app was using Passport Google OAuth2.0, but I found out that I needed to get a response on the front-end to set the state of a custom hook that grants access to the private routes and that didn't seem possible with Passport, thus I came across this react-google-login npm package, which allows me to define an onSuccess callback.
Now, is it possible to make this React package work with Passport Google OAuth strategy without conflicts? I want Passport to keep handling user creation on the database and generating JWT token. I just have no idea how to make them communicate with each other in such way that I can get to the onSuccess callback.
My Google Strategy and authentication routes are exactly like this:
passport.js
passport.use(
new GoogleStrategy(
{
clientID: process.env.GOOGLE_CLIENT_ID,
clientSecret: process.env.GOOGLE_CLIENT_SECRET,
callbackURL: `${serverUrl}${process.env.GOOGLE_CALLBACK_URL}`,
},
function (accessToken, refreshToken, profile, cb) {
User.findOrCreate(
{ googleId: profile.id },
{ first_name: profile.displayName, email: profile._json.email },
function (err, user) {
return cb(err, user);
}
);
}
)
);
auth.js
router.get(
"/google",
passport.authenticate("google", {
scope: ["email", "profile"],
})
);
const clientUrl =
process.env.NODE_ENV === "production"
? process.env.CLIENT_URL_PROD
: process.env.CLIENT_URL_DEV;
router.get(
"/google/movie-log",
passport.authenticate("google", {
failureRedirect: clientUrl + "/login",
session: false,
}),
(req, res) => {
const token = req.user.generateJWT();
res.cookie("access_token", token, { httpOnly: true, sameSite: true });
res.redirect(clientUrl + "/diary");
}
);
module.exports = router;
The React component:
Login.js
function handleSuccess(response) {
authContext.setIsAuthenticated(true);
navigate(state?.path || "/diary");
console.log("Successfully authenticated");
}
function handleFailure(response) {
console.log("Authentication failed");
}
<GoogleLogin
clientId="my client ID"
uxMode="redirect"
scope="profile email"
redirectUri="http://localhost:5000/auth/google/movie-log"
onSuccess={handleSuccess}
onFailure={handleFailure}
cookiePolicy={"single_host_origin"}
/>

Passport with google-outh strategy

I am creating API for login with google & login with facebook
whenever I call API URL I got error :
"TypeError: OAuth2Strategy requires a verify callback"
I am using local server for testing ,
Here is my code to implement google-outh-strategy with node.js
clientID: "clientId",
clientSecret: "clientsecret",
callbackURL: "http://localhost:3001/",
passReqToCallback: true
},
function (request, accessToken, refreshToken, profile, done) {
console.log(refreshToken);
console.log(accessToken);
console.log(profile);
done(null, profile)
}
));
Here is my references Docs for it :
http://www.passportjs.org/packages/passport-google-oauth2/

Save accessToken to local storage using passport-facebook

I'm new to MEAN Stack, I'm having trouble saving passport-facebook accessToken to localStorage. How do I do this? Below is my setup.
passport.use(new FacebookStrategy({
clientID: passport_config.facebook.clientID,
clientSecret: passport_config.facebook.clientSecret,
callbackURL: passport_config.facebook.callbackURL
},
function(accessToken, refreshToken, profile, done) {
FBAccount.findOne({fbId : profile.id}, function(err, oldUser){
if(oldUser){
done(null,oldUser);
}else{
var newUser = new FBAccount({
fbId : profile.id ,
name : profile.displayName
}).save(function(err,newUser){
if(err) throw err;
console.log(newUser);
done(null, newUser);
});
}
});
}
));
Try this
var localStorage = require('localStorage')
localStorage.setItem('accessToken', accessToken);
FBAccount.findOne({ ....
You can also add token in the cookies by some middleware like
passport.use(new FacebookStrategy({
clientID: '566950043453498',
clientSecret: '555022a61da40afc8ead59c6c26306ed',
callbackURL: 'http://www.localhost:3000/auth/facebook/callback'
}, function(accessToken, refreshToken, profile, done) {
console.log("hello " + profile.displayName);
done(null);
}
));
//Authentication
app.get('/auth/facebook', passport.authenticate('facebook'));
router.get('/auth/facebook/callback', passport.authenticate('facebook', {
failureRedirect: '/login?failedSocial=facebook'
}), auth.authCallback);
and in auth service
exports.authCallback = function (req, res) {
res.res.cookie('token', JSON.stringify(req.user.token));
res.redirect('/');
}

Resources