nodejs中google授权登录

  |  

google 授权配置

创建项目 >> 在凭据页面创建 OAuth 2.0 客户端 ID >> 配置 (已获授权的重定向 URI) >> 测试完成 在 OAuth 同意屏幕 发布正式版

授权跳转连接

1
2
3
4
5
6
7
8
const url = `https://accounts.google.com/o/oauth2/v2/auth?scope=${encodeURIComponent(
"https://www.googleapis.com/auth/userinfo.email"
)}&include_granted_scopes=true&
response_type=token&state=1234&redirect_uri=${encodeURIComponent(
"<跳转连接 需要在谷歌配置>"
)}&client_id=client_id`;

console.log(url);

授权成功后跳转链接如下

(跳转连接 需要在谷歌配置)#state=1234&access_token=&token_type=Bearer&expires_in=3599&scope=email%20https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/drive.metadata.readonly%20openid&authuser=0&prompt=none

获取用户信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import * as superagent from "superagent";

try {
const url = `https://www.googleapis.com/oauth2/v1/userinfo`;

const res = await superagent.get(url, { access_token: token }).set({
"Content-Type": "application/json",
});

// 获取客户邮箱 和id 头像
return res.body;
} catch (error) {
console.log(error);
}

文档

适用于客户端 Web 应用的 OAuth 2.0

文章目录
  1. 1. google 授权配置
  2. 2. 授权跳转连接
  3. 3. 授权成功后跳转链接如下
  4. 4. 获取用户信息
  5. 5. 文档