使用Firebase身份验证访问Google日历API

使用Firebase身份验证访问Google日历API

本文介绍了使用Firebase身份验证访问Google日历API的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AngularJS,Firebase(SDK v3)和Google Calendar API构建一个Web应用程序。我正在使用Google OAuth对用户进行身份验证。我的目的是能够从Firebase中的数据库节点创建日历事件。到目前为止,我设法请求访问日历范围:

  _authProvider = new firebase.auth.GoogleAuthProvider(); 
//获取管理日历的权限
_authProvider.addScope(https://www.googleapis.com/auth/calendar);
_fbAuthObject.signInWithRedirect(_authProvider);

我正在使用重定向流进行身份验证,因此身份验证重定向可用为:

  _fbAuthObject.getRedirectResult()
.then(function _readToken(result){$ b $ if(result.credential){
_googleToken = result.credential.accessToken;
var authHeader ='Bearer'+ _googleToken;

//对api进行测试调用,返回200 OK
$ http ({
method:'GET',
headers:{
'Authorization':authHeader
},
url:'https://www.googleapis.com (calendar)/ v3 / users / me / calendarList / primary'
})
.then(function success(response){
console.log('Cal response',response);
$,
函数错误(响应){
console.log('Error',response);
});

然而,似乎在初始登录之外,无法通过Firebase SDK获取Google访问令牌。似乎只能访问Firebase JWT令牌,不能使用Calendar API。我可以存储访问令牌,但这不能解决令牌刷新时出现的问题等。有没有办法使用Firebase SDK获取当前的Google Access令牌,如果没有,还有什么其他解决方案可以解决问题验证用户两次?



更新1:



好像。在这个问题上,有一个,指出Firebase身份验证不再保留访问令牌。那么我怎样才能处理令牌刷新?是否真的没有答案呢?



更新2:

我与Firebase Support联系了一个有关这个问题的功能请求,他们给了我下面的答案:

lockquote

感谢您花时间给我们写信。

我已经明白你的意思了,这确实是一个很好的建议。我们肯定知道许多用户(比如您自己)会喜欢在刷新时访问令牌的OAuth功能。我们正在探索潜在的解决方案,但是我不能保证这个解决方案是否能在短期内推出。我们会继续考虑您的反馈。持续改进对于我们的社区来说非常重要,所以感谢您提出这个建议!



请留意我们的发行说明中的​​任何更新。


因此,似乎访问令牌目前无法通过Firebase SDK访问。我仍然试图找到一个解决方法,所以如果有人有一个有效的解决方案的想法,我会很高兴听到他们。当然,如果我自己找到一个工作解决方案,我会在这里发布它。

解决方案

通过使用Google API JavaScript客户端处理Firebase以外的身份验证问题。此解决方案需要将Google身份验证客户端包含为。手动处理Firebase登录流程记录在 here。

  gapi.auth2.getAuthInstance()。signIn()
()函数_firebaseSignIn(googleUser){
var unsubscribe = firebase.auth()。onAuthStateChanged(function(firebaseUser){
unsubscribe();
//检查我们是否已经签名 - 在Firebase中使用正确的用户
if(!_isUserEqual(googleUser,firebaseUser)){
//使用Google ID令牌构建Firebase凭证
var credential = firebase.auth.GoogleAuthProvider。凭证(
googleUser.getAuthResponse()。id_token);

//使用Google用户的凭证登录
return firebase.auth()。signInWithCredential(凭证)
.then(函数(result){
//其他东西...
});

_isUserEqual函数:

  function _isUserEqual(googleUser,firebaseUser){
if(firebaseUser){
var providerData = firebaseUser.providerData;
for(var i = 0; i< providerData.length; i ++){
if(providerData [i] .providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID&&
providerData [i] .uid === googleUser.getBasicProfile()。getId()){
//我们不需要重新验证Firebase连接。
返回true;
}
}
}
return false;

$ / code>

现在我可以像这样引用访问令牌:

  var user = gapi.auth2.getAuthInstance()。currentUser.get(); 
返回user.getAuthResponse()。access_token;

这对我来说仍然不是理想的解决方案,但是现在可以工作了,能够对Firebase和Calendar API进行身份验证。


I am building a web application using AngularJS, Firebase (SDK v3) and Google Calendar API. I'm authenticating users using Google OAuth. My purpose is to be able to create calendar events from database nodes in Firebase. So far I've managed to request access to the calendar scope with:

_authProvider = new firebase.auth.GoogleAuthProvider();
// Get permission to manage Calendar
_authProvider.addScope("https://www.googleapis.com/auth/calendar");
_fbAuthObject.signInWithRedirect(_authProvider);

I'm authenticating with the redirect flow so the authentication redirect is available as:

_fbAuthObject.getRedirectResult()
    .then(function _readToken(result) {
      if (result.credential) {
        _googleToken = result.credential.accessToken;
        var authHeader = 'Bearer '+ _googleToken;

        // Just a test call to the api, returns 200 OK
        $http({
          method: 'GET',
          headers: {
            'Authorization': authHeader
          },
          url: 'https://www.googleapis.com/calendar/v3/users/me/calendarList/primary'
        })
          .then(function success(response) {
            console.log('Cal response', response);
          },
          function error(response) {
            console.log('Error', response);
          });

However, it seems like outside the initial login it's not possible to get the Google access token through the Firebase SDK. It seems only possible to access the Firebase JWT token, no use with the Calendar API. I could store the access token, but this wouldn't resolve the problems when refreshing the token, etc. Is there any way to get the current Google Access token with Firebase SDK and if not, what other solutions is there to the problem without having to authenticate the user twice?

UPDATE 1:

Seems like someone else has struggled with similar problems with Facebook authentication. On that question there was a link to the Firebase documentation stating that Firebase Authentication no longer persists the access token. So how can I handle token refreshes? Is there really no answer to this?

UPDATE 2:

So, I contacted Firebase Support with a feature request about this problem and they gave me the following answer:

So It seems like the access tokens are not available through the Firebase SDK at the moment. I'm still trying to find a workaround, so if anyone has ideas about a valid solution I'd be glad to hear them. And of course, I'll be posting it here if I ever find a working solution myself.

解决方案

I finally got around this problem by handling the authentication outside Firebase with the Google APIs JavaScript client. This solution requires including the Google auth client as documented here. Manually handling the Firebase sign-in flow is documented here.

gapi.auth2.getAuthInstance().signIn()
    .then(function _firebaseSignIn(googleUser) {
      var unsubscribe = firebase.auth().onAuthStateChanged(function(firebaseUser) {
        unsubscribe();
        // Check if we are already signed-in Firebase with the correct user.
        if (!_isUserEqual(googleUser, firebaseUser)) {
          // Build Firebase credential with the Google ID token.
          var credential = firebase.auth.GoogleAuthProvider.credential(
            googleUser.getAuthResponse().id_token);

          // Sign in with credential from the Google user.
          return firebase.auth().signInWithCredential(credential)
            .then(function(result) {
              // other stuff...
            });

The _isUserEqual function:

function _isUserEqual(googleUser, firebaseUser) {
  if (firebaseUser) {
    var providerData = firebaseUser.providerData;
    for (var i = 0; i < providerData.length; i++) {
      if (providerData[i].providerId === firebase.auth.GoogleAuthProvider.PROVIDER_ID &&
        providerData[i].uid === googleUser.getBasicProfile().getId()) {
        // We don't need to reauth the Firebase connection.
        return true;
      }
    }
  }
  return false;
}

Now I can reference the access token like this:

var user = gapi.auth2.getAuthInstance().currentUser.get();
return user.getAuthResponse().access_token;

This still isn't the ideal solution for me, but it works for now, and I'm able to authenticate to both Firebase and the Calendar API.

这篇关于使用Firebase身份验证访问Google日历API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-24 11:25