使用从客户端收到的Google授权代码获取服务器端javascript(nodejs)上的访问令牌 [英] Get access token on server side javascript (nodejs) using google authorization code received from client side

查看:73
本文介绍了使用从客户端收到的Google授权代码获取服务器端javascript(nodejs)上的访问令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经阅读了此文档:- https://developers.google.com/identity/sign-in/web/server-side-flow

i have gone through this documentation :- https://developers.google.com/identity/sign-in/web/server-side-flow

在最后一步,它接收到授权代码,然后显示了使用Java或python库接收访问令牌和刷新令牌的示例,但是我在nodejs中找不到任何类似的示例. 我如何使用nodejs复制相同的示例? 我不能只是发送帖子或获取对某些Google oauth api的请求并使用授权码接收访问令牌吗?

At the last step it receives the authorization code and after that it shows the example of receiving access token and refresh token using java or python libraries, but i cant find any similar example in nodejs. How can i replicate the same example using nodejs? Can't i just send a post or get request to some google oauth api and receive the access token using authorization code?

先谢谢您了:)

推荐答案

Google API节点. js客户端库提供 oauth2Client.getToken(code, cb) 给出访问令牌(以及可选的刷新令牌)以交换授权代码:

Google APIs Node.js Client library offers oauth2Client.getToken(code, cb) which gives access token (and optionally refresh token) in exchange of the authorization code :

oauth2Client.getToken(code, function (err, tokens) {
  // Now tokens contains an access_token and an optional refresh_token. Save them.
  if (!err) {
    oauth2Client.setCredentials(tokens);
  }
});

可以在 https://github上找到官方示例. com/google/google-api-nodejs-client/tree/master/samples ,其中包括

An official example is available at https://github.com/google/google-api-nodejs-client/tree/master/samples which includes oauth2.js, an helper for the oauth part

您还可以在Paul Shan的本网站上找到完整的示例. ,这是使用 Google API Node.js客户端的nodejs示例.编辑ClientIdClientSecret,运行此示例,然后转到 http://127.0.0.1:8081

You can also find a complete example on this site by Paul Shan, it's a nodejs example using Google APIs Node.js Client. Edit ClientId and ClientSecret, run this sample and go to http://127.0.0.1:8081

var http = require('http');
var express = require('express');
var Session = require('express-session');
var google = require('googleapis');
var plus = google.plus('v1');
var OAuth2 = google.auth.OAuth2;
const ClientId = "YOUR_CLIENT_ID";
const ClientSecret = "YOUR_CLIENT_SECRET";
const RedirectionUrl = "http://localhost:8081/oauthCallback";

var app = express();
app.use(Session({
    secret: 'raysources-secret-19890913007',
    resave: true,
    saveUninitialized: true
}));

function getOAuthClient() {
    return new OAuth2(ClientId, ClientSecret, RedirectionUrl);
}

function getAuthUrl() {
    var oauth2Client = getOAuthClient();
    // generate a url that asks permissions for Google+ and Google Calendar scopes
    var scopes = [
        'https://www.googleapis.com/auth/plus.me'
    ];

    var url = oauth2Client.generateAuthUrl({
        access_type: 'offline',
        scope: scopes,
        //use this below to force approval (will generate refresh_token)
        //approval_prompt : 'force'
    });

    return url;
}

app.use("/oauthCallback", function(req, res) {
    var oauth2Client = getOAuthClient();
    var session = req.session;
    var code = req.query.code;
    oauth2Client.getToken(code, function(err, tokens) {
        console.log("tokens : ", tokens);
        // Now tokens contains an access_token and an optional refresh_token. Save them.
        if (!err) {
            oauth2Client.setCredentials(tokens);
            session["tokens"] = tokens;
            res.send(`
                <html>
                <body>
                    <h3>Login successful!!</h3>
                    <a href="/details">Go to details page</a>
                <body>
                <html>
            `);
        } else {
            res.send(`
                <html>
                <body>
                    <h3>Login failed!!</h3>
                </body>
                </html>
            `);
        }
    });
});

app.use("/details", function(req, res) {
    var oauth2Client = getOAuthClient();
    oauth2Client.setCredentials(req.session["tokens"]);

    var p = new Promise(function(resolve, reject) {
        plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
            console.log("response : ", response);
            resolve(response || err);
        });
    }).then(function(data) {
        res.send(`<html><body>
            <img src=${data.image.url} />
            <h3>Hello ${data.displayName}</h3>
            </body>
            </html>
        `);
    })
});

app.use("/", function(req, res) {
    var url = getAuthUrl();
    res.send(`
        <html>
        <body>
<h1>Authentication using google oAuth</h1>
        <a href=${url}>Login</a>
        </body>
        </html>
    `)
});


var port = 8081;
var server = http.createServer(app);
server.listen(port);
server.on('listening', function() {
    console.log(`listening to ${port}`);
});

这篇关于使用从客户端收到的Google授权代码获取服务器端javascript(nodejs)上的访问令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆