Code Monkey home page Code Monkey logo

Comments (8)

CarleneCannon-Conner avatar CarleneCannon-Conner commented on August 20, 2024 1

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.

Pazaz avatar Pazaz commented on August 20, 2024 1

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.

CarleneCannon-Conner avatar CarleneCannon-Conner commented on August 20, 2024 1

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.

mcollina avatar mcollina commented on August 20, 2024

Please provide a reproducible example.

from fastify-passport.

gasner avatar gasner commented on August 20, 2024
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.

CarleneCannon-Conner avatar CarleneCannon-Conner commented on August 20, 2024

Assignee: @CarleneCannon-Conner

from fastify-passport.

mcollina avatar mcollina commented on August 20, 2024

go for it!

from fastify-passport.

simoneb avatar simoneb commented on August 20, 2024

Closing

from fastify-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.