javascript - 在 Firebase Microsoft 帐户身份验证中从用户获取电子邮件

标签 javascript firebase firebase-authentication microsoft-graph-api

我使用以下代码对使用 Microsoft 帐户登录的 Firebase 用户进行身份验证:

  signInMicrosoft = () => {
    var provider = new firebase.auth.OAuthProvider('microsoft.com');
    provider.addScope('openid');
    provider.addScope('email');
    firebase
      .auth()
      .signInWithPopup(provider)
      .then(
        function(result) {
          console.log('result', result)
          var token = result.credential.accessToken;
          var user = result.user;
          var isNewUser = result.additionalUserInfo.isNewUser;
          //window.location.href = "/";
        }.bind(this)
      )
      .catch(function(error) {
        // Handle Errors here.
        var errorCode = error.code;
        var errorMessage = error.message;
        this.setState({
          loginError: true
        });
        // The email of the user's account used.
        var email = error.email;
        // The firebase.auth.AuthCredential type that was used.
        var credential = error.credential;
        // ...
    });
  }

但是,当我尝试使用以下代码访问用户的电子邮件时:

firebase.auth().onAuthStateChanged(user => {
  console.log('user', user) 
});

“user.email”条目设置为空。如何让 Firebase 以这种方式访问​​ Microsoft 帐户的电子邮件,以便将“user.email”设置为用户的电子邮件?

最佳答案

我试过了。

我可以获得电子邮件地址。

参见:

At this time, the offline_access ("Maintain access to data you have given it access to") and user.read ("Sign you in and read your profile") permissions are automatically included in the initial consent to an application. These permissions are generally required for proper app functionality - offline_access gives the app access to refresh tokens, critical for native and web apps, while user.read gives access to the sub claim, allowing the client or app to correctly identify the user over time and access rudimentary user information

Important The Microsoft Authentication Library (MSAL) currently specifies offline_access, openid, profile, and email by default in authorization and token requests. This means that, for the default case, if you specify these permissions explicitly, Azure AD may return an error.

provider.addScope(); 不是必需的。

请尝试注释掉或删除provider.addScope();

    // provider.addScope('openid');
    // provider.addScope('email');

您应该检查您的 Microsoft 应用程序设置。

Microsoft Graph 权限 > 委派权限设置为 User.Read。?

备注:

以下文档中的

provider.addScope('mail.read'); 允许应用读取用户邮箱中的电子邮件。 不允许应用读取用户电子邮件地址。

关于javascript - 在 Firebase Microsoft 帐户身份验证中从用户获取电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55679236/

相关文章:

javascript - Firebase 身份验证检测用户是否来自重定向登录

javascript - 如何让我的弹出窗口在 3 秒后消失

java - 如何在 Android WebView 中使 JavaScript-Java 通信同步?

javascript - 提交按钮无法使用 JavaScript 验证表单

swift - 从 firebase 检索数据失败

ios - 防止重新加载已报告的评论

ios - 使用来自 Firebase 的数据在 map 上显示注释图像时出现奇怪的行为。环球银行金融电信协会4.1

javascript - 如何在 Ajax 调用 Controller 后显示 View

android - Firebase 覆盖

swift - iOS Firebase Twitter 登录每次都需要权限