Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use passport with koa-generic-session()?

I've created a Koa application which uses passport with a local authentication strategy. I'd like to use the module koa-generic-session so I can store the session data in Redis.

How do I use those two together?

I found this repo which does this but it doesn't really seem to use the sessions and I am not sure whether it is correct: https://github.com/dozoisch/koa-react-full-example

like image 718
Hedge Avatar asked Oct 18 '22 10:10

Hedge


1 Answers

(Disclaimer: I'm not familiar with Koa, but I am with Express and Passport.)

I've looked through the link you provided, and here's how they use koa-generic-session with passport.

In the server.js file, the following lines refer to configuring Passport.

08 - const passport = require("koa-passport");
13 - const config = require("./config/config");

38 - require("./config/passport")(passport, config);
40 - require("./config/koa")(app, config, passport);

Line 38 is the traditional passport config file, which simply sets up serialization and deserialization.
Line 40 brings in koa.js and passes it the app, config file, and passport variables.

The following code is from koa.js:

04 - const session = require("koa-generic-session");

18 - app.keys = config.app.keys;

Looking at koa.js, koa-generic-session is assigned to the variable session. This variable is later called here:

35 -  app.use(session({
36 -      key: "koareactfullexample.sid",
37 -      store: new MongoStore({ url: config.mongo.url }),
38 -   }));

On line 18, app.keys is initialized as the documentation for koa-generic-session calls for. While the project you linked uses a MongoStore with koa-generic-session, you can simply replace that constructor with a koa-redis constructor, as is shown in the koa-generic-session documentation.

Lastly, Passport is initialized:

41 - app.use(passport.initialize());
42 - app.use(passport.session());

This code is similar to using Passport with Express, as that's all Passport needs to manage authentication through a session.

like image 124
Gibryon Bhojraj Avatar answered Nov 15 '22 06:11

Gibryon Bhojraj