接收Blazor wasm发送的Azure功能中的身份验证令牌

时间:2020-06-24 18:41:51

标签: azure-functions blazor blazor-client-side

我正在使用Azure Functions作为API来开发Blazor wasm。 我已经可以通过客户端应用程序上的Azure AD B2C对用户进行身份验证,但是当要在Azure Function中标识用户时,对于所有请求,ClaimsPrincipal.Current都会为null接收,即使用户为 在blazor应用程序中登录。

public static class Function1
{
    [FunctionName("Function1")]
    public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.User, "get", "post", Route = null)] HttpRequest req,
        ILogger log)
    {
        log.LogInformation("C# HTTP trigger function processed a request.");

        if (ClaimsPrincipal.Current == null || !ClaimsPrincipal.Current.Identity.IsAuthenticated)
        {
            log.LogInformation("Claims: Not authenticated");
        }
        else
        {
            log.LogInformation("Claims: Authenticated as " + ClaimsPrincipal.Current.Identity.Name);
        }

        string name = req.Query["name"];

        string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
        dynamic data = JsonConvert.DeserializeObject(requestBody);
        name = name ?? data?.name;

        string responseMessage = string.IsNullOrEmpty(name)
            ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response."
            : $"Hello, {name}. This HTTP triggered function executed successfully.";

        return new OkObjectResult(responseMessage);
    }
}

我想念什么?应用是否会在每次请求时自动发送令牌? 我仅将其添加到program.cs中有关身份验证的内容。

builder.Services.AddMsalAuthentication(options =>
        {
            builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
        });

如何确定该应用正在发送令牌? ClaimsPrincipal是接收令牌和用户身份的正确方法吗?

1 个答案:

答案 0 :(得分:2)

当将Authorization处理程序附加到BaseAddressAuthorizationMessageHandler时,令牌由http请求在HttpClient头中发送。
要使用此处理程序创建HttpClient,您可以像这样在HttpClientFactory中注册客户端:

services
    .AddHttpClient("azure-function")
    .ConfigureHttpClient(httpClient =>
    {
        var azureUri = new Uri("{path to azure}");
        httpClient.BaseAddress = azureUri;
    })
    .AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();

并通过注入http客户端工厂,在您的组件或服务中使用此客户端:

@using System.Net.Http
@inject IHttpClientFactory _factory

@code {
    protected override async Task OnInitializedAsync()
    {
        var httpClient = _factory.CreateClient("azure-function");
        var result = await httpClient.GetAsyn<Result>("{endpoint path}");
    }
}