简体   繁体   中英

How to add custom startup class in http trigger azure function app

Azure http trigger function apps doesn't comes with a startup. I want to implement azure AD authentication which adds UseAuthentication method of Microsoft.AspNetCore.Builder to validate the token an authenticate the user.

Currently Http trigger is hitting the Run method directly.There should be some middle ware logic to add servies and configurations

Startup Class

public void ConfigureServices(IServiceCollection services)
{            services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
               .AddAzureADBearer(options => Configuration.Bind("ConfigName", options));
}


public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory logger)
{
   app.UseAuthentication();
}

post implementation below Authorize attribute should validate the token and allow/deny the user access.

public static class Function1
   {
       [Authorize]
       [FunctionName("Function1")]
       public static async Task<IActionResult> Run(
           [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
           ILogger log)
       {
           log.LogInformation("C# HTTP trigger function processed a request.");

           return (ActionResult)new OkObjectResult($"Hello");
       }
   }

Please help.

Azure function by default don't have a Startup class. You can add services using an IWebJobStartup , but you cannot add custom middleware.

You could [assembly: WebJobsStartup(typeof(MyNamespace.Startup))] to register and configure the dependency injection bindings. Refer to this article .

[assembly: WebJobsStartup(typeof(MyNamespace.MyStartup))]
namespace MyNamespace
{
    public static class Function1
    {
        [FunctionName("Function1")]
        public static async Task<IActionResult> Run(
        [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,ILogger log)
        {
            log.LogInformation("C# HTTP trigger function processed a request.");

            return (ActionResult)new OkObjectResult($"Hello");
        }
    }
    public class MyStartup : IWebJobsStartup
    {
        public void Configure(IWebJobsBuilder builder)
        {
        builder.Services...
        }
    }
}

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