コード例 #1
0
        public async Task InvokeAsync(FunctionContext context, FunctionExecutionDelegate next)
        {
            if (GetRequestData(context) is HttpRequestData request)
            {
                try
                {
                    var authorizationHeader = request.Headers.FirstOrDefault(x => x.Key.Equals("authorization", StringComparison.InvariantCultureIgnoreCase));
                    if (authorizationHeader.Value is IEnumerable <string> headerValue)
                    {
                        var user = await GetValidUserAsync(headerValue.FirstOrDefault());

                        if (user != null)
                        {
                            context.Items.Add("User", user);
                            await next(context);

                            return;
                        }
                    }
                }
                catch { }

                // NOTE: this middleware requires an authenticated user
                SetRequestResponse(context, request.CreateResponse(HttpStatusCode.Unauthorized));
                return;
            }

            await next(context);
        }
コード例 #2
0
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            var logger = context.GetLogger <AuthenticationMiddleware>();
            var data   = context.BindingContext.BindingData;

            if (data.ContainsKey("Headers"))
            {
                data.TryGetValue("Headers", out var headersObject);

                var headers = JsonSerializer.Deserialize <JsonDocument>(headersObject as string);

                var authzHeaderExists = headers.RootElement.TryGetProperty("Authorization", out JsonElement authorizationHeader);

                if (authzHeaderExists)
                {
                    var token = authorizationHeader.ToString().Substring("Bearer ".Length);

                    var principal = await _authenticationProvider.AuthenticateAsync(context, token);

                    if (principal != null)
                    {
                        await next(context);

                        return;
                    }
                }
            }

            // return 401
        }
コード例 #3
0
        public void InlineMiddleware_RunsInExpectedOrder()
        {
            var services = new ServiceCollection();
            IFunctionsWorkerApplicationBuilder builder = new FunctionsWorkerApplicationBuilder(services);

            builder.Use(next => context =>
            {
                context.Items.Add("Middleware1", null);
                return(next(context));
            });

            builder.UseMiddleware((context, next) =>
            {
                context.Items.Add("Middleware2", null);
                return(next());
            });

            builder.Use(next => context =>
            {
                context.Items.Add("Middleware3", null);
                return(next(context));
            });

            FunctionExecutionDelegate app = builder.Services
                                            .BuildServiceProvider()
                                            .GetService <FunctionExecutionDelegate>();

            var context = _mockContext.Object;

            context.Items = new Dictionary <object, object>();

            app(context);

            Assert.Equal(new[] { "Middleware1", "Middleware2", "Middleware3" }, context.Items.Keys);
        }
コード例 #4
0
 public FunctionsApplication(FunctionExecutionDelegate functionExecutionDelegate, IFunctionContextFactory functionContextFactory,
                             IOptions <WorkerOptions> workerOptions, ILogger <FunctionsApplication> logger, IWorkerDiagnostics diagnostics)
 {
     _functionExecutionDelegate = functionExecutionDelegate ?? throw new ArgumentNullException(nameof(functionExecutionDelegate));
     _functionContextFactory    = functionContextFactory ?? throw new ArgumentNullException(nameof(functionContextFactory));
     _workerOptions             = workerOptions ?? throw new ArgumentNullException(nameof(workerOptions));
     _logger      = logger ?? throw new ArgumentNullException(nameof(logger));
     _diagnostics = diagnostics ?? throw new ArgumentNullException(nameof(diagnostics));
 }
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            foreach (IConfigurationRefresher refresher in Refreshers)
            {
                _ = refresher.TryRefreshAsync();
            }

            await next(context).ConfigureAwait(false);
        }
        public FunctionExecutionDelegate Build()
        {
            FunctionExecutionDelegate pipeline = context => Task.CompletedTask;

            pipeline = _middlewareCollection
                       .Reverse()
                       .Aggregate(pipeline, (p, d) => d(p));

            return(pipeline);
        }
コード例 #7
0
 public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
 {
     try
     {
         await next(context);
     }
     catch (Exception ex)
     {
         var logger = context.GetLogger(context.FunctionDefinition.Name);
         logger.LogError("Unexpected Error in {0}: {1}", context.FunctionDefinition.Name, ex.Message);
     }
 }
コード例 #8
0
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            ArgumentNullException.ThrowIfNull(context, nameof(context));
            ArgumentNullException.ThrowIfNull(next, nameof(next));

            var scope = AsyncScopedLifestyle.BeginScope(_container);

            await using (scope.ConfigureAwait(false))
            {
                context.InstanceServices = new SimpleInjectorServiceProviderAdapter(scope.Container !);
                await next(context).ConfigureAwait(false);
            }
        }
コード例 #9
0
        /// <summary>
        /// Invoke Pass through middleware
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task Invoke(FunctionExecutionContext context, FunctionExecutionDelegate next)
        {
            context.Logger?.Log(LogLevel.Information, "Inside pass-through middleware");

            context.InvocationResult = new HttpResponseData(HttpStatusCode.OK);

            var response = context.InvocationResult as HttpResponseData;

            response.Body += "\n Request stage - Pass-through middleware";

            await next.Invoke(context);

            ResponseStage(context);
        }
コード例 #10
0
        /// <summary>
        /// Invoke Bypass middleware
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task Invoke(FunctionExecutionContext context, FunctionExecutionDelegate next)
        {
            context.Logger?.Log(LogLevel.Information, "Inside Bypass middleware");

            context.InvocationResult = new HttpResponseData(HttpStatusCode.Unauthorized);

            var response = context.InvocationResult as HttpResponseData;

            response.Body += "\n Request stage - Bypass middleware";

            await Task.FromResult(Task.CompletedTask);

            ResponseStage(context);
        }
コード例 #11
0
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            var logger     = context.GetLogger("Authentication");
            var headerData = context.BindingContext.BindingData["headers"] as string;
            var headers    = JsonSerializer.Deserialize <Dictionary <string, string> >(headerData);

            if (headers.ContainsKey("Authorization"))
            {
                var authorization = headers["Authorization"];
                var bearerHeader  = AuthenticationHeaderValue.Parse(authorization);
                await Authenticate(context, bearerHeader, logger).ConfigureAwait(false);
            }

            await next(context).ConfigureAwait(false);
        }
コード例 #12
0
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            // This is added pre-function execution, function will have access to this information
            // in the context.Items dictionary
            context.Items.Add("middlewareitem", "Hello, from middleware");

            await next(context);

            // This happens after function execution. We can inspect the context after the function
            // was invoked
            if (context.Items.TryGetValue("functionitem", out object value) && value is string message)
            {
                ILogger logger = context.GetLogger <MyCustomMiddleware>();

                logger.LogInformation("From function: {message}", message);
            }
        }
コード例 #13
0
        public Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            ArgumentNullException.ThrowIfNull(context, nameof(context));
            ArgumentNullException.ThrowIfNull(next, nameof(next));

            if (!_identity.HasIdentity && _actorContext.CurrentActor != null)
            {
                if (!string.IsNullOrWhiteSpace(_actorContext.CurrentActor.Identifier))
                {
                    _identity.AssignId(_actorContext.CurrentActor.Identifier);
                }
                else
                {
                    _identity.AssignId(_actorContext.CurrentActor.ActorId.ToString());
                }
            }

            return(next(context));
        }
コード例 #14
0
        public Task Invoke(FunctionExecutionContext context, FunctionExecutionDelegate next)
        {
            foreach (var param in context.FunctionDefinition.Parameters)
            {
                if (param.Type == typeof(FunctionExecutionContext))
                {
                    context.Logger = new InvocationLogger(context.Invocation.InvocationId, _channel.Channel.Writer);
                    param.Value    = context;
                }
                else
                {
                    object?source           = context.Invocation.ValueProvider.GetValue(param.Name);
                    var    converterContext = new DefaultConverterContext(param, source, context);
                    if (TryConvert(converterContext, out object?target))
                    {
                        param.Value = target;
                        continue;
                    }
                }
            }

            return(next(context));
        }
        /// <summary>
        /// Invoke ExceptionHandler middleware
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public async Task Invoke(FunctionExecutionContext context, FunctionExecutionDelegate next)
        {
            context.Logger?.Log(LogLevel.Information, "Inside ExceptionHandler middleware");

            context.InvocationResult = new HttpResponseData(HttpStatusCode.Unauthorized);

            var response = context.InvocationResult as HttpResponseData;

            response.Body += "\n Request stage - ExceptionHandler middleware";

            try
            {
                await next.Invoke(context);
            }
            catch (Exception ex)
            {
                context.Logger?.Log(LogLevel.Error, "Catched unhandled exceptions: " + ex.Message);

                await Task.CompletedTask;
            }

            ResponseStage(context);
        }
コード例 #16
0
        public async Task InvokeAsync(FunctionExecutionContext context, FunctionExecutionDelegate next)
        {
            if (context.InvocationRequest is InvocationRequest invocation)
            {
                var req = invocation.InputData.FirstOrDefault(x => x.Name == "req");

                if (req?.Data?.Http != null)
                {
                    try
                    {
                        var request = new Microsoft.Azure.Functions.Worker.HttpRequestData(req.Data.Http);

                        var authorizationHeader = request.Headers.FirstOrDefault(x => x.Key.Equals("authorization", StringComparison.InvariantCultureIgnoreCase));
                        if (authorizationHeader.Value is string headerValue)
                        {
                            var user = await GetValidUserAsync(headerValue);

                            if (user != null)
                            {
                                context.Items.Add("User", user);
                                await next(context);

                                return;
                            }
                        }
                    }
                    catch { }

                    // NOTE: this middleware requires an authenticated uses.
                    context.InvocationResult = new HttpResponseData(HttpStatusCode.Unauthorized);
                    return;
                }
            }

            await next(context);
        }
コード例 #17
0
 public Task Invoke(FunctionExecutionContext context, FunctionExecutionDelegate next)
 {
     context.Items.Add("Greeting", "Hello from our middleware");
     return(next(context));
 }
コード例 #18
0
        public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
        {
            await next(context);

            AddOutputBindings(context);
        }
コード例 #19
0
 public FunctionBroker(FunctionExecutionDelegate functionExecutionDelegate, IFunctionExecutionContextFactory functionExecutionContextFactory, IFunctionDefinitionFactory functionDescriptorFactory)
 {
     _functionExecutionDelegate       = functionExecutionDelegate ?? throw new ArgumentNullException(nameof(functionExecutionDelegate));
     _functionExecutionContextFactory = functionExecutionContextFactory ?? throw new ArgumentNullException(nameof(functionExecutionContextFactory));
     _functionDescriptorFactory       = functionDescriptorFactory ?? throw new ArgumentNullException(nameof(functionDescriptorFactory));
 }