A lightweight library for managing authentication and authorization in Azure Functions WebApp
License
—
Deps
7
Install Size
—
Vulns
✓ 0
Published
Nov 23, 2024
$ dotnet add package FuncAuthzFuncAuthz is a .NET package designed to provide authentication and authorization for Azure Function Apps using JWT tokens. This package simplifies the process of securing your Azure Functions by integrating JWT token validation and role-based access control.
To install FuncAuthz, add the package to your project using NuGet:
dotnet add package FuncAuthz
In your Program.cs or Startup.cs, configure the authentication and authorization services:
using System.Text;
using FuncAuthz.Extensions;
using Microsoft.Extensions.Hosting;
using Microsoft.IdentityModel.Tokens;
var host = new HostBuilder()
.ConfigureFunctionsWebApplication(builder =>
{
builder.AddAuthentication()
.AddJwtBearer(new TokenValidationParameters
{
ValidateAudience = false,
ValidateIssuer = true,
ValidIssuer = "Issuer",
RequireExpirationTime = true,
IssuerSigningKey =
new SymmetricSecurityKey(
Encoding.UTF8.GetBytes("A secure key that's shared between AspNetCore and Azure Functions")),
ValidateIssuerSigningKey = true,
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero
});
})
.Build();
host.Run();
Ensure the AuthorizationMiddleware is added to the pipeline:
builder.UseMiddleware<AuthorizationMiddleware>();
Use the [Authorize] attribute to secure your Azure Functions:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.AspNetCore.Authorization;
using System.Net;
public class MyFunction
{
[Function("MyFunction")]
[Authorize(Roles = "Admin")]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteStringAsync("Hello, authorized user!");
return response;
}
}
Use the [AllowAnonymous] attribute to allow anonymous access to specific functions:
using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Http;
using Microsoft.AspNetCore.Authorization;
using System.Net;
public class MyFunction
{
[Function("MyFunction")]
[AllowAnonymous]
public async Task<HttpResponseData> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req,
FunctionContext executionContext)
{
var response = req.CreateResponse(HttpStatusCode.OK);
await response.WriteStringAsync("Hello, anonymous user!");
return response;
}
}
Contributions are welcome! Please open an issue or submit a pull request on GitHub.
This project is licensed under the MIT License. See the LICENSE file for details.
For any questions or feedback, please contact the project maintainers.