2017-09-27 63 views
0

我想存儲在瀏覽器localStorage中從passport.js返回的jwt令牌,因爲從服務器到客戶端的通信自從生成令牌服務器。如何從Passport.js中存儲令牌在本地存儲

我將不勝感激任何關於如何在客戶端瀏覽器localStorage上設置由服務器生成的令牌的幫助。

路線

// Setting the github oauth routes 
    app.get('/auth/github', passport.authenticate('github', { 
    failureRedirect: '/signin' 
    }), authCallback); 

    app.get('/auth/github/callback', passport.authenticate('github', { 
    failureRedirect: '/signin' 
    }), authCallback); 

passport.js

passport.use(new GitHubStrategy(
    { 
    clientID: process.env.GITHUB_CLIENT_ID || config.github.clientID, 
    clientSecret: process.env.GITHUB_CLIENT_SECRET || config.github.clientSecret, 
    callbackURL: config.github.callbackURL 
}, 
((accessToken, refreshToken, profile, done) => { 
    User.findOne({ 
    'github.id': profile.id 
    }, (err, user) => { 
    if (err) { 
     return done(err); 
    } 
    if (!user) { 
     user = new User({ 
     name: profile.displayName, 
     username: profile.username, 
     provider: 'github', 
     github: profile._json 
     }); 
     user.save(() => done(err, user)); 
    } else { 
     return done(err, user); 
     } 
     }); 
    }) 
)); 

AuthCallBack

export const authCallback = (req, res) => { 
    const { TOKEN_SECRET } = process.env; 
    if (!req.user) { 
    res.redirect('/#!/signin?error=emailRequired'); 
    } else { 
    const token = jwt.sign(
     { user: req.user.id, name: req.user.name }, 
     TOKEN_SECRET, 
     { expiresIn: 72 * 60 * 60 } 
    ); 
    // window.localStorage.setItem('token', token); 
    res.redirect('/#!/app'); 
    } 
}; 

我會非常感謝有助於將來自authCallBack的令牌存儲在我的瀏覽器localStorage中。

回答

1

我不得不通過在瀏覽器cookie中設置數據來解決這個問題,然後檢索客戶端存儲的數據,然後將數據存儲在瀏覽器localStorage中。