egg-passport
passport plugin for egg, base on passportjs.
Install
$ npm i egg-passport
Usage
enable passport plugin
// config/plugin.jsexportspassport = enable: true package: 'egg-passport';
Using Github and Twitter strategy
// config/config.default.jsexportspassportGithub = key: 'my oauth2 clientID' secret: 'my oauth2 clientSecret'; exportspassportTwitter = key: 'my oauth1 consumerKey' secret: 'my oauth1 consumerSecret';
Authenticate Requests
Use app.passport.mount(strategy[, options])
, specifying the 'github'
and 'twitter'
strategy, to authenticate requests.
// app/router.jsmodule { app; // authenticates routers apppassport; // this is a passport router helper, it's equal to the below codes // // const github = app.passport.authenticate('github'); // app.get('/passport/github', github); // app.get('/passport/github/callback', github); // custom options.login url and options.successRedirect apppassport;};
Verify and store user
Use app.passport.verify(async (ctx, user) => {})
hook:
// app.jsmodule { apppassport;};
egg-passport-${provider}
plugin
How to develop an See example: egg-passport-twitter.
- Plugin dependencies on egg-passport to use
app.passport
APIs.
// package.json
- Define config and set default values
Must use key
and secret
instead of consumerKey|clientID
and consumerSecret|clientSecret
.
// config/config.default.jsexportspassportTwitter: key: '' secret: '' callbackURL: '/passport/twitter/callback';
- Init
Strategy
inapp.js
and format user inverify callback
// app.jsconst debug = 'egg-passport-twitter';const assert = ;const Strategy = Strategy; module { const config = appconfigpassportTwitter; // must set passReqToCallback to true configpassReqToCallback = true; ; ; // convert to consumerKey and consumerSecret configconsumerKey = configkey; configconsumerSecret = configsecret; // register twitter strategy into `app.passport` // must require `req` params apppassport;};
- That's all!
APIs
application
extent app.passport.mount(strategy, options)
: Mount the login and the login callback routers to use the givenstrategy
.app.passport.authenticate(strategy, options)
: Create a middleware that will authorize a third-party account using the givenstrategy
name, with optionaloptions
.app.passport.verify(handler)
: Verify authenticated userapp.passport.serializeUser(handler)
: Serialize user before store into sessionapp.passport.deserializeUser(handler)
: Deserialize user after restore from session
context
extend ctx.user
: get the current authenticated userctx.isAuthenticated()
: Test if request is authenticated* ctx.login(user[, options])
: Initiate a login session foruser
.ctx.logout()
: Terminate an existing login session
Unit Tests
This plugin has includes some mock methods to helper you writing unit tests more conveniently.
app.mockUser([user])
: Mock an authenticated user
const mm = ; ;
app.mockUserContext([user])
: Mock a context instance with authenticated user
;
Questions & Suggestions
Please open an issue here.