Comments (8)
Hi @gasner I have been having a look into this issue. Am I right in understanding that you want to call passport.authenticate('local', ...
on a GET request to obtain user data?
I was able to reproduce the Bad Request as per your example. I found that the error only occurs on GET requests where a fastifyPassport.authenticate()
is called passing in passport-local
as a strategy. I then had a look at the this repository to see if any tests were failing, in particular the GET requests and they all appeared to be working, however they used different strategies. This lead me to looking into the strategy used in your example which lives in the passport-local repository. The readme shows this POST example
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
And there are no GET examples.
The readme goes on to point out an example using express. Looking at this code, again I see no examples of GET requests where authenticate is called on passport. The example shows that the GET /login renders a page that allows the user to enter in credentials in a form and by submitting that form the POST /login/password request gets called. It's there that authenticate gets called on passport.
router.post('/login/password', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureMessage: true
}));
From what I have found, it does not look like you can obtain user data by calling passport.authenticate
, passing in passport-local
as a strategy in a GET request. Perhaps another strategy would be more useful.
from fastify-passport.
Ran into this issue myself... it seems that passport.authenticate(...)
is used to validate a username/password primarily, and the result gets stored in req.user. Not sure what authInfo does but I get the same bad request error, so I don't think you should call it regularly, unless this is an oversight/break down somewhere. You'll also see req.isAuthenticated() should return true regardless of a pre-validation hook being added now.
In your normal GET requests you should use req.user, and you can add your own preValidation function to check/redirect.
i.e. (do not take this as best practice)
async function redirectToLogin(req, res) {
if (req.isUnauthenticated()) {
res.redirect(302, '/login'); // or return an error. I use this to redirect to a page to log in with
}
}
fastify.get('/',
{ preValidation: async (req, res) => await redirectToLogin(req, res) },
(req, res) => {
return {
index: true
};
}
)
fastify.post('/login',
{ preValidation: Passport.authenticate('local', { successRedirect: '/', failureRedirect: '/login' }) },
() => { }
);
from fastify-passport.
Thank you @Pazaz for the additional information. The 'Bad Request' is likely coming form the Strategy.prototype.authenticate
function here. It expects both a username and a password to be provided via the body or query in the request.
@gasner I hope our input was helpful. I recommend closing this issue.
from fastify-passport.
Please provide a reproducible example.
from fastify-passport.
const fastify = require("fastify");
const fastifyPassport = require("fastify-passport");
const fastifySecureSession = require("fastify-secure-session");
const LocalStrategy = require("passport-local");
const mongoose = require("mongoose");
const path = require("path");
const fs = require("fs");
mongoose.connect("mongodb://127.0.0.1:27017/", {
useNewUrlParser: true,
useUnifiedTopology: true,
dbName: "test",
});
const Schema = mongoose.Schema;
const userSchema = new Schema(
{
username: {
type: String,
required: true,
unique: true,
},
password: { type: String, required: true },
},
{ timestamps: true }
);
const User = mongoose.model("user", userSchema);
const server = fastify();
server.register(fastifySecureSession, {
key: fs.readFileSync(path.join(__dirname, "secret-key")),
});
server.register(fastifyPassport.initialize());
server.register(fastifyPassport.secureSession());
fastifyPassport.use(
"local",
new LocalStrategy(function (username, password, done) {
User.findOne({ username: username }, function (err, user) {
if (err) {
return done(err);
}
if (!user) {
return done(null, false, { message: "Incorrect username." });
}
return done(null, user);
});
})
);
fastifyPassport.registerUserSerializer(async (user, request) => {
return user.id;
});
fastifyPassport.registerUserDeserializer(async (id, request) => {
let user = await User.findById(id);
return user;
});
server.post("/register", async (req, reply) => {
await User.create({
username: req.body.username,
password: req.body.password,
});
return { a: "hey" };
});
server.post(
"/login",
{
preValidation: fastifyPassport.authenticate("local", {
successRedirect: "/auth",
authInfo: false,
}),
},
() => {}
);
server.get(
"/auth",
{
preValidation: fastifyPassport.authenticate("local", {
authInfo: true,
}),
},
async (req, res) => {
console.log(req, res);
return "Hey";
}
);
server.listen(3000);
Thanks!
from fastify-passport.
Assignee: @CarleneCannon-Conner
from fastify-passport.
go for it!
from fastify-passport.
Closing
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
- `Forbidden` error after getting authorization code from okta using `passport-okta-oauth` library as a strategy HOT 3
- Use session or not as an option HOT 7
- 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.