How to process passport authenticate function in as request handler function - node.js

I am creating a web application based on Node.js and Express 4. I am also using Passportjs and Google OAuth 2 Startegy for authentication.
I am trying to configure my routes in order to process requests.
I have learned that this line work well:
router.get('/signin/google/callback', passport.authenticate('google', {failureRedirect: '/signin'}));
but when I decided to handle the route in the function, application stopped responding:
router.get('/signin/google/callback', function (req, res) {
passport.authenticate('google', {failureRedirect: '/signin'});
});
Do I miss something? thanks in advance

The callback of the Google OAuth function should be something like this:
app.get('/auth/google/callback',
passport.authenticate('google', { failureRedirect: '/login' }),
function(req, res) {
res.redirect('/');
});
The passport.authenticate() is middleware with arguments request,response, next. You could also define your own middlewares or the last request handler.

Related

How to achieve conditional authentication with passport.js and express?

I would like to use basic authentication for my API routes but also allow users to access the API in the browser through the local authentication strategy. My middle-ware looks like this:
router.get("/Login", (req: Request, res: Response, next: NextFunction) => {
let test = req.flash("loginMessage");
res.render("Login", { message: test });
});
// Local authentication for user login
router.post(
"/Login",
passport.authenticate("local-login", {
failureRedirect: config.urlExtension + "/Login", // redirect back to the signup page if there is an error
failureFlash: true, // allow flash messages
})
);
// Basic authentication for API routes
router.all("/api/*", passport.authenticate("basic", { session: false }));
router.all("*", connectensurelogin.ensureLoggedIn(`${config.urlExtension}/Login`))
So for the API authentication route I'd like to bypass basic authentication if local authentication has already been achieved by login.
I found that you can return a call to the authentication route from inside a outer route with this conditional like so:
// Basic authentication for API routes
router.all("/api/*", (req, res, next) =>
req.isAuthenticated()
? next()
: passport.authenticate("basic", { session: false })(req, res, next),
);

Koa2: how to write chain of middleware?

So in express, we can have a chain of middleware, copies an example:
middleware = function(req, res){
res.send('GET request to homepage');
});
app.get('/', middleware, function (req, res) {
res.send('GET request to homepage');
});
What's the equivalent way to write this in koa2 please ?
I'm thinking of using it for the route, for each route i want to have a middleware to check if user is already logged in.
Thanks !
If you're simply interested in making sure a middlware runs for every route, all you have to do is register the middleware before you register your routing middelware.
app.use(middleware);
As long as you call this before you 'use' your router, it will be called for every request. Just make sure you call the next function. This is how your middleware might look like:
function middleware(ctx, next) {
// Authenticate user
// Eventually call this
return next();
}

Use app.all as oauth authorization middleware in node.js

I can't figure out how to use app.all to act as oauth authorization filter for all the routes starting with /api/
passport.authenticate('bearer', { session: false });
is used for authorization. and here are two standard get configurations:
app.get('/api/foo', foo.find);
app.get('/api/bar', bar.find);
I don't want to include it in every call like:
app.get('/api/foo', passport.authenticate('bearer', { session: false }), foo.find);
It's simple, just get it to catch all routes starting with api. Make sure you put this before your routes.
app.all('/api/*', passport.authenticate('bearer', {session: false});

What unique functionality does app.post( .. ) provide, in Express.js

app.post is not documented in expressjs.com. As I understand, the server listens to a url requestion / etc. which then invokes a middleware and a callback. But all this is same in app.get.
What unique value does it provide to express?
PS. There are other questions like Express Framework app.post and app.get, or app.use and app.get (or app.post) node.js express but reading answers to the same does not provide the answer to teh question.
Edit:
The following code provides for invocation of both app.get and app.post on /login request from the browswer. Are both app.get and app.post invoked? (Presumably in the order of appearance. )
app.get('/login', function(req, res){
var username = req.user ? req.user.username : ''; res.render('login', { title: 'authenticate', username: username,
});
message: req.flash('error') });
app.post('/login',
passport.authenticate('local', { failureRedirect: '/login', failureFlash: true }), function(req, res) {
res.redirect('/admin'); });
enter code here
I'd not say it's not documented, but basically it does the same as app.get() does for HTTP GET, but instead only matches HTTP POST requests.
If you don't know what the difference between a POST and a GET is, you can for example take a look here.
As for your sample code, either your get or your post handler is invoked, depending on whether the browser does a post or a get request. Both are never invoked for the same request.

Routes file issues with Passport

I'm using NodeJS, Express, and PassportJS to build a web application. I'm having a problem with one of my routes which I can't make any sense out of. When I have:
...
app.get('/auth/facebook', passport.authenticate('facebook'));
...
Everything seems to work fine. But when I change that to:
...
app.get('/auth/facebook',
function(req, res) {
passport.authenticate('facebook');
});
...
It hangs? Am I missing something on the app.get function? I want to be able to do this because I want to make the path a little more dynamic where I determine what passport authenticates. For example:
...
app.get('/auth/:provider',
function(req, res) {
passport.authenticate(req.params.provider);
});
...
Where provider could be facebook, twitter, or google...
passport.authenticate is middleware, take a gander at the source: https://github.com/jaredhanson/passport/blob/master/lib/passport/middleware/authenticate.js
passport.authenticate('facebook') returns a function that takes the req, res, next parameters from express and handles them.
so:
app.get('/auth/:provider',
function(req, res, next) {
passport.authenticate(req.params.provider)(req, res, next);
});
is what you need.

Resources