我正在创建一个节点web应用程序,需要使用azure REST API与一些Azure服务集成。我使用节点MSAL库进行用户登录,并检索一个访问令牌,以便向Azure REST api发出请求。我能够成功地登录用户并检索访问令牌。然而,当我尝试向Azure的REST api发出请求时,我收到了一个401错误,上面写着error="invalid_token", error_description="The access token is from wrong audience or resource."
web应用本身就是用Node LTS
和React v16.8.6
构建的。它已部署在Azure中并注册到active directory。我使用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
发布于 2019-06-28 01:13:46
所以我最终切换到ADAL库,看看我是否会得到同样的错误,我做到了。然而,我确实意识到资源请求URL是不正确的。api-version
不是一个被接受的版本。当我将它切换到2018-02-01
时,请求返回200。
发布于 2019-06-26 08:55:52
get方法是默认的,问题可能出在'Authorization': `Bearer ${token}`
中。有时人们使用不同的规则,如'Authorization': token
或'Token': `Bearer ${token}`
。我看到一些使用'S-token': token
的应用编程接口。试试看。我想是因为令牌确实到了那里。
发布于 2019-06-27 09:29:46
您正在使用msal,因此您的msalConfig中不需要resource
参数。您可以将其删除。
将作用域更改为scopes: ['https://management.azure.com/.default']
。
https://stackoverflow.com/questions/56763726
复制相似问题