NodeJS调用Google的OAuth API实现身份认证

OAuth的实践

接下来演示在nodejs应用中调用Google的OAuth API实现身份认证的过程。具体代码可以访问github

生成clientId和clientSecret

首先在Google developers console中创建一个应用。按下面描述的步骤操作,可以生成client-id和client-secret。

NodeJS调用Google的OAuth API实现身份认证_第1张图片
image

NodeJS调用Google的OAuth API实现身份认证_第2张图片
image

NodeJS调用Google的OAuth API实现身份认证_第3张图片
image

NodeJS调用Google的OAuth API实现身份认证_第4张图片
image

NodeJS调用Google的OAuth API实现身份认证_第5张图片
image

NodeJS调用Google的OAuth API实现身份认证_第6张图片
image

nodeJS调用OAuth

通过node/express实现一个简单的应用来演示调用的过程。

安装express和googleais模块

npm install express
npm install googleapis

在这个应用中有一个页面需要用到express session,需要安装一下

npm install express-session

创建index.js做为入口文件

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

//starting the express app
var app = express();

//using session in express
app.use(Session({
    secret: 'your-random-secret-19890913007',
    resave: true,
    saveUninitialized: true
}));

//this is the base route
app.use("/", function (req, res) {
    res.send(`
        

Authentication using google oAuth

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

创建OAuth Url

/**
 * 创建OAuth客户端
 */
function getOAuthClient() {
    return new OAuth2(ClientId, ClientSecret, RedirectUrl);
}
/**
 * 生成向认证服务器申请认证的Url
 */
function getAuthurl() {
    var oauth2Client = getOAuthClient();
    // 生成一个url用来申请Googe+和Google日历的访问权限
    var scopes = [
        'https://www.googleapis.com/auth/plus.me'
        // 'https://www.googleapis.com/auth/calendar'
    ];
    var url = oauth2Client.generateAuthUrl({
        // 'online' (default) or 'offline' (gets refresh_token)
        access_type: 'offline',
        // If you only need one scope you can pass it as a string
        scope: scopes,
        // Optional property that passes state parameters to redirect URI
        state: { foo: 'bar' }
    });
    return url;
}

getOAuthClient函数用来创建一个OAuth客户端,getAuthurl函数创建用于认证的Url。

修改基础路由,在里边增加一个链接:

app.get("/", function(req, res) {
    var url = getAuthurl();
    res.send(`

Authentication using google oAuth

Login`); });

现在打个浏览器访问这个链接:

NodeJS调用Google的OAuth API实现身份认证_第7张图片
image

增加callback路由

在google开发者平台申请clientId时,同时申请了一个callback地址,接下来在node应用中增加这个路由。

// GET /oauthcallback?code={authorizationCode}
app.get("/oauthCallback", function(req, res) {
    // 获取url中code的值
    var code = req.query.code;
    var session = req.session;
    // 使用授权码code,向认证服务器申请令牌
    var oauth2Client = getOAuthClient();
    oauth2Client.getToken(code, function(err, tokens) {
        // tokens包含一个access_token和一个可选的refresh_token
        if (!err) {
            oauth2Client.setCredentials(tokens);
            session["tokens"] = tokens;
            res.send(`

Login successful!

Go to details page`) } else { res.send(`

Login failed!!

`) } }); });

google服务会跳转到这个地址,同时附上授权码code在这个地址的后面,通过这个code可以向google服务申请令牌(access token),获取令牌后存储在当前用户的session中。

登录成功后会重定向到下面的页面。

NodeJS调用Google的OAuth API实现身份认证_第8张图片
image

增加details路由,获取用户数据

登录成功后接下就可以调用gogle apis来获取用户的信息。如下代码中增加details路由

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

    new Promise(function(resolve, reject) {
        // https://developers.google.com/+/web/api/rest/latest/people/get
        // me 表示通过授权的用户
        plus.people.get({ userId: 'me', auth: oauth2Client }, function(err, response) {
            if (!err) {
                resolve(response)
            } else {
                reject(err)
            }
        });
    }).then(function(data) {
        res.send(`

Id ${data.id}

Hello ${data.displayName}

profile url ${data.url}

`); }).catch(function(err) { res.send(`message get failed!`) }) });

使用存储在session中的令牌,请求接口获取用户信息。如果一些顺利可以看到页面的结果

NodeJS调用Google的OAuth API实现身份认证_第9张图片
image

你可能感兴趣的:(NodeJS调用Google的OAuth API实现身份认证)