簡體   English   中英

使用從客戶端收到的Google授權代碼在服務器端javascript(nodejs)上獲取訪問令牌

[英]Get access token on server side javascript (nodejs) using google authorization code received from client side

我已閱讀此文檔: - https://developers.google.com/identity/sign-in/web/server-side-flow

在最后一步,它接收授權代碼,之后它顯示了使用java或python庫接收訪問令牌和刷新令牌的示例,但我無法在nodejs中找到任何類似的示例。 如何使用nodejs復制相同的示例? 我不能只是發送帖子或獲取一些谷歌oauth api請求並使用授權碼接收訪問令牌?

提前致謝 :)

Google API Node.js客戶端庫提供oauth2Client.getToken(code, cb) ,它提供訪問令牌(以及可選的刷新令牌)以交換授權代碼:

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上提供了一個官方示例,其中包含oauth2.js ,oauth部分的幫助程序

您還可以在Paul Shan的網站上找到完整的示例,它是使用Google API Node.js Client的nodejs示例。 編輯ClientIdClientSecret ,運行此示例並轉到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}`);
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM