如何使用Azure身份验证在Azure功能中获取当前用户身份?

pen*_*tur 10 c# azure azure-active-directory azure-functions azure-authentication

我创建了一个新的功能应用程序,为其启用了应用程序服务身份验证/授权(" 使用身份验证/授权来保护您的应用程序并使用每个用户数据 ")并禁用未经身份验证的请求.

到目前为止,一切似乎都正常.如果我尝试请求我的HttpTriggered功能,它需要我先登录; 一旦我登录,所有请求都将按原样处理.所以"保护你的应用程序"部分没有问题.

但是,我完全坚持"使用每用户数据"部分.我的Azure函数被调用为

public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)

并且没有任何与身份验证相关的内容HttpRequestMessage.(AuthorizationLevel.Anonymous似乎控制着完全不同的东西 - 即,如果该函数可以被任何人调用,或者只能由具有固定API密钥的人调用).

如何获取调用该函数的已认证用户的身份?

Kzr*_*tof 5

使用Azure Function运行时v2.0.12309,可以从方法中注入的ClaimsPrincipal实例中检索经过身份验证的用户信息:Run

public static async Task<HttpResponseMessage> Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]
    HttpRequest httpRequest, 
    ILogger logger, 
    ClaimsPrincipal claimsPrincipal)
 {
            // Explores the authenticated user's claims in claimsPrincipal.
 }
Run Code Online (Sandbox Code Playgroud)


pen*_*tur 0

似乎可以从全局状态获取当前用户名System.Security.Claims.ClaimsPrincipal.Current.Identity.Name(当我最初发布这个问题时我不知道这一点)。但是,尚不清楚这是否是可靠或推荐的获取登录用户信息的方法。

例子:

using System.Net;
using System.Net.Http;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;

namespace FunctionApp
{
    public static class Function1
    {
        [FunctionName("HttpTriggerCSharp")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            return req.CreateResponse(HttpStatusCode.OK, "Hello " + ClaimsPrincipal.Current.Identity.Name);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这里真的很困惑...如果您无法访问当前登录的用户信息,为什么要启用身份验证?! (2认同)