Title: Passport

Login authentication is a common business scenario, including “account password login” and “third-party unified login”.

Among them, we often use the latter, such as Google, GitHub, QQ unified login, which are based on OAuth specification.

Passport is a highly scalable authentication middleware that supports the Strategy of Github ,Twitter,Facebook, and other well-known service vendors. It also supports login authorization verification via account passwords.

Egg provides an egg-passport plugin which encapsulates general logic such as callback processing after initialization and the success of authentication so that the developers can use Passport with just a few API calls.

The execution sequence of Passport is as follows:

  • User accesses page
  • Check Session
  • Intercept and jump to authentication login page
  • Strategy Authentication
  • Check and store user information
  • Serialize user information to Session
  • Jump to the specified page

Using egg-passport

Below, we will use GitHub login as an example to demonstrate how to use it.

Installation

  1. $ npm i --save egg-passport
  2. $ npm i --save egg-passport-github

For more plugins, see GitHub Topic - egg-passport .

Configuration

Enabling the plugin:

  1. // config/plugin.js
  2. module.exports.passport = {
  3. enable: true,
  4. package: 'egg-passport'
  5. };
  6. module.exports.passportGithub = {
  7. enable: true,
  8. package: 'egg-passport-github'
  9. };

Configuration:

Note: The egg-passport standardizes the configuration fields, which are unified as key and secret.

  1. // config/default.js
  2. config.passportGithub = {
  3. key: 'your_clientID',
  4. secret: 'your_clientSecret'
  5. };

note:

  • Create a GitHub OAuth Apps to get the clientID and clientSecret information.
  • Specify a callbackURL, such as http://127.0.0.1:7001/passport/github/callback
    • You need to update to the corresponding domain name when deploying online
    • The path is configured via options.callbackURL, which defaults to /passport/${strategy}/callback

Mounting Routes

  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. // Mount the authentication route
  5. app.passport.mount('github');
  6. // The mount above is syntactic sugar, which is equivalent to
  7. // const github = app.passport.authenticate('github', {});
  8. // router.get('/passport/github', github);
  9. // router.get('/passport/github/callback', github);
  10. }

User Information Processing

Then we also need:

  • When signing in for the first time, you generally need to put user information into the repository and record the Session.
  • In the second login, the user information obtained from OAuth or Session, and the database is read to get the complete user information.
  1. // app.js
  2. module.exports = app => {
  3. app.passport.verify(async (ctx, user) => {
  4. // Check user
  5. assert(user.provider, 'user.provider should exists');
  6. assert(user.id, 'user.id should exists');
  7. // Find user information from the database
  8. //
  9. // Authorization Table
  10. // column | desc
  11. // --- | --
  12. // provider | provider name, like github, twitter, facebook, weibo and so on
  13. // uid | provider unique id
  14. // user_id | current application user id
  15. const auth = await ctx.model.Authorization.findOne({
  16. uid: user.id,
  17. provider: user.provider,
  18. });
  19. const existsUser = await ctx.model.User.findOne({ id: auth.user_id });
  20. if (existsUser) {
  21. return existsUser;
  22. }
  23. // Call service to register a new user
  24. const newUser = await ctx.service.user.register(user);
  25. return newUser;
  26. });
  27. // Serialize and store the user information into session. Generally, only a few fields need to be streamlined/saved.
  28. app.passport.serializeUser(async (ctx, user) => {
  29. // process user
  30. // ...
  31. // return user;
  32. });
  33. // Deserialize the user information from the session, check the database to get the complete information
  34. app.passport.deserializeUser(async (ctx, user) => {
  35. // process user
  36. // ...
  37. // return user;
  38. });
  39. };

At this point, we have completed all the configurations. For a complete example, see: eggjs/examples/passport

API

egg-passport provides the following extensions:

  • ctx.user - Get current logged in user information
  • ctx.isAuthenticated() - Check if the request is authorized
  • ctx.login(user, [options]) - Start a login session for the user
  • ctx.logout() - Exit and clear user information from session
  • ctx.session.returnTo= - Set redirect address after authentication page success

The API also be provided for:

  • app.passport.verify(async (ctx, user) => {}) - Check user
  • app.passport.serializeUser(async (ctx, user) => {}) - Serialize user information into session
  • app.passport.deserializeUser(async (ctx, user) => {}) - Deserialize user information from the session
  • app.passport.authenticate(strategy, options) - Generate the specified authentication middleware
    • options.successRedirect - specifies the redirect address after successful authentication
    • options.loginURL - jump login address, defaults to /passport/${strategy}
    • options.callbackURL - callback address after authorization, defaults to /passport/${strategy}/callback
  • app.passport.mount(strategy, options) - Syntactic sugar for developers to configure routing

Using Passport Ecosystem

Passport has many middleware and it is impossible to have the second encapsulation.
Next, let’s look at how to use Passport middleware directly in the framework.
We will use passport-local for “account password login” as an example:

Installation

  1. $ npm i --save passport-local

Configuration

  1. // app.js
  2. const LocalStrategy = require('passport-local').Strategy;
  3. module.exports = app => {
  4. // Mount strategy
  5. app.passport.use(new LocalStrategy({
  6. passReqToCallback: true,
  7. }, (req, username, password, done) => {
  8. // format user
  9. const user = {
  10. provider: 'local',
  11. username,
  12. password,
  13. };
  14. debug('%s %s get user: %j', req.method, req.url, user);
  15. app.passport.doVerify(req, user, done);
  16. }));
  17. // Process user information
  18. app.passport.verify(async (ctx, user) => {});
  19. app.passport.serializeUser(async (ctx, user) => {});
  20. app.passport.deserializeUser(async (ctx, user) => {});
  21. };

Mounting Routes

  1. // app/router.js
  2. module.exports = app => {
  3. const { router, controller } = app;
  4. router.get('/', controller.home.index);
  5. // Callback page after successful authentication
  6. router.get('/authCallback', controller.home.authCallback);
  7. // Render login page, user inputs account password
  8. router.get('/login', controller.home.login);
  9. // Login verification
  10. router.post('/login', app.passport.authenticate('local', { successRedirect: '/authCallback' }));
  11. };

How to develop an egg-passport plugin

In the previous section, we learned how to use a Passport middleware in the framework. We can further encapsulate it as a plugin and give back to the community.

initialization:

  1. $ egg-init --type=plugin egg-passport-local

Configure dependencies in package.json:

  1. {
  2. "name": "egg-passport-local",
  3. "version": "1.0.0",
  4. "eggPlugin": {
  5. "name": "passportLocal",
  6. "dependencies": ["passport"]
  7. },
  8. "dependencies": {
  9. "passport-local": "^1.0.0"
  10. }
  11. }

Configuration:

  1. // {plugin_root}/config/config.default.js
  2. // https://github.com/jaredhanson/passport-local
  3. exports.passportLocal = {
  4. };

Note: egg-passport standardizes the configuration fields, which are unified as key and secret, so if the corresponding Passport middleware attribute names are inconsistent, the developer should do the conversion.

Register the passport middleware:

  1. // {plugin_root}/app.js
  2. const LocalStrategy = require('passport-local').Strategy;
  3. module.exports = app => {
  4. const config = app.config.passportLocal;
  5. config.passReqToCallback = true;
  6. app.passport.use(new LocalStrategy(config, (req, username, password, done) => {
  7. // Cleans up the data returned by the Passport plugin and returns the User object
  8. const user = {
  9. provider: 'local',
  10. username,
  11. password,
  12. };
  13. // This does not process application-level logic and passes it to app.passport.verify for unified processing.
  14. app.passport.doVerify(req, user, done);
  15. }));
  16. };