简体   繁体   English

如何修复“访问令牌来自错误的受众或资源”。 尝试使用MSAL令牌访问Azure的REST api时

[英]How do I fix 'The access token is from wrong audience or resource.' when trying to access Azure's REST api using an MSAL token

I'm creating a node web app that needs to integrate with some azure services using Azure REST API. 我正在创建一个需要使用Azure REST API与某些Azure服务集成的节点Web应用程序。 I'm using the node MSAL library for user login and retrieving an access token for making requests to the Azure REST api. 我正在使用节点MSAL库进行用户登录,并检索用于向Azure REST api发出请求的访问令牌。 I'm able to login a user successfully and retrieve an access token. 我能够成功登录用户并检索访问令牌。 However, when I try to make a request to Azure's REST api I am receiving a 401 error that says error="invalid_token", error_description="The access token is from wrong audience or resource." 但是,当我尝试向Azure的REST API发出请求时,我收到一条401错误,内容为error="invalid_token", error_description="The access token is from wrong audience or resource."

The web app itself is built with Node LTS and React v16.8.6 . 该Web应用程序本身是使用Node LTSReact v16.8.6 It has been deployed in Azure and registered with active directory. 它已部署在Azure中并在活动目录中注册。 I'm using MSAL v1.0.1 to login a user and retrieve a token when the user lands on the login page. 我正在使用MSAL v1.0.1登录用户并在用户登陆登录页面时检索令牌。

login.js 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;

I am successfully returning an access token and putting it in local storage. 我已成功返回访问令牌并将其放入本地存储中。

On a separate page I am retrieving the MSAL access token from local storage and using it to make a request to retrieve all resources associated with my Azure subscription. 在单独的页面上,我从本地存储中检索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));
  }

I suspect I'm getting the error because there is some discrepancy between the resource value sent with the login request and the scope value sent with the token request. 我怀疑出现错误是因为随登录请求发送的资源值与随令牌请求发送的作用域值之间存在差异。

I've attempted changing the resource value to 'resource': 'https://management.core.windows.net/' per Azure: The access token has been obtained from wrong audience or resource but that didn't change anything. 我试图将资源值更改为'resource': 'https://management.core.windows.net/'每个Azure 'resource': 'https://management.core.windows.net/' :访问令牌是从错误的受众或资源获取的,但没有任何改变。

I've also attempted various scopes including https://management.azure.com/user_impersonation and https://management.azure.com//user_impersonation following this example Access Token do not include access for API with MSAL 在此示例访问令牌之后,我也尝试了各种范围,包括https://management.azure.com/user_impersonationhttps://management.azure.com//user_impersonation

The get method is default, and the problem might be in 'Authorization': `Bearer ${token}` . get方法是默认的,问题可能出在'Authorization': `Bearer ${token}` Sometimes people use different rules, like 'Authorization': token , or 'Token': `Bearer ${token}` . 有时人们使用不同的规则,例如'Authorization': token'Token': `Bearer ${token}` I see some API using 'S-token': token . 我看到一些使用'S-token': token API。 try that. 试试看。 I thinkit is because the token did get there. 我认为这是因为令牌确实到达了那里。

You are using msal, so resource parameter is not needed in your msalConfig. 您正在使用msal,因此msalConfig中不需要resource参数。 You can remove it. 您可以删除它。

Change the scopes to scopes: ['https://management.azure.com/.default'] . 将范围更改为scopes: ['https://management.azure.com/.default']

So I ended up switching to the ADAL library to see if I would get the same error and I did. 因此,我最终切换到ADAL库,看看是否会遇到相同的错误,但确实如此。 I did however realize the resource request URL wasn't correct. 但是我确实意识到资源请求URL不正确。 The api-version wasn't an accepted version. api-version不是可接受的版本。 Once I switched it to 2018-02-01 the request returned 200. 一旦我将其切换为2018-02-01该请求就会返回200。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 MSAL 中使用客户端密码获取 Azure 访问令牌? - How to get Azure access token using client secret in MSAL? Azure 访问令牌 react-aad-msal - Azure Access Token react-aad-msal Azure AD Token generaiton using reactjs, to access WebAPI and SharePoint REST API/GrapAPI using jwt token - Azure AD Token generaiton using reactjs, to access WebAPI and SharePoint REST API/GrapAPI using jwt token 应用程序不使用 MSAL (react-aad-msal) 从缓存中获取访问令牌 - Application does not fetch access token from cache using MSAL (react-aad-msal) React SPA中的msal-使用从AcquireTokenRedirect收到的访问令牌 - msal in React SPA - use access token received from AcquireTokenRedirect 我们如何使用访问令牌来授权我们的 rest api? - How can we use access token to authorize our rest api? 带有 msal-react 包装器 acquireTokenSilent 的 msal-browser 不会从缓存中获取访问令牌 - msal-browser with msal-react wrapper acquireTokenSilent doesn't get access token from cache Azure B2C 抛出访问令牌验证失败。 无效的观众 - Azure B2C throw Access token validation failure. Invalid audience 从 Microsoft Graph for Azure 获取访问令牌 - Get access token from Microsoft Graph for Azure 如何使用 API 令牌从 REST API 获取数据 - How to fetch data from a REST API by using an API-Token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM