使用OAuth2

时间:2016-02-27 10:18:32

标签: node.js google-api oauth2

我想在我的应用程序中使用node.js中的simple-oauth2授权gmail登录,并尝试获取用户配置文件,最初我正在进行身份验证,代码是

    var oauth2 = require('simple-oauth2')({
    clientID: configAuth.googleAuth.clientID,
    clientSecret: configAuth.googleAuth.clientSecret,
    site: 'https://accounts.google.com/o/',
    tokenPath: 'https://accounts.google.com/o/oauth2/token',
    authorizationPath: 'oauth2/auth'
});

//授权uri定义

var authorization_uri = oauth2.authCode.authorizeURL({
    redirect_uri: 'http://localhost:8080/auth/google/callback',
    scope: 'https://www.googleapis.com/auth/userinfo.profile',
    scope: 'https://www.googleapis.com/auth/analytics.readonly',
    scope: 'https://www.googleapis.com/auth/userinfo.email',
    state: '382332$'
});
app.get('/auth/google', function (req, res) {
    res.redirect(authorization_uri);
});

回调是,

    app.get('/auth/google/callback', function (req, res) {
    var code = req.query.code;
     oauth2.authCode.getToken({
        code: code,
        redirect_uri: 'http://localhost:8080/auth/google/callback'
    }, saveToken);

    function saveToken(error, result, profile1) {
        if (error) {
            console.log('Access Token Error', error);
        }
        token = oauth2.accessToken.create(result);
        console.log('token',token)
    }

令牌的结果是这样的:

{ access_token: 'ya29.lQKN8a2ECM0h5ECWL4NcThS924m_eMUWg9I3BVfRvkTiK-lt-     8_1bCLjBmtmi68Kg8k',
  token_type: 'Bearer',
  expires_in: 3599,
  id_token: 'somelongstring',
  expires_at: Sat Feb 27 2016 16:38:05 GMT+0530 (India Standard Time) 
  }

在令牌响应中,我无法获得刷新令牌。有没有其他方法可以获得刷新令牌?

还有如何在登录成功后获取登录用户的个人资料详细信息。请提出一些解决方案..!     在此先感谢!!

2 个答案:

答案 0 :(得分:0)

我没有使用simple-oauth2的经验但我知道使用passport-google(http://passportjs.org/docs/google)它可以满足您的需求。

答案 1 :(得分:0)

我添加了这些

approval_prompt: 'force',
access_type: 'offline',
在authorization_uri中

var authorization_uri = oauth2.authCode.authorizeURL({
    redirect_uri: 'http://localhost:8080/auth/google/callback',
    approval_prompt: 'force',
    access_type: 'offline',
    scope: 'https://www.googleapis.com/auth/userinfo.profile     
    state: '3832$'
});

这对我有用!!