Reputation: 455
I'm working on a Blazor wasm with Azure Functions as API. I can already authenticate user by Azure AD B2C on the client app but when it comes to identifying the user in Azure Function, the ClaimsPrincipal.Current is received null for all requests even if user is logged-in in the blazor app.
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);
}
}
What am I missing? Does the app automatically send the token on each request? I've added only this to program.cs regarding authentication.
builder.Services.AddMsalAuthentication(options =>
{
builder.Configuration.Bind("AzureAdB2C", options.ProviderOptions.Authentication);
});
How can I figure out that the app is sending the token? Is ClaimsPrincipal the correct way to receive the token and user identity?
Upvotes: 1
Views: 881
Reputation: 17424
The token is sent by http request in the Authorization
header when a BaseAddressAuthorizationMessageHandler
handler is attached to the HttpClient
.
To create an HttpClient with this handler you can register a client in the HttpClientFactory
like that:
services
.AddHttpClient("azure-function")
.ConfigureHttpClient(httpClient =>
{
var azureUri = new Uri("{path to azure}");
httpClient.BaseAddress = azureUri;
})
.AddHttpMessageHandler<BaseAddressAuthorizationMessageHandler>();
And use this client in your component or service by injecting the http client factory:
@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}");
}
}
Upvotes: 2