본문 바로가기

express

passport-facebook with JWT [Express]

When we use SOCIAL LOGIN (like facebook, google login) we can use passport.js

there is a lot of strategy to use(Facebook Strategy, github Strategy etc..). these strategies help us to login by these sites. you can remember these process. you already used it a lot.

process of passport-facebook (use session)

  1. choose what strategy to login with
  2. click choosed strategy link
  3. redirect to strategy site(facebook login site)
  4. input facebook id and password
  5. if the input data is valid then success login
  6. facebook passes your data to your application.
  7. your data will be saved in session.
  8. whenever you request in your application, the data saved in session will be passed with request.

Above process is for passport-facebook. this uses session. session is usually used in browser.
But. It is not that good to use in react-native.
## If your application is mobile, Token is better way to persist authroization, authentication then session.

I choosed JWT(jsonWebToken) to use token in my application

  1. Get user data from passport-facebook and save user data in DB
  2. then We need to choose what data will be contained in Token(these data called as 'payload'). these datas(payload) are gonna used for querying DB. to Find real User data.
  3. and Encrypt data(payload) with JWT secretKey.
  4. then Pass to client.
  5. from now Client can do protected work(works need authentication) by passing valid token with request.

Before using JWT

// Facebook
router.get('/login/facebook',
    passport.authenticate('facebook'));
router.get('/login/facebook/callback',
    passport.authenticate('facebook', { failureRedirect: '/auth/login' }),
    function (req, res) {
        console.log(req);
        req.session.save(function () {
            res.redirect('/');
        });
    });

After using JWT

// Facebook
router.get('/login/facebook',
    passport.authenticate('facebook'));
router.get('/login/facebook/callback',
    passport.authenticate('facebook', { session: false, failureRedirect: '/auth/login' }),
    function (req, res) {
        // 'req' has user data

        // JWT process
        var payload = {
            email: req.user.email // I choosed only email to my payload
        };
        var options = { expiresIn: 60*60*24};
        let token = jwt.sign(payload, process.env.JWT_SECRET, options); // issue token

        // response to client with token
        res.json({
            token : token,
            message: 'token issued!'
        })

    }); 

Almost is from these stackoverflow. I followed this answer to make my application_

Though there is good answer, I wanted to add more information with example.

Passport's google/facebook strategy is session based, it stores user info in cookie which is not advisable. So we need to disable it first
To disable session we need modify our redirect router. For example if we have redirect path /google/redirect like following, we need to pass { session: false } object as parameter.

router.get('/google/redirect', passport.authenticate('google', { session: false }), (req, res)=> {
    console.log(":::::::::: user in the redirect", req.user);
    //GENERATE JWT TOKEN USING USER
    res.send(TOKEN);
})

So where does this user come from? This user comes from passport's callback function. In the previous snippet we have added passport.authenticate(....) This middlewire initiates passport's google-strategy's callback which deals with the user. For example

passport.use(
    new GoogleStrategy({
        callbackURL: '/google/redirect',
        clientID: YOUR_GOOGLE_CLIENT_ID
        clientSecret: YOUR_GOOGLE_SECRET_KEY
    }, 
    (accessToken, refreshToken, profile, done)=>{
        console.log('passport callback function fired');

        // FETCH USER FROM DB, IF DOESN'T EXIST CREATE ONE

        done(null, user);

    })
)

That's it. We have successfully combined JWT and Google/Facebook Strategy.

'express' 카테고리의 다른 글

Divide DB by the 'env'  (0) 2020.08.27
What is node.js?[not done]  (0) 2020.07.14
body-parser[Middleware]  (0) 2020.07.03
How to test passport-facebook /Social login test [TDD]  (0) 2020.06.28
How to show joined models [mongoose]  (0) 2020.05.21