Middleware in Iron-router

238 views Asked by At

I am trying to apply JWT(JSON Web Token) in Meteor server-side API's with Iron-router. I am able to create token but I can't get method in iron-router to write middleware for verifying that token. Can you Please explain Which method is used to write middleware and how to define it ?

2

There are 2 answers

0
Harry Adel On

There're a handful of ways to achieve this, this simplest in my opinion is to apply your logic within the action method of the route like so:

Router.route("/dashboard", {
  name: "dashboard",
  action: function() {
    const token = this.params.query.token
    try {
      var decoded = jwt.verify(token, "secret");
      this.render()
    } catch (err) {
      this.render("home"); // go home
    }
  }
});

You may also try tinkering with hooks or plugins as mentioned in the docs.

0
Christian Fritz On

In iron-router, middleware is defined using the onBeforeAction method (see "Server Hooks and Connect" in the guide). So for JWT verification, you can use something like this:

import { Meteor } from 'meteor/meteor';
import { Router } from 'meteor/iron:router';
import jwt from 'jsonwebtoken';

Router.onBeforeAction(function(req, res, next) {
    jwt.verify(req.query.token, "secret", (err, decoded) => {
      if (err) {
        console.log(`Failed to verify token. Error: "${err}"`);
        res.statusCode = 401;
        res.end('invalid token');
      } else {
        next();
      }
    });
  }, {where: 'server'});

// example server-side route for testing
Router.route('/server', { where: 'server' })
  .get(function () {
    this.response.end('ok');
  })

Failing example (true negative):

> curl -i localhost:3000/server?token=totally-wrong
HTTP/1.1 401 Unauthorized
date: Mon, 25 Nov 2019 16:41:33 GMT
connection: keep-alive
transfer-encoding: chunked

invalid token

Succeeding example (true positive):

> curl -i localhost:3000/server?token=eyJhbGciOiJIUzI1NiJ9.MTIzNDU2Nzg5MA.oy8UH-Y_-5ztrLKo8zgx-8b8AKvUTy4ijH-ItJU32qo
HTTP/1.1 200 OK
date: Mon, 25 Nov 2019 16:41:52 GMT
connection: keep-alive
transfer-encoding: chunked

ok