繁体   English   中英

如何使用 Axios 使用 Node js API 获取 Azure 访问令牌

[英]How to get Azure access token with Node js API using Axios

我在 Nodejs 中有一个后端,使用 Axios 进行 API 调用。 我需要实现 Azure 身份验证来获取令牌,所以我遵循以下示例:

https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-v2-nodejs-webapp-msal?WT.mc_id=Portal-Microsoft_AAD_RegisteredApps

该示例使用 express 并重定向到首先获取和授权,然后是令牌,我一直在尝试使用 Axios 找到一个示例,但是我找不到。

这就是我到目前为止所拥有的,这个想法是使用结果来获取令牌,任何指导都非常感谢。

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


const REDIRECT_URI = "http://localhost:3000/";
const LOGIN = "https://login.microsoftonline.com/";


const config = {
    auth: {
        clientId: "12345678910",
        authority: "https://login.microsoftonline.com/12345678910",
        clientSecret: "Secret",
        knownAuthorities: ["https://login.microsoftonline.com/12345678910"
    ]
    }
};

const pca = new msal.ConfidentialClientApplication(config);

module.exports = {

    async getAzureAdToken(){

        try {

            let instance = axios.create({baseURL: LOGIN});
            
            const authCodeUrlParameters = {
                scopes: ["user.read"],
                redirectUri: REDIRECT_URI
            };

            pca.getAuthCodeUrl(authCodeUrlParameters).then((response) =>{

                let url = response.substring(LOGIN.length);

                instance.get(url).then((result) =>{


                });

            }).catch((error) => console.log(JSON.stringify(error)));
        } catch (error) {
            throw error
        }
    },

您可以使用客户端凭据流通过 axios 获取访问令牌。 客户端凭据流允许 web 服务(机密客户端)在调用另一个 web 服务时使用其自己的凭据而不是模拟用户进行身份验证。 在客户端凭据流中,权限由管理员直接授予应用程序本身。 我们需要在 API Permission 中添加应用权限。

在 Postman 中进行测试:

POST https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token
Content-Type: application/x-www-form-urlencoded

client_id=<client_id>
&scope=https://graph.microsoft.com/.default
&client_secret=<client_secret>
&grant_type=client_credentials

使用 Nodejs 的代码:

// Replace these values from the values of you app
const APP_ID = '[APP_ID/CLIENT_ID]';
const APP_SECERET = '[CLIENT_SECRET]';
const TOKEN_ENDPOINT ='https://login.microsoftonline.com/[TENANT_ID]/oauth2/v2.0/token';
const MS_GRAPH_SCOPE = 'https://graph.microsoft.com/.default';

const axios = require('axios');
const qs = require('qs');

const postData = {
  client_id: APP_ID,
  scope: MS_GRAPH_SCOPE,
  client_secret: APP_SECERET,
  grant_type: 'client_credentials'
};

axios.defaults.headers.post['Content-Type'] =
  'application/x-www-form-urlencoded';

let token = '';

axios
  .post(TOKEN_ENDPOINT, qs.stringify(postData))
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM