Bringing AuthorizeAttribute Behavior to Azure Functions v2. For v3 compatibility use functions-authorize.
It hooks into .NET Core dependency injection container to enable authentication and authorization in the same way ASP.NET Core does.
This projects is open source and may be redistributed under the terms of the Apache 2.0 license.
dotnet add package DarkLoop.Azure.WebJobs.Authorize
The goal is to utilize the same authentication framework provided for ASP.NET Core
using Microsoft.Azure.WebJobs.Hosting;
using MyFunctionAppNamespace;
[assembly: WebJobsStartup(typeof(Startup))]
namespace MyFunctionAppNamespace
{
class Startup : IWebJobsStartup
{
public void Configure(IWebJobsBuilder builder)
{
builder
.AddAuthentication(options =>
{
options.DefaultAuthenticationScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddOpenIdConnect(options =>
{
options.ClientId = "<my-client-id>";
// ... more options here
})
.AddJwtBearer(options =>
{
options.Audience = "<my-audience>";
// ... more options here
});
builder
.AddAuthorization(options =>
{
options.AddPolicy("OnlyAdmins", policyBuilder =>
{
// configure my policy requirements
});
});
}
}
}
No need to register the middleware the way we do for ASP.NET Core applications.
And now lets use WebJobAuthorizeAttribute
the same way we use AuthorizeAttribute
in our ASP.NET Core applications.
public class Functions
{
[WebJobAuthorize]
[FunctionName("get-record")]
public async Task<IActionResult> GetRecord(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req,
ILogger log)
{
var user = req.HttpContext.User;
var record = GetUserData(user.Identity.Name);
return new OkObjectResult(record);
}
[WebJobAuthorize(Policy = "OnlyAdmins")]
[FunctionName("get-all-records")]
public async Task<IActionResult>(
[HttpTrigger(AuthorizationLevel.Anonymous, "get")] HttpRequest req,
ILogger log)
{
var records = GetAllData();
return new OkObjectResult(records);
}
}