Vue/Hapi JS App中如何使用AzureAD进行身份验证

How to use AzureAD for authentication in Vue / Hapi JS App

我们在 Azure 门户上注册了一个应用程序,我们想在 front-end 上使用 MSAL.js 并在 [=53= 上使用 hapi-auth-jwt2jwks-rsa ] 来验证用户。 back-end 不是托管在 Azure 上,而是托管在我们自己的 MySQL 服务器上。

根据这个例子active-directory-b2c-javascript-msal-singlepageapp we can use MSAL.js to login and either silently or with a pop up acquire ID and Access Tokens. We then attach the access token to the http header like this Vue.prototype.$http.defaults.headers.common['Authorization'] = 'Bearer ' + token and send a request with axios to our back-end /login route. When we hit the route from our client, jwt auth strategy kicks in and tries to decode the token using the keys retrieved with jwks-rsa from the public https://login.microsoftonline.com/common/discovery/keys

问题是来自 /login 的响应带有 401 (Unauthorized)res.headers.www-authenticate: "Bearer error=\"Invalid token\""

当我们将访问令牌copy/paste转换为jwt.io时,我们注意到我们解码的header object由typnonce组成, algx5tkid 并且签名无效。此外,我们的应用程序注册目前在所需权限下选择了带有 User.Read 的 Microsoft Graph,但我们删除了它。

为了测试问题是否出在我们的 JWT 策略中,我们将 ID 令牌而不是访问令牌传递给 Bearer。 JWT 解码了令牌,但响应返回 res.headers.www-authenticate: "Bearer error=\"Invalid credentials\""

我们的问题是:

  1. 是否可以在不调用 Graph API 的情况下验证访问令牌,我们该怎么做?
  2. 如果上述方法不可行,我们可以使用 ID 令牌对用户进行身份验证吗?这将如何工作?
  3. 如果我们可以在不调用 Graph 的情况下验证访问令牌 API https://portal.azure.com/ 中的设置应该是什么?

解决方案是在 https://portal.azure.com 中为我们的 API 定义一个范围,然后使用新创建的范围创建 API 权限。访问令牌被 hapi-auth-jwt2 成功解码,之后我们在 validate() 函数中进行了另一个内部级别的身份验证 return isValid: true 如果内部身份验证 returned正确的结果。希望这对某人有帮助