简体   繁体   中英

How to make Passport.js work in Adonis Framework

I wanted to know if Passport.js can ONLY be used in an Express framework and not in any other? The docs doesn't completely answer my question. I'm in the middle of migrating my project from Express to Adonis.js and I can't seem to make passport work. Here is a sample of my code:

 const passport = use('passport') const bearer = use('./bearer') passport.use('bearer', bearer) module.exports = passport

and here is how I register it:

 const namedMiddleware = { auth: 'Adonis/Middleware/Auth', guest: 'Adonis/Middleware/AllowGuestOnly', bearer: passport.authenticate(['bearer'], { session: false }), }

this is the usage (I provided a bearer token):

 Route.post('/', ({ response }) => { response.json('Hello world') }).middleware(['bearer'])

It does not work. Error about res.setHeader is not a function showing. Maybe because the resoponse and http structure is different in adonis?

I know that Adonis has its own authentication library but my INITIAL goal is to get what I have now in Express to work in an Adonis environment before making any library changes to avoid any complications.

I recently migrated from knex to adonis.js as well. Integrating passport.js was initially painful but I get it to work with Macros.

For your error, Adonis' Request object has no setHeader. You will need to create a macro on Request for that function. Something like this

function setHeader (name, value) {
  this.header(name, value)
}
Response.macro('setHeader', setHeader)

Add that to a provider or hooks and you should be all set.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM