๐Ÿ“” Passport (1/2): ๊ฐœ๊ด„

Jake_Youngยท2020๋…„ 10์›” 4์ผ
0
post-thumbnail

Express ์„œ๋ฒ„๋ฅผ ์œ„ํ•œ ์š”๋ž€์Šค๋Ÿฝ์ง€ ์•Š๊ณ  ๊ฐ„๋‹จํ•œ ์‚ฌ์šฉ์ž ์ธ์ฆ ๋ฏธ๋“ค์›จ์–ด

๐Ÿ’ก ์ •๋ณด ์ถœ์ฒ˜

  1. passport-official website : Click Here
  2. github-passport : Click Here
  3. npm-passport : Click Here

๐Ÿ˜ passport๋ž€?

  • ์ฃผ๊ฐ„ ๋‹ค์šด๋กœ๋“œ ํšŸ์ˆ˜ 903,545 (2020๋…„ 10์›” 4์ผ ๊ธฐ์ค€)
  • passport๋Š” stratagies๋ผ๊ณ  ๋ถˆ๋ฆฌ๋Š” ํ”Œ๋Ÿฌ๊ทธ์ธ๋“ค์„ ๊ฐ€์ง€๊ณ  request๋ฅผ ์ธ์ฆํ•˜๊ธฐ ์œ„ํ•ด ๋งŒ๋“ค์–ด์กŒ๋‹ค.
  • passport๋Š” ํŠน์ • ๋ผ์šฐํŠธ๋‚˜ DB ์Šคํ‚ค๋งˆ์— ๊ตญํ•œ๋˜์ง€ ์•Š๊ณ  ๊ฐœ๋ฐœ์ž๊ฐ€ ์Šค์Šค๋กœ ์›ํ•˜๋Š” ๋ฐฉ์‹์œผ๋กœ ๊ฐœ๋ฐœํ•  ์ˆ˜ ์žˆ๋„๋ก ๋…ธ๋ ฅํ–ˆ๋‹ค.
  • ๋‹น์‹ ์ด passport๋ฅผ request์— ์ „๋‹ฌํ•ด์ฃผ๋ฉด passport๋Š” ์ธ์ฆ ์ดํ›„์˜ ์ž‘์—…์„ ์กฐ์ž‘ํ•  ์ˆ˜ ์žˆ๋Š” hooks๋ฅผ ์ œ๊ณตํ•œ๋‹ค.

๐Ÿ˜Ž strategy

passport.use(new LocalStrategy(
  function(username, password, done) {
    User.findOne({ username: username }, function (err, user) {
      // ๋ฌธ์ œ๊ฐ€ ์žˆ๋‹ค๋ฉด ์—๋Ÿฌ๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
      if (err) { return done(err); }
      // ๊ฐ€์ž…๋˜์ง€ ์•Š์€ ์œ ์ €๋ผ๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
      if (!user) { return done(null, false); }
      // ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ํ‹€๋ ธ๋‹ค๋ฉด false๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
      if (!user.verifyPassword(password)) { return done(null, false); }
      // ์œ„์˜ ๋ชจ๋“  ๊ฒฝ์šฐ๋ฅผ ํ†ต๊ณผํ–ˆ๋‹ค๋ฉด, user๋ฅผ ๋ฐ˜ํ™˜ํ•œ๋‹ค.
      return done(null, user);
    });
  }
));

๐Ÿฅฐ session

passport.serializeUser(function(user, done) {
  done(null, user.id);
});
 
passport.deserializeUser(function(id, done) {
  User.findById(id, function (err, user) {
    done(err, user);
  });
});

๐Ÿคช middleware

var app = express();
app.use(require('serve-static')(__dirname + '/../../public'));
app.use(require('cookie-parser')());
app.use(require('body-parser').urlencoded({ extended: true }));
app.use(require('express-session')({ secret: 'keyboard cat', resave: true, saveUninitialized: true }));
// ์•„๋ž˜์˜ passport.initialize๋ฅผ ๋ฐ˜๋“œ์‹œ ํ•ด์ค˜์•ผํ•œ๋‹ค.
app.use(passport.initialize());
app.use(passport.session());

๐Ÿคฉ Authenticate Requests

app.post('/login', 
  passport.authenticate('local', { failureRedirect: '/login' }),
  function(req, res) {
    res.redirect('/');
  });

๐Ÿคซ ๊ณต์‹ ์˜ˆ์ œ

  1. Local-strategy
  2. Social Authentication
profile
์ž๋ฐ”์Šคํฌ๋ฆฝํŠธ์™€ ํŒŒ์ด์ฌ ๊ทธ๋ฆฌ๊ณ  ์ปดํ“จํ„ฐ์™€ ๋„คํŠธ์›Œํฌ

0๊ฐœ์˜ ๋Œ“๊ธ€