Comments (8)
Hi @darkterra, can this issue finally be closed?
from fastify-passport.
Can you provide a minimal reproducible example?
from fastify-passport.
Hello @mcollina,
Yes see this piece of code ("./routes/userR" => piece of code on my precedent post) :
'use strict'
const { readFileSync } = require('fs');
const { join } = require('path');
const fastify = require('fastify');
const passport = require('fastify-passport');
const secureSession = require('fastify-secure-session');
function build(opts = {}) {
const app = fastify(opts);
// --- plugins (from the Fastify ecosystem) ---
app.register(secureSession, { key: readFileSync(join(__dirname, '..', 'secret-key')) })
app.register(passport.initialize());
app.register(passport.secureSession())
// --- routes ---
app.register(require('./routes/userR'));
return app;
}
module.exports = build;
On the Front-End side, it's a simple button in a React WebApp :
oauthLogin = () => {
window.location.href = `${process.env.REACT_APP_API_URL}/get-in/google`
}
<CardActions className={classes.actions}>
<Button variant="contained" color="secondary" size="large" onClick={this.oauthLogin}>
<FontAwesomeIcon icon={faGoogle} className="faButton" /> Log in with Google
</Button>
</CardActions>
from fastify-passport.
The reason of something I can just run (after inserting secrets) is that otherwise it would take me too much effort to debug this.
from fastify-passport.
Ok.
npm init
npm i fastify fastify-passport fastify-secure-session passport-google-oauth20
./node_modules/.bin/secure-session-gen-key > secret-key
index.html :
<html>
<head>
<title>Test Fastify Passport</title>
</head>
<body>
<Button onClick="oauthLogin()">Login with Google</Button>
<script>
function oauthLogin() {
console.log('oauthLogin fired...');
window.location.href = 'http://localhost:3001/get-in/google';
}
</script>
</body>
</html>
server.js :
'use strict'
const { readFileSync } = require('fs');
const { join } = require('path');
const fastify = require('fastify')({ logger: true });
const passport = require('fastify-passport');
const secureSession = require('fastify-secure-session');
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
const PORT = 3001;
const BASE_URL = 'http://localhost';
const CLIENT_ID = 'SET HERE YOUR CLIENT_ID';
const CLIENT_SECRET = 'SET HERE YOUR CLIENT_SECRET';
const CALLBACK = `${BASE_URL}:${PORT}/auth/google/callback`;
// --- plugins (from the Fastify ecosystem) ---
fastify.register(secureSession, { key: readFileSync(join(__dirname, 'secret-key')) })
fastify.register(passport.initialize());
fastify.register(passport.secureSession())
console.log('GoogleStrategy add to Passport');
console.log('CLIENT_ID: ', CLIENT_ID);
console.log('CLIENT_SECRET: ', CLIENT_SECRET);
console.log('CALLBACK: ', CALLBACK);
passport.use('google',
new GoogleStrategy(
{
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: CALLBACK
},
function(accessToken, refreshToken, profile, done) {
console.log('Verify Callback of GoogleStrategy Passport fired...');
console.log('accessToken:', accessToken);
console.log('refreshToken:', refreshToken);
console.log('PROFILE:', profile);
const googleEmail = profile.emails[0].value;
console.log('GoogleUser LogIn... ', googleEmail);
done();
// Never fired -_-
}
)
)
function getInGoogleC (req, res, err, user, status) {
console.log('FastifyPassport Callback of GoogleStrategy Passport fired...');
console.log('err:', err);
console.log('user:', user);
console.log('status:', status);
console.log('getInGoogle finish...');
}
function getCallbackGoogleC (req, res) {
res.redirect(`${BASE_URL}:${PORT}/auth/google/callback?u=${encodeURIComponent(JSON.stringify(req.user))}`)
}
// --- routes ---
const defRoutes = [
{
method: 'GET',
url: `/get-in/google`,
preValidation: passport.authenticate('google', { session: true, scope: ['profile', 'email'] }),
handler: getInGoogleC // Never fired too -_-
},
{
method: 'GET',
url: `/auth/google/callback`,
handler: getCallbackGoogleC // no data into req.user decorator -_-
}
]
// Add all routes into Fastify route system
for (const route of defRoutes) {
fastify.route(route);
}
async function start () {
try {
// await connect(MONGO_URL, OPTIONS);
fastify.listen(PORT, () => {
console.log(fastify.printRoutes());
});
}
catch (e) {
throw e;
}
}
start();
Normally this example is equivalent in a simpler version than the original code.
from fastify-passport.
Hello,
Do you have an idea on the origin of the bug ?
from fastify-passport.
@darkterra I did some tests, your code gives me a TOO_MANY_REDIRECTS
error in chrome, you should user the preValidation
hook also in the callback route to check against the passport strategy.
The code below is a simplified version of yours, and it prints the user correctly, can you check and see if it solves your problem?
'use strict'
const { readFileSync } = require('fs');
const { join } = require('path');
const fastify = require('fastify')({ logger: true });
const passport = require('fastify-passport');
const secureSession = require('fastify-secure-session');
const { Strategy: GoogleStrategy } = require('passport-google-oauth20');
const PORT = 3001;
const BASE_URL = 'http://localhost';
const CLIENT_ID = '...';
const CLIENT_SECRET = '...';
const CALLBACK = `${BASE_URL}:${PORT}/auth/google/callback`;
// --- plugins (from the Fastify ecosystem) ---
fastify.register(secureSession, { key: readFileSync(join(__dirname, 'secret-key')) })
fastify.register(passport.initialize());
//fastify.register(passport.secureSession())
console.log('GoogleStrategy add to Passport');
console.log('CLIENT_ID: ', CLIENT_ID);
console.log('CLIENT_SECRET: ', CLIENT_SECRET);
console.log('CALLBACK: ', CALLBACK);
passport.use('google',
new GoogleStrategy(
{
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
callbackURL: CALLBACK
},
function (accessToken, refreshToken, profile, done) {
console.log('Verify Callback of GoogleStrategy Passport fired...');
console.log('accessToken:', accessToken);
console.log('refreshToken:', refreshToken);
console.log('PROFILE:', profile);
const googleEmail = profile.emails[0].value;
console.log('GoogleUser LogIn... ', googleEmail);
done(null, profile);
}
)
)
passport.registerUserSerializer(async (user) => user.id);
passport.registerUserDeserializer(async (user) => user);
// --- routes ---
const defRoutes = [
{
method: 'GET',
url: `/get-in/google`,
preValidation: passport.authenticate('google', { session: true, scope: ['profile', 'email'] }),
handler: (req, res, err, user, status) => {
console.log('FastifyPassport Callback of GoogleStrategy Passport fired...');
console.log('err:', err);
console.log('user:', user);
console.log('status:', status);
console.log('getInGoogle finish...');
}
},
{
method: 'GET',
url: `/auth/google/callback`,
preValidation: passport.authenticate('google', { session: true }),
handler: (req, res) => {
return res.send(req.user);
}
}
]
// Add all routes into Fastify route system
for (const route of defRoutes) {
fastify.route(route);
}
async function start() {
try {
fastify.listen(PORT, () => {
console.log(fastify.printRoutes());
console.log('Visit: http://localhost:3001/get-in/google');
});
}
catch (e) {
throw e;
}
}
start();
from fastify-passport.
Hello @leorossi, Thank you a lot for your answare, I made a quick test and it's seem to be working !
I just want to do a another test juste to be sure, and then à close this issue ;)
from fastify-passport.
Related Issues (20)
- Duplicate 'passport' decorator error when instantiating multiple Authenticator instances HOT 3
- Add support of 'keepSessionInfo' bool param for strategies HOT 2
- Infinite authentication loop on protected route HOT 3
- Update workflow, update dependencies and release new major HOT 1
- Migrate to `node:test` and `c8` HOT 2
- Protected routes array when registering passport.initalize() HOT 3
- All routes throw an "Invalid CORS origin option" error if used together with @fastify/cors and an async function as origin option HOT 2
- passport-github verify callback never called? HOT 9
- Using fastify-secure-session with openid-client strategy HOT 8
- Failed to serialize user into session HOT 3
- Cannot publish new module HOT 1
- `state` param is not included in the Typescript interface for AuthenticateOptions HOT 1
- Calling Strategy.fail with 2 arguments is misinterpreted by the compiler HOT 8
- How to print custom error message instead of default "Unauthorized" or "Bad request" HOT 2
- Fastify Custom Strategy, redirect method not working - TypeError: res.setHeader is not a function HOT 3
- the user property remains occupied by the type when userProperty is changed HOT 3
- passport types not exists when using ESM + Typescript HOT 1
- @fastify/jwt and @fastify/passport FST_ERR_DEC_ALREADY_PRESENT HOT 1
- using fastify-passport with passport-jwt strategy HOT 2
- Invalid Typings for PassportUser in Typescript HOT 11
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from fastify-passport.