diff --git a/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs b/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs new file mode 100644 index 000000000..f1e477278 --- /dev/null +++ b/src/Microsoft.Identity.Web/AzureFunctionsAuthenticationHttpContextExtension.cs @@ -0,0 +1,47 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +using System; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; + +namespace Microsoft.Identity.Web +{ + /// + /// Extensions for . + /// + public static class AzureFunctionsAuthenticationHttpContextExtension + { + /// + /// Enables an Azure Function to act as/expose a protected web API, enabling bearer token authentication. Calling this method from your Azure function validates the token and exposes the identity of the user or app on behalf of which your function is called, in the HttpContext.User member, where your function can make use of it. + /// + /// The current HTTP Context, such as req.HttpContext. + /// A task indicating success or failure. In case of failure . + public static async Task<(bool, IActionResult?)> AuthenticateAzureFunctionAsync( + this HttpContext httpContext) + { + if (httpContext == null) + { + throw new ArgumentNullException(nameof(httpContext)); + } + + AuthenticateResult? result = + await httpContext.AuthenticateAsync(Constants.Bearer).ConfigureAwait(false); + if (result != null && result.Succeeded) + { + httpContext.User = result.Principal; + return (true, null); + } + else + { + return (false, new UnauthorizedObjectResult(new ProblemDetails + { + Title = "Authorization failed.", + Detail = result?.Failure?.Message, + })); + } + } + } +} diff --git a/src/Microsoft.Identity.Web/Microsoft.Identity.Web.xml b/src/Microsoft.Identity.Web/Microsoft.Identity.Web.xml index 148fd676a..5041d3b90 100644 --- a/src/Microsoft.Identity.Web/Microsoft.Identity.Web.xml +++ b/src/Microsoft.Identity.Web/Microsoft.Identity.Web.xml @@ -164,6 +164,18 @@ Exception from which we look for an MsalUiRequiredException. The MsalUiRequiredException if there is one, null, otherwise. + + + Extensions for . + + + + + Enables an Azure Function to act as/expose a protected web API, enabling bearer token authentication. Calling this method from your Azure function validates the token and exposes the identity of the user or app on behalf of which your function is called, in the HttpContext.User member, where your function can make use of it. + + The current HTTP Context, such as req.HttpContext. + A task indicating success or failure. In case of failure . + Description of a certificate.