如何在Azure AD身份验证的Azure函数中获取用户信息

时间:2019-01-11 15:51:08

标签: angular oauth-2.0 azure-functions

我有一个角度应用程序和一个Azure Functions应用程序。这两个应用程序均已通过Azure AD进行身份验证。放置适当的凭据后,我正在调用“功能”应用的功能时,它工作正常。 Angular应用程序将令牌与调用一起添加,并且用于对Azure函数进行身份验证。 但是,在Azure函数中,我需要基于用户放置一些逻辑,但无法找到如何获取有关调用函数的用户的信息。 我尝试ClaimsPrincipal来获取用户信息,但它没有向我提供我期望的用户信息,而是返回了管理员信息。

谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用Microsoft Graph绑定,特别是Auth token绑定。

只需确保将identity属性的值设置为userFromRequest,然后调用文档中所示的Microsoft Graph APIs之一即可。

作为参考,这是文档中的示例

function.json

{
  "bindings": [
    {
      "name": "req",
      "type": "httpTrigger",
      "direction": "in"
    },
    {
      "type": "token",
      "direction": "in",
      "name": "graphToken",
      "resource": "https://graph.microsoft.com",
      "identity": "userFromRequest"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    }
  ],
  "disabled": false
}

C#脚本

using System.Net; 
using System.Net.Http; 
using System.Net.Http.Headers;
using Microsoft.Extensions.Logging; 

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, string graphToken, ILogger log)
{
    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", graphToken);
    return await client.GetAsync("https://graph.microsoft.com/v1.0/me/");
}

NodeJS / JavaScript

const rp = require('request-promise');

module.exports = function (context, req) {
    let token = "Bearer " + context.bindings.graphToken;

    let options = {
        uri: 'https://graph.microsoft.com/v1.0/me/',
        headers: {
            'Authorization': token
        }
    };

    rp(options)
        .then(function(profile) {
            context.res = {
                body: profile
            };
            context.done();
        })
        .catch(function(err) {
            context.res = {
                status: 500,
                body: err
            };
            context.done();
        });
};