我使用 Msal 从 AAD 获得了一个令牌,但无法使用获取的令牌获取用户配置文件。如何仅在 Node 后端验证令牌?

I got a token from AAD using Msal, but can't get the user profile using the token acquired. How to validate the token simply on Node backend?

我使用以下配置从 AAD 请求令牌。

app.module.ts 文件:

MsalModule.forRoot({
            clientID: 'CLIENT_ID',
            authority: "https://login.microsoftonline.com/TENANT_ID",
            validateAuthority: true,
            cacheLocation: 'sessionStorage',
            postLogoutRedirectUri: 'http://localhost:4200/authorize/signin',
            navigateToLoginRequestUrl: true,
            popUp: true,
            consentScopes: ['user.read', 'https://graph.microsoft.com']
        }

它 return 是 msal.idtoken、accesstoken 和一些更多的 msal 键值对。 现在,以下代码用于通过粘贴获取的 MSAL_IDTOKEN.

来获取用户的个人资料
const request = require('request');
const tok = 'MSAL_IDTOKEN HERE';
request.get({ url: "https://graph.microsoft.com/v1.0/me", headers: { "Authorization": "Bearer " + tok, "Content-type": "application/json" } }, function (err, response, body) {

    if (err) {
        console.log('err', err);
    }
    else
        console.log(response.body);
})

现在 运行 节点上的应用程序之后,它曾经 return 用户的配置文件,在解码令牌后找到,但现在没有。

您似乎正在尝试从您的访问令牌中读取用户配置文件。

为此,您需要在 Azure 门户上分配 profile 专用权限。

请参阅下面的屏幕截图:

Note: After assigning permission you can check your token on https://jwt.io/ whether it contains required permission.

令牌领取:

读取用户数据:

代码段:

令牌Class:

 public class AccessTokenClass
        {
            public string token_type { get; set; }
            public string expires_in { get; set; }
            public string resource { get; set; }
            public string scope { get; set; }
            public string access_token { get; set; }
            public string refresh_token { get; set; }

        }

令牌方法:

private async Task<string> GetTokenByROPCFormat()
        {

            string tokenUrl = $"https://login.microsoftonline.com/YourTenantIdOrName/oauth2/token";

            var tokenRequest = new HttpRequestMessage(HttpMethod.Post, tokenUrl);

            tokenRequest.Content = new FormUrlEncodedContent(new Dictionary<string, string>
            {
                ["grant_type"] = "password",
                ["client_id"] = "b603c7be-a866--e6921e61f925",
                ["client_secret"] = "Vxf1SluKbgu4PF0Nf3wE5oG",
                ["resource"] = "https://graph.microsoft.com",
                ["username"] = "kironmemb@MyTenant.onmicrosoft.com",
                ["password"] = "@Mypassword"

            });

            dynamic json;
            dynamic results;
            HttpClient client = new HttpClient();

            var tokenResponse = await client.SendAsync(tokenRequest);

            json = await tokenResponse.Content.ReadAsStringAsync();
            results = JsonConvert.DeserializeObject<AccessTokenClass>(json);
            Console.WriteLine("Your Refresh Token=>{0}", results.refresh_token);



            //  New Block For Accessing Data from API
            HttpClient newClient = new HttpClient();

            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");

            request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", results.access_token);
            HttpResponseMessage response = await newClient.SendAsync(request);

            string output = await response.Content.ReadAsStringAsync();
            return output;




        }

我看到您在 Portal 上的配置正确。

如果您使用的是 MSAL.js,请给出如下代码:

    this.app = new Msal.UserAgentApplication(

        this.applicationConfig.clientID,

        `https://login.microsoftonline.com/${AzureADName}/`,

        () => {

            // callback for login redirect

        },

        {

            redirectUri

        }

    );

然后您将调用它来获取用户信息:

this.app.getUser();

this.app.getAccount();

您必须提供版本信息才能确定,因为 API 已更改。

获取用户配置文件仅适用于 msal": "^0.2.4",不适用于当前版本 1.1。