Firebase 自定义身份验证与 Microsoft Azure/Graph [英] Firebase custom Auth with Microsoft Azure / Graph

查看:21
本文介绍了Firebase 自定义身份验证与 Microsoft Azure/Graph的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个使用 Microsoft Graph 登录的企业应用程序.成功签名后,我想使用要发送的令牌对 Firebase Auth 进行身份验证(这样我就可以保护对数据库的访问).

成功登录后收到的令牌不能直接用于 Firebase.

Firebase 自定义身份验证说明页面上说:

<块引用>

获取项目的服务器密钥:

  1. 转到项目设置中的服务帐户页面.
  2. 点击服务帐户"页面的 Firebase Admin SDK 部分底部的生成新私钥".
  3. 新服务帐号的公钥/私钥对会自动保存在您的计算机上.将此文件复制到您的身份验证服务器.

第三点说你需要输入认证服务器的密钥.这是否可以使用 Microsoft GraphAzure AD?

Firebase 为您提供的密钥是 JSON 文件.我检查了 Microsoft 应用注册门户,它允许您编辑应用清单,但没有成功.

JSON 文件如下所示:

{类型":服务帐户",project_id":APP_ID",private_key_id":KEY_ID_VALUE","private_key": "-----BEGIN PRIVATE KEY----<KEY VALUE>-----END PRIVATE KEY-----
",client_email":firebase-adminsdk-0ubvc@********.iam.gserviceaccount.com",client_id":XXXXXXXXXXXX",auth_uri":https://accounts.google.com/o/oauth2/auth",token_uri":https://accounts.google.com/o/oauth2/token",auth_provider_x509_cert_url":https://www.googleapis.com/oauth2/v1/certs",client_x509_cert_url":https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-0ubvc%XXXXXXXX.iam.gserviceaccount.com"}

我似乎找不到任何涵盖此问题的 github 项目或 stackoverflow 线程.

如何使用 MS Graph 或 Azure AD 接收自定义令牌?

解决方案

我现在已经完全解决了这个问题.通过对 Stackoverflow 的广泛研究和大量帮助,我设法解决了这个问题.

更新

目前已弃用数据库机密,并使用旧版 Firebase 令牌生成器.现在 Firebase Admin 导入已经足够好了.

所以,这些是我的发现:

<罢工>1.您确实需要在铸造 Firebase 令牌时将您的私钥发送到您的 Firebase 函数.在 Firebase 控制台中,您可以提取密钥并将文件重命名为 service-account.json.在执行 Firebase 部署

之前,这应该放在您的 Functions 文件夹中

  1. 在您的 index.js 文件中,您可以通过输入以下代码来获取您的服务文件:

    const admin = require('firebase-admin');

  2. 编写从其他身份验证服务接收信息的函数:

    //从任何 UID 创建一个 Firebase 令牌export.createFirebaseToken = functions.https.onRequest((req, res) => {//我们将分配给用户的 UID 和其他内容.常量 uid = req.body.uid;常量附加声明 = {名称:req.body.name,电子邮件:req.body.email};//创建或更新用户帐户.const userCreationTask = admin.auth().updateUser(uid, additionalClaims).catch(error => {if (req.method === 'PUT') {res.status(403).send('禁止!');}if (req.method === 'GET') {res.status(403).send('请使用 POST 这个函数');}//如果用户不存在,我们创建它.if (error.code === 'auth/user-not-found') {console.log(`使用 UID:${uid} 创建的用户,名称:${additionalClaims.name} 和电子邮件:${additionalClaims.email}`);返回 admin.auth().createUser({uid:uid,显示名称:additionalClaims.name,电子邮件:additionalClaims.email,});}抛出错误;console.log('错误!');});return Promise.all([userCreationTask]).then(() => {console.log('函数创建令牌触发');//创建一个 Firebase 自定义身份验证令牌.admin.auth().createCustomToken(uid, additionalClaims).then((token) => {console.log('为 UID 创建自定义令牌 "', uid, '" Token:', token);res.status(200).send(token);返回令牌});});});

使用 res.status 进行响应非常重要,因为这将完成任务.单个 return 语句不会执行此操作.Firebase 自己的完整工作示例可以在 github

  1. 您现在可以使用 Alamofireswift

    来创建一个类似于这样的 HTTP-request

    Alamofire.request("https://us-central1-<你的数据库参考>.cloudfunctions.net/createFirebaseToken",方法:.post,参数:参数,编码:JSONEncoding.default).responseString(completionHandler: { (token) in//这里处理结果})

    在这种情况下,Parameters 是一个常规 JSON 文件,其中包含您要添加到用户 Firebase 帐户的任何内容.

  2. 重要提示 知道您的 cloudfunctions URL 的任何人都可以触发此令牌铸造.因此,请确保添加安全措施来处理此问题.Firebase 制作的 YouTube 上的 Firecast 视频中简要提到了这一点Stackoverflow 中的此线程

  3. 中也进行了讨论
  4. 当您的客户收到令牌时,您会在 iOSAndroid 中,如文档中所述.

  5. 您现在已通过 FirebaseMicrosoft

  6. 的身份验证
  7. 我还添加了额外的安全层,通过检查我从 Microsoft 获得的 ID 是否与存储在经过身份验证的帐户中的 ID 相同Firebase.

I'm building an enterprise app using Microsoft Graph to sign in. After a successful signing i want to use the token to be sent to authenticate to Firebase Auth (so i can secure the access to the database).

The token recieved after a successful sign in cannot be used directly to Firebase.

On the Firebase custom Auth instructions page it says:

Get your project's server keys:

  1. Go to the Service Accounts page in your project's settings.
  2. Click Generate New Private Key at the bottom of the Firebase Admin SDK section of the Service Accounts page.
  3. The new service account's public/private key pair is automatically saved on your computer. Copy this file to your authentication server.

The third point says that you need to enter the key to the authentication server. Is this possible using Microsoft Graph or Azure AD?

The key that Firebase gives you is a JSON file. I've checked Microsoft App registration portal which allows you to edit the apps Manifest, but with no luck.

The JSON file looks like this:

{
    "type": "service_account",
    "project_id": "APP_ID",
    "private_key_id": "KEY_ID_VALUE",
    "private_key": "-----BEGIN PRIVATE KEY----<KEY VALUE>-----END PRIVATE KEY-----
",
    "client_email": "firebase-adminsdk-0ubvc@********.iam.gserviceaccount.com",
    "client_id": "XXXXXXXXXXXX",
    "auth_uri": "https://accounts.google.com/o/oauth2/auth",
    "token_uri": "https://accounts.google.com/o/oauth2/token",
    "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
    "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-0ubvc%XXXXXXXX.iam.gserviceaccount.com"
}

I can't seem to find any github projects or stackoverflow threads that covers this issue.

How can you recieve custom tokens with MS Graph or Azure AD?

解决方案

I have now fully worked this out. Through extensive research and a lot of help here on Stackoverflow i managed to solve this.

UPDATE

Database secrets are currently deprecated and use a legacy Firebase token generator. Now Firebase Admin import is good enough.

so, these are my findings:

1. You DO need to send your private keys to your firebase functions when minting a Firebase Token. In the Firebase console, you can extract the key and rename the file to service-account.json. This should be put in your Functions folder before performing your Firebase deploy

  1. In your index.js file, you can get your service file by entering this code:

    const admin = require('firebase-admin');
    

  2. Write the function for accepting information from the other Authentication service:

    // Create a Firebase token from any UID
    exports.createFirebaseToken = functions.https.onRequest((req, res) => {
    
      // The UID and other things we'll assign to the user.
      const uid = req.body.uid;
      const additionalClaims = {
        name: req.body.name,
        email: req.body.email
      };
    
      // Create or update the user account.
      const userCreationTask = admin.auth().updateUser(uid, additionalClaims).catch(error => {
    
        if (req.method === 'PUT') {
          res.status(403).send('Forbidden!');
        }
    
        if (req.method === 'GET') {
         res.status(403).send('Please use POST for this function');
        }
    
        // If user does not exists we create it.
        if (error.code === 'auth/user-not-found') {
          console.log(`Created user with UID:${uid}, Name: ${additionalClaims.name} and e-mail: ${additionalClaims.email}`);
          return admin.auth().createUser({
          uid: uid,
          displayName: additionalClaims.name,
          email: additionalClaims.email,
        });
            }
            throw error;
            console.log('Error!');
        });
    
    
        return Promise.all([userCreationTask]).then(() => {
          console.log('Function create token triggered');
          // Create a Firebase custom auth token.
          admin.auth().createCustomToken(uid, additionalClaims).then((token) => {
          console.log('Created Custom token for UID "', uid, '" Token:', token);
            res.status(200).send(token);
            return token
        });
      });
    });
    

It's very important to respond with a res.status since this will finish the task. A single return statement will not do this. A fully working sample from Firebase themself can be found on github

  1. You can now make a HTTP-request that could look something like this using Alamofire and swift

    Alamofire.request("https://us-central1-<YOUR DATABASE REFERENCE>.cloudfunctions.net/createFirebaseToken", 
    method: .post, parameters: parameters, encoding: JSONEncoding.default).
    responseString(completionHandler: { (token) in
        // Handle the result here
    })
    

    In this case, the Parameters is a regular JSON file that contains whatever you want to add to the users Firebase account.

  2. IMPORTANT Anyone with your cloudfunctions URL can trigger this token minting. So make sure you add security measures to handle this. This is briefly mentioned in a Firecast video on youtube made by Firebase and has also been discussed in this thread in Stackoverflow

  3. When your client received the token you a custom auth sign in iOS or in Android as described in the documentation.

  4. You are now authenticated both towards Firebase and Microsoft

  5. I have also added an extra layer of security, by checking that the ID i got from Microsoft, is the same ID stored in the authenticated account from Firebase.

这篇关于Firebase 自定义身份验证与 Microsoft Azure/Graph的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆