简体   繁体   中英

How can I use Authorize attributes in HttpTrigger of Azure Function

Our system is role based and makes a lot of use of the Authorize attribute

In our App Services we use the code below to set this up:

public void ConfigureAuth(IApplicationBuilder app)
{
    if (Configuration.GetValue<bool>("UseLoadTest"))
    {
        app.UseMiddleware<ByPassAuthMiddleware>();
    }

    app.UseAuthentication();
}

How can I do this with an Azure function Http Trigger?

There is no UseAuthentication() method on IFunctionsHostBuilder .

public override void Configure(IFunctionsHostBuilder builder)
{
}

I'm using .NET Core 3.1.

AFAIK Functions doesn't have such an attribute currently. This issue tracks the work going in to support Filters for Functions but this is still in preview.

Based on the above preview feature, looks like this is one library - dark-loop/functions-authorize - that adds support for this.

I started using Middleware for this: Took inspiration from this article: https://jinalkumarpatel.hashnode.dev/azure-functions-middleware-part-2-authentication-middleware

Create the middleware:

public class BearerAuthenticationMiddleware
    : IFunctionsWorkerMiddleware
{
    private readonly ILogger<BearerAuthenticationMiddleware> logger;

    public BearerAuthenticationMiddleware(ILogger<BearerAuthenticationMiddleware> logger)
    {
        this.logger = logger;
    }
    public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
    {
        if (context.IsHttpTriggerFunction())
        {
            var headers = context.BindingContext.BindingData["Headers"]?.ToString();
            var httpHeaders = System.Text.Json.JsonSerializer.Deserialize<HttpHeaders>(headers);
            if (httpHeaders?.Authorization != null &&
                httpHeaders.Authorization.StartsWith("Bearer"))
            {
                //Validation logic for your token. Here If Bearer present I consider as Valid.
                if (httpHeaders.Authorization.Contains("admin"))
                {
                    // Originally based on token get user role.
                    // Put into context.Items so it will be used by next middleware.
                    context.Items.Add("UserRole", "Admin");
                }
                await next(context);
            }
            else
            {
                await context.CreateJsonResponse(System.Net.HttpStatusCode.Unauthorized, new { Message = "Token is not valid." });
            }
        }
        else
        {
            await next(context);
        }
    }
}

Register the middleware:

public class Program
{
    public static void Main()
    {
        var host = new HostBuilder()
            .ConfigureFunctionsWorkerDefaults(configure=>
            {
                // other middleware also configure following way.
                // It will execute in same order it is configured over here.
                configure.UseMiddleware<SimpleMiddleware>();
            })
            .Build();

        host.Run();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM