Beace Lee

Beace Blog

Written by Beace Lee who lives and works in China building useful things. You should follow him on Twitter

Github中passport的应用(github登录接口)

September 12, 2016

1、点击头像下拉三角形按钮,进入settings

alt

2、点击左侧列表按钮中的oAuth applications

alt

3、左侧默认显示的你曾经用github账号登录过的网站,点击developer application,作为开发者应用使用。 4、依次按照表单提示填写内容,最终会生成Client IDClient Secret

alt

5、在项目中安装两个模块

npm install:

"passport": "*",
"passport-github": "*"

6、在入口文件中(app.js) 引入模块:

//创建用户使用github登录
var passport = require('passport'),
    GithubStrategy = require('passport-github').Strategy;
app.use(passport.initialize());//初始化
// YOUR ClientID/Secret
passport.use(new GithubStrategy({
    clientID: "ClientID",
    clientSecret: "ClientSecret",
    callbackURL: "http://localhost:3000/login/github/callback"
}, function(accessToken, refreshToken, profile, done) {
    done(null, profile);
}));

7、在网络请求中,分配路由,并且把github所登录的账户写入session(默认会在user中)

//github login
    app.get("/login/github", passport.authenticate("github", {session: false}));
    app.get("/login/github/callback", passport.authenticate("github", {
        session: false,
        failureRedirect: '/login',
        successFlash: '登陆成功!'
    }), function (req, res) {
        req.session.user = {name: req.user.username, head: "https://gravatar.com/avatar/" + req.user._json.gravatar_id + "?s=48"};
        res.redirect('/');
    });

8、在模板引擎ejs文件中加入github登录的链接进行测试:

<a href="/login/github">使用 GitHub 登录</a>

alt