使用 Azure AD 和 MSAL 通过 REST API 使用电子邮件密码登录用户

问题描述 投票:0回答:1

我有一个场景,我有一个 React Native 应用程序和一个 NodeJS 服务器。我需要使用 Azure AD 对用户进行身份验证。我首先想到使用 Clerk、Appwrite、Supabase、Firebase 等身份验证提供商进行社交身份验证,但决定改为这样做:用户输入他们的电子邮件和密码,并将其发送到后端 Nodejs api。然后,此 API 将使用 MSAL(或者更好的东西,如果我们有的话),并根据大学的 Azure AD 对该用户进行身份验证,然后将令牌发送回 RN 应用程序。当 RN 应用程序到达

/getStudentData
端点时,它将验证令牌并从数据库中获取学生的数据。

我找不到我正在寻找的确切文档或教程。有人有这样的经历吗?我需要使用 MSAL 保护我的 API 路由,但也能够使用电子邮件和密码登录用户。这是一个好的架构吗?有什么建议给我吗?谢谢。

node.js rest azure-ad-msal msal
1个回答
0
投票

注意:如果您想使用电子邮件和密码来登录或验证用户,您可以使用

acquireTokenByUsernamePassword
方法。

  • 但是
    acquireTokenByUsernamePassword
    出于安全原因微软不推荐。
  • ROPC 流程不支持个人帐户或启用 MFA 的用户帐户。
  • 因此,您还可以使用
    acquireTokenByCode()
    方法来验证用户身份。

根据您的要求创建Azure AD应用程序并授予API权限

enter image description here

通过 Postman 使用以下参数生成访问令牌

https://login.microsoftonline.com/TenantID/oauth2/v2.0/token

grant_type:password
scope:api://xxx/test.read
username:[email protected]
password:***
client_id:ClientID

enter image description here

要在

msal-node
中执行相同操作,请使用以下代码:

const msal = require("@azure/msal-node");

const msalConfig = {
    auth: {
        clientId: "ClientID",
        authority: "Authority",
    }
};

const pca = new msal.PublicClientApplication(msalConfig);
const usernamePasswordRequest = {
    scopes: ["scope"],
    username: "username", 
    password: "***",
};

pca.acquireTokenByUsernamePassword(usernamePasswordRequest).then((response) => {
    console.log("acquired token by password grant");
}).catch((error) => {
    console.log(error);
});

否则请参考此

MsDoc
来使用acquireTokenByCode()

© www.soinside.com 2019 - 2024. All rights reserved.