L
L
Leonid Nimchenko2021-11-18 12:54:33
JSON Web Token
Leonid Nimchenko, 2021-11-18 12:54:33

How to login with jwt on node.js server?

I'm with node.js for the first time (working with php and js). It is necessary to fasten authorization to the site managed by node.js through another site. The sources are here https://github.com/chsasank/outline-wiki-docker-compose . Passport.js is used for authorization. Added authorization form and strategy:

import passport from "@outlinewiki/koa-passport";
import Router from "koa-router";
import errorHandling from "../../../middlewares/errorHandling";
import methodOverride from "../../../middlewares/methodOverride";
import validation from "../../../middlewares/validation";
import { User, Team } from "../../../models";
import accountProvisioner from "../../../commands/accountProvisioner";
import { signIn } from "../../../utils/authentication";
import util from "util";

const router = new Router();

export const config = {
  name: "mysiteauth",
  enabled: true,
};

router.use(methodOverride());
router.use(validation());

function Strategy(verify) {
  passport.Strategy.call(this);
  this.name = 'mysiteauth';
  this._verify = verify;
}
util.inherits(Strategy, passport.Strategy);

Strategy.prototype.authenticate = function (req) {
  var self = this;
  function verified(err, user, info) {
    if (err) {
      return self.error(err);
    }
    if (!user) {
      return self.fail(info);
    }
//		self.success(user, info); // при включении этой строки возникает ошибка
  }

  try {
    self._verify(req, verified);
  } catch (ex) {
    return self.error(ex);
  }
};

passport.serializeUser(function(user, done) {
  done(null, user);
});

passport.deserializeUser(function(user, done) {
  done(null, user);
});

passport.use(new Strategy(
  async function(req, done) {
    // здесь потом будет запрос к основному сайту о соответствии логина паролю

    try {
      const result = await accountProvisioner({
        ip: req.ip,
        team: {
          name: 'mysite',
          domain: 'mysite.ru',
          subdomain: 'mysite',
        },
        user: {
          name: req.body.login,
          email: '[email protected]',
          isAdmin: false,
        },
        authenticationProvider: {
          name: "mysiteauth",
          providerId: 'mysite.ru',
        },
        authentication: {
          scopes: ["read"],
          providerId: "11112021",
        },
      });
      return done(null, result.user, result);
    } catch (err) {
      return done(err, null);
    }
  }
));
router.post("mysiteauth", passport.authenticate('mysiteauth'));
export default router;

Functions work out, but authorization does not occur. I do not understand what needs to be added and where?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question