我正在开发一个 Web 应用程序并使用 Firebase 身份验证进行用户登录。我的应用程序需要通过 Microsoft OAuth 提供程序(特别是 Azure Active Directory)对用户进行身份验证,然后检索用户的 Azure AD 组信息。
我已成功向 Microsoft 提供商设置 Firebase 身份验证以实现基本登录流程。但是,我不确定如何检索用户的 Azure AD 组信息。
任何关于如何使用 Firebase 身份验证在 TypeScript 应用程序中实现这些步骤的示例或指南将不胜感激。
预先感谢您的协助!
您需要:
+----------------+ +-------------------+
| | | |
| Azure AD +<-------------+ Firebase Auth |
| | | |
+-------+--------+ +---------+---------+
| |
| |
v v
+-------+--------+ +---------+---------+
| | | |
| Group Claims | | Your TypeScript |
| in Token | | Application |
| | | |
+----------------+ +-------------------+
请参阅“配置可选声明”:
然后更新您的 Firebase 配置:
最后,修改您的 TypeScript 应用程序:
import * as firebase from 'firebase/app';
import 'firebase/auth';
// Initialize Firebase
//
firebase.auth().signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com'))
.then((result) => {
// The Microsoft OAuth Access Token.
const token = result.credential.accessToken;
// Now use the token to retrieve group information from Microsoft Graph API
//
}).catch((error) => {
// Handle Errors here.
//
});
身份验证后,使用访问令牌调用 Microsoft Graph API 检索组信息。
确保您的 Azure AD 应用程序具有读取组数据所需的权限。
您可以使用访问令牌向 Microsoft Graph API 发出请求。
通过向
https://graph.microsoft.com/v1.0/me/memberOf
发出 GET 请求来获取组。
// previous code
firebase.auth().signInWithPopup(new firebase.auth.OAuthProvider('microsoft.com'))
.then(async (result) => {
const token = result.credential.accessToken;
// Fetch group data
const groupResponse = await fetch('https://graph.microsoft.com/v1.0/me/memberOf', {
headers: {
'Authorization': `Bearer ${token}`
}
});
const groups = await groupResponse.json();
console.log(groups);
// Handle groups here
}).catch((error) => {
// Handle Errors here
console.log(error);
});
作为替代方法,您可以:
firebase.auth()
方法 获取当前用户的对象,其中包含有关经过身份验证的用户的信息:import * as firebase from 'firebase/app';
import 'firebase/auth';
// Initialize Firebase
const firebaseConfig = {
apiKey: "your-api-key",
authDomain: "your-auth-domain",
databaseURL: "your-database-url",
projectId: "your-project-id",
storageBucket: "your-storage-bucket",
messagingSenderId: "your-messaging-sender-id",
appId: "your-app-id",
measurementId: "your-measurement-id"
};
firebase.initializeApp(firebaseConfig);
// Get the current user
const currentUser = firebase.auth().currentUser;
获得 currentUser 对象后,您可以使用 getIdTokenResult() 方法 检索用户的 OAuth 访问令牌。然后,该令牌可用于对 Azure AD 进行 API 调用以检索用户的组信息:
// Get the access token
const token = currentUser.getIdTokenResult().token;
// Make an API call to Azure AD to retrieve the user's group information
fetch(https://graph.microsoft.com/v1.0/me/memberOf?$select=id,displayName, {
headers: {
Authorization: Bearer ${token}
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error(error));
该 API 调用使用 Microsoft Graph API 从 Azure AD 检索用户的组信息。
$select
参数过滤响应以仅包含组 ID 和显示名称。 Authorization
标头包含从 Firebase 检索的访问令牌。
请注意,您需要在 Azure AD 租户中启用 Microsoft Graph API,并授予您的应用程序访问该 API 的权限。您可以通过在 Azure 门户中注册您的应用程序并配置必要的权限来完成此操作。