Passport.JS 获取 Google 日历

问题描述 投票:0回答:1

我目前正在尝试在 Node.JS 中构建一个与 Google 日历挂钩的日历应用程序。然而,我一直在努力尝试从 Google API 获取日历。我已经下载了 GoogleApis npm 包来协助 PassportJS,但我似乎无法获得与 GoogleAPI 交互的护照。我试图找到一种使用已经经过身份验证的用户来获取日历的方法,但谷歌没有产生任何结果。有没有办法使用 Passport.JS 来获取 Google 日历,或者我是否需要完全放弃 PassportJS 来完成此任务?

这是我目前用来尝试获取日历的快速路线。

let auth = passport.authenticate('google', { 
scope: ['profile', 'email', 
'https://www.googleapis.com/auth/calendar.events', 
'https://www.googleapis.com/auth/calendar.readonly']
})
/*
I want to know if there is a way to Get The Calendar without the Code below or if I can use Passportjs for the Credentials Section
*/
 const client = google.auth.getClient({
        credentials: credentials 
        scopes: ['https://www.googleapis.com/auth/calendar'],
      })
    calendar.events.list({
        calendarId: 'CALID',
...
javascript node.js google-api passport.js google-calendar-api
1个回答
0
投票

PassportJS 不会对日历 API 进行 API 调用,它的唯一目的是对用户进行身份验证,在对日历 API 进行任何调用之前,您似乎缺少整个 OAuth 流程。

首先,您需要在 Google Cloud Console 上设置项目并启用日历 API https://console.cloud.google.com/ 生成凭证的 JSON。

有了手中的凭据,您可以简单地加载它们:

const keys = require('./your_oauth_keys.json');

然后您需要指定身份验证策略

const GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;

passport.use(new GoogleStrategy({
    clientID: keys.web.client_id,
    clientSecret:  keys.web.client_secret,
    callbackURL: "http://localhost:3000/auth/callback",
  },
  function(accessToken, refreshToken, profile, done) {
      userProfile=profile;
      return done(null, userProfile);
  }
));

然后假设您使用的是快递,只需添加所需的路线

app.get('/auth', 
  passport.authenticate('google', { scope : scopes }));
 
app.get('/auth/callback', 
  passport.authenticate('google', { failureRedirect: '/error' }),
  function(req, res) {
    // Successful authentication, redirect success.
    res.redirect('/success');
  });

您还应该将 http://localhost:3000/ 添加到 oauth 策略允许的 url

© www.soinside.com 2019 - 2024. All rights reserved.