【发布时间】:2019-11-07 20:43:30
【问题描述】:
我正在创建一个需要使用 Azure REST API 与一些 azure 服务集成的节点 Web 应用。我正在使用节点 MSAL 库进行用户登录并检索访问令牌以向 Azure REST api 发出请求。我能够成功登录用户并检索访问令牌。但是,当我尝试向 Azure 的 REST api 发出请求时,我收到一个 401 错误,上面写着 error="invalid_token", error_description="The access token is from wrong audience or resource."
网络应用程序本身是使用Node LTS 和React v16.8.6 构建的。它已部署在 Azure 中并在活动目录中注册。
我正在使用MSAL v1.0.1 登录用户并在用户登陆登录页面时检索令牌。
login.js
import React, { Component } from 'react';
import * as Msal from 'msal';
let msalConfig = {
auth: {
clientId: process.env.REACT_APP_CLIENT_ID,
authority: `https://login.microsoftonline.com/process.env.REACT_APP_TENANT_ID'`,
navigateToLoginRequestUrl: false,
redirect_uri: 'http://localhost:3000/newEntry',
resource: 'https://management.azure.com/'
},
cache: {
cacheLocation: "localStorage",
storeAuthStateInCookie: true
}
};
var msalInstance = new Msal.UserAgentApplication(msalConfig);
var tokenRequest = {
scopes: ['https://management.azure.com/']
}
class Login extends Component {
constructor(props) {
super(props);
this.state = {
response: null,
};
}
componentWillMount() {
// prevent login loop by checking for logged in user and then acquire a token if logged in
if (!msalInstance.getAccount() && !msalInstance.isCallback(window.location.hash)) {
this.login();
} else {
msalInstance.acquireTokenSilent(tokenRequest)
.then(res => localStorage.setItem('access_token', res.accessToken))
.catch(err => console.error(err))
}
}
login = () => {
msalInstance.handleRedirectCallback((error, response) => {
if (error) console.error(error);
console.log(response);
})
msalInstance.loginRedirect(tokenRequest);
}
render() {
return (
<div>
<h2>Login</h2>
</div>
)
}
}
export default Login;
我已成功返回访问令牌并将其放入本地存储中。
在一个单独的页面上,我正在从本地存储中检索 MSAL 访问令牌,并使用它来发出请求以检索与我的 Azure 订阅关联的所有资源。
componentWillMount() {
let token = localStorage.getItem('access_token');
let url = 'https://management.azure.com/subscriptions/process.env.REACT_APP_SUBSCRIPTION_ID/resource?api-version=2018-02-14'
fetch(url, {
method: 'GET',
headers: {
'Authorization': `Bearer ${token}`
}
})
.then(response => console.log(response))
.catch(err => console.error(err));
}
我怀疑我收到了错误,因为登录请求发送的资源值与令牌请求发送的范围值之间存在一些差异。
我已尝试根据Azure: The access token has been obtained from wrong audience or resource 将资源值更改为'resource': 'https://management.core.windows.net/',但这并没有改变任何东西。
我还尝试了各种范围,包括 https://management.azure.com/user_impersonation 和 https://management.azure.com//user_impersonation 按照这个示例 Access Token do not include access for API with MSAL
【问题讨论】:
标签: reactjs azure access-token msal azure-rest-api