使用Microsoft Azure/Graph的Firebase自定义Auth [英] Firebase custom Auth with Microsoft Azure / Graph

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

问题描述

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

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).

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

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

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

获取项目的服务器密钥:

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

第三点说,您需要输入身份验证服务器的密钥.是否可以使用 Microsoft Graph Azure AD ?

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

Firebase为您提供的密钥是一个JSON文件.我已经检查过 Microsoft App注册门户,该门户使您可以编辑清单,但运气不佳.

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.

JSON文件如下所示:

{
    "type": "service_account",
    "project_id": "APP_ID",
    "private_key_id": "KEY_ID_VALUE",
    "private_key": "-----BEGIN PRIVATE KEY----<KEY VALUE>-----END PRIVATE KEY-----\n",
    "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线程.

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

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

推荐答案

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

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

当前不建议使用数据库机密,并使用旧版Firebase令牌生成器.现在Firebase Admin导入就足够了.

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

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

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. 在您的index.js文件中,您可以通过输入以下代码来获取服务文件:

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

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

  • 编写用于接受来自其他身份验证服务的信息的功能:

  • 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
        });
      });
    });
    

  • res.status响应非常重要,因为这将完成任务.单个return语句将不会执行此操作. 可以在

    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. 您现在可以使用 Alamofire 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
    })
    

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

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

    重要拥有您的cloudfunctions URL的任何人都可以触发此令牌铸造.因此,请确保添加安全措施以解决此问题. 这是Firebase在youtube上制作的Firecast视频中简短提及的,并且在 Stackoverflow中的该线程

    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

    当您的客户收到令牌时,您将在 iOS 或文档中所述的 Android 中.

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

    您现在已通过 Firebase Microsoft

    我还通过检查我从Microsoft获得的ID与从Firebase身份验证的帐户中存储的ID是否相同,还增加了一层安全保护.

    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.

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

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