Beispiel #1
0
 /// <summary>Gets this instance.</summary>
 /// <returns></returns>
 public MethodNotFoundModel Get()
 {
     return(new MethodNotFoundModel
     {
         RequestMethod = requestContextResolver.GetContext().Request.Method
     });
 }
Beispiel #2
0
 /// <summary>Gets the with default enable head.</summary>
 /// <returns></returns>
 public RequestHeadModel GetWithDefaultEnableHead()
 {
     return(new RequestHeadModel
     {
         Configured = requestContextResolver.GetContext().Configuration.EnableHeadForGetRequests
     });
 }
Beispiel #3
0
 /// <summary>Gets the with authorization.</summary>
 /// <returns></returns>
 public AuthorizationModel GetWithAuthorization()
 {
     return(new AuthorizationModel
     {
         IsAuthorized = contextResolver.GetContext().Request.ClientAuthorizationInfo?.AuthResults?.All(a => a.IsAuthorized),
         AuthorizedBy = contextResolver.GetContext().Request.ClientAuthorizationInfo?.AuthorizedBy ?? AuthorizationType.None
     });
 }
Beispiel #4
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                IPipelineComponent pipeline = null;

                try
                {
                    if (context.RequestServices != null)
                    {
                        pipeline = context.RequestServices.GetService(Type.GetType(PipelineType.AssemblyQualifiedName)) as IPipelineComponent;
                    }
                }
                catch { }

                if (pipeline == null)
                {
                    try
                    {
                        pipeline = Activator.CreateInstance(Type.GetType(PipelineType.AssemblyQualifiedName)) as IPipelineComponent;
                    }
                    catch { }
                }

                if (pipeline != null)
                {
                    await pipeline.Invoke(contextResolver).ConfigureAwait(false);
                }
            }
        }
Beispiel #5
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public async Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                IEndpointValidator validator = null;

                try
                {
                    if (context.RequestServices != null)
                    {
                        validator = context.RequestServices.GetService(Type.GetType(ValidatorType.AssemblyQualifiedName)) as IEndpointValidator;
                    }
                }
                catch { }

                if (validator == null)
                {
                    try
                    {
                        validator = Activator.CreateInstance(Type.GetType(ValidatorType.AssemblyQualifiedName)) as IEndpointValidator;
                    }
                    catch { }
                }

                if (validator != null)
                {
                    return(await validator.Validate(contextResolver).ConfigureAwait(false));
                }
            }

            return(null);
        }
Beispiel #6
0
        /// <summary>Activates the <see cref="DeepSleep.Auth.IAuthorizationProvider" />.</summary>
        /// <remarks>
        /// For activation to be successful, the <see cref="IAuthorizationProvider" /> must contain a public parameterless constructor
        /// or be accessible via DI using <see cref="IServiceProvider"/>
        /// </remarks>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns>The <see cref="DeepSleep.Auth.IAuthorizationProvider" /></returns>
        protected virtual IAuthorizationProvider Activate(IApiRequestContextResolver contextResolver)
        {
            IAuthorizationProvider provider = null;

            var context = contextResolver?.GetContext();

            if (context != null)
            {
                try
                {
                    if (context.RequestServices != null)
                    {
                        provider = context.RequestServices.GetService(Type.GetType(typeof(T).AssemblyQualifiedName)) as IAuthorizationProvider;
                    }
                }
                catch { }

                if (provider == null)
                {
                    try
                    {
                        provider = Activator.CreateInstance(Type.GetType(typeof(T).AssemblyQualifiedName)) as IAuthorizationProvider;
                    }
                    catch { }
                }
            }

            return(provider);
        }
Beispiel #7
0
        /// <summary>Invokes the specified httpcontext.</summary>
        /// <param name="httpcontext">The httpcontext.</param>
        /// <param name="contextResolver">The context resolver.</param>
        /// <param name="requestPipeline">The request pipeline.</param>
        /// <param name="config">The config.</param>
        /// <returns></returns>
        public async Task Invoke(HttpContext httpcontext, IApiRequestContextResolver contextResolver, IApiRequestPipeline requestPipeline, IDeepSleepServiceConfiguration config)
        {
            var path = httpcontext?.Request?.Path.ToString() ?? string.Empty;

            if (!IsIncludedPath(path, config.IncludePaths))
            {
                await apinext.Invoke(httpcontext);

                return;
            }

            if (IsExcludedPath(path, config.ExcludePaths))
            {
                await apinext.Invoke(httpcontext);

                return;
            }

            contextResolver.SetContext(await BuildApiRequestContext(httpcontext));
            var context = contextResolver.GetContext();

            var defaultRequestConfiguration = context.RequestServices.GetService(typeof(IDeepSleepRequestConfiguration)) as IDeepSleepRequestConfiguration;

            await context.ProcessApiRequest(httpcontext, contextResolver, requestPipeline, defaultRequestConfiguration);
        }
Beispiel #8
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="apiRequestContextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver apiRequestContextResolver)
        {
            var context             = apiRequestContextResolver?.GetContext();
            var suggestedStatusCode = context.Configuration.ValidationErrorConfiguration.UriBindingErrorStatusCode;

            return(Task.FromResult(ApiValidationResult.Single("VALIDATOR-3", suggestedHttpStatusCode: suggestedStatusCode)));
        }
Beispiel #9
0
        /// <summary>Activates the <see cref="DeepSleep.Auth.IAuthenticationProvider" />.</summary>
        /// <remarks>
        /// For activation to be successful, the <see cref="IAuthenticationProvider" /> must contain a public parameterless constructor
        /// or be accessible via DI using <see cref="IServiceProvider"/>
        /// </remarks>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns>The <see cref="DeepSleep.Auth.IAuthenticationProvider" /></returns>
        public IAuthenticationProvider Activate(IApiRequestContextResolver contextResolver)
        {
            IAuthenticationProvider provider = null;
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                try
                {
                    if (context.RequestServices != null)
                    {
                        provider = context.RequestServices.GetService(Type.GetType(AuthenticationProviderType.AssemblyQualifiedName)) as IAuthenticationProvider;
                    }
                }
                catch (Exception ex)
                {
                    context.Log(ex.ToString());
                }

                if (provider == null)
                {
                    try
                    {
                        provider = Activator.CreateInstance(Type.GetType(AuthenticationProviderType.AssemblyQualifiedName)) as IAuthenticationProvider;
                    }
                    catch (Exception ex)
                    {
                        context.AddInternalException(ex);
                        context.Log(ex.ToString());
                    }
                }
            }

            return(provider);
        }
Beispiel #10
0
        public ItemsRs GetWithItems()
        {
            var found1 = contextResolver.GetContext().TryGetItem <string>("TestItem", out var value1);
            var found2 = contextResolver.GetContext().TryGetItem <string>("TestItem2", out var value2);
            var found3 = contextResolver.GetContext().TryGetItem <string>("TestItem3", out var value3);

            return(new ItemsRs
            {
                Found1 = found1,
                Value1 = value1,

                Found2 = found2,
                Value2 = value2,

                Found3 = found3,
                Value3 = value3
            });
        }
Beispiel #11
0
        public RequestModel GetRequest()
        {
            var context = contextResolver.GetContext();

            return(new RequestModel
            {
                Path = context.Request.Path,
                RequestUri = context.Request.RequestUri
            });
        }
Beispiel #12
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            await apinext.Invoke(contextResolver).ConfigureAwait(false);

            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            await context.ProcessHttpResponseMessages(contextResolver).ConfigureAwait(false);
        }
Beispiel #13
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            if (await context.ProcessHttpRequestCanceled().ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Beispiel #14
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context != null)
            {
                context.TryAddItem(nameof(CustomRequestPipelineComponent), "SET");
            }

            return(Task.CompletedTask);
        }
Beispiel #15
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            await apinext.Invoke(contextResolver).ConfigureAwait(false);

            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var formatterFactory = context?.RequestServices?.GetService <IDeepSleepMediaSerializerFactory>();

            await context.ProcessHttpResponseBodyWriting(contextResolver, formatterFactory).ConfigureAwait(false);
        }
Beispiel #16
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context             = contextResolver?.GetContext();
            var suggestedStatusCode = context.Configuration.ValidationErrorConfiguration.UriBindingErrorStatusCode;

            var results = new List <ApiValidationResult>();

            results.Add(ApiValidationResult.Failure("VALIDATOR-4.1", suggestedHttpStatusCode: suggestedStatusCode));
            results.Add(ApiValidationResult.Failure("VALIDATOR-4.2", suggestedHttpStatusCode: suggestedStatusCode));

            return(Task.FromResult(results as IList <ApiValidationResult>));
        }
Beispiel #17
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            await apinext.Invoke(contextResolver).ConfigureAwait(false);

            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var defaultRequestConfiguration = context.RequestServices.GetService <IDeepSleepRequestConfiguration>();

            await context.ProcessHttpResponseCaching(defaultRequestConfiguration).ConfigureAwait(false);
        }
Beispiel #18
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var formUrlEncodedObjectSerializer = context?.RequestServices?.GetService <IFormUrlEncodedObjectSerializer>();

            if (await context.ProcessHttpRequestUriBinding(formUrlEncodedObjectSerializer).ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Beispiel #19
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver.GetContext();
            var body    = context.Request.InvocationContext.Models <DataAnnotationsBodyModel>().FirstOrDefault();
            var uri     = context.Request.InvocationContext.Models <DataAnnotationsUriModel>().FirstOrDefault();

            if (body.Value != uri.Value)
            {
                return(Task.FromResult(ApiValidationResult.Single("Body value and Uri value must be the same")));
            }

            return(Task.FromResult(ApiValidationResult.Success()));
        }
Beispiel #20
0
        /// <summary>Tasks the invoker.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public async Task TaskInvoker(IApiRequestContextResolver contextResolver)
        {
            var context            = contextResolver.GetContext();
            var registeredPipeline = this.pipeline.RegisteredPipeline;
            var index = registeredPipeline.FirstOrDefault(p => p.Value.type == this.type).Key;

            var next = (index >= registeredPipeline.Count - 1)
                ? new ApiRequestDelegate(TaskFinisher)
                : registeredPipeline[index + 1].requestDelegate;

            var instance = Activator.CreateInstance(this.type, new object[] { next }) as IPipelineComponent;

            await instance.Invoke(contextResolver).ConfigureAwait(false);
        }
Beispiel #21
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            try
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
            finally
            {
                var context = contextResolver
                              .GetContext()
                              .SetThreadCulure();

                await context.ProcessHttpResponseCrossOriginResourceSharing().ConfigureAwait(false);
            }
        }
Beispiel #22
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var routes   = context.RequestServices.GetService <IApiRoutingTable>();
            var resolver = context.RequestServices.GetService <IUriRouteResolver>();
            var defaultRequestConfiguration = context.RequestServices.GetService <IDeepSleepRequestConfiguration>();

            if (await context.ProcessHttpRequestCrossOriginResourceSharingPreflight(routes, resolver, defaultRequestConfiguration).ConfigureAwait(false))
            {
                await this.apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Beispiel #23
0
        public Task <AuthenticationResult> Authenticate(IApiRequestContextResolver contextResolver)
        {
            var context     = contextResolver.GetContext();
            var clientValue = context.Request.ClientAuthenticationInfo.AuthValue ?? string.Empty;
            var isMatch     = clientValue == "91E4BCD0-9C67-4AA1-9821-D2AC6B7AB037";

            if (!isMatch)
            {
                return(Task.FromResult(new AuthenticationResult("InvalidToken")));
            }

            var myIPrincipal = new SecurityContextPrincipal(1, new[] { "SiteUser" }, "AuthType");

            return(Task.FromResult(new AuthenticationResult(true, myIPrincipal)));
        }
Beispiel #24
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var routes               = context?.RequestServices.GetService <IApiRoutingTable>();
            var resolver             = context?.RequestServices.GetService <IUriRouteResolver>();
            var defaultRequestConfig = context?.RequestServices?.GetService <IDeepSleepRequestConfiguration>();

            if (await context.ProcessHttpRequestMethod(routes, resolver, defaultRequestConfig).ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Beispiel #25
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context?.ValidationState() != ApiValidationState.Failed)
            {
                context.TryAddItem <string>("TestItem", "TestItemValue-ShouldBe-Overridden-First");
                context.UpsertItem <string>("TestItem", "TestItemValue-ShouldBe-Overridden");
                context.UpsertItem <string>("TestItem", "TestItemValue");
                context.TryAddItem <string>("TestItem", "TestItemValue-ShouldBe-Overridden-First");


                context.UpsertItem <string>("TestItem2", "TestItemValue2");
            }

            return(Task.FromResult(null as IList <ApiValidationResult>));
        }
Beispiel #26
0
        /// <summary>Validates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <IList <ApiValidationResult> > Validate(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver?.GetContext();

            if (context?.ValidationState() != ApiValidationState.Failed)
            {
                if (context.Items.TryGetValue(nameof(CustomRequestPipelineComponent), out var beforeValidator))
                {
                    if (beforeValidator as string == "SET")
                    {
                        context.TryAddItem(nameof(RequestPipelineModelValidator), "VALIDATOR-SET");
                    }
                }
            }

            return(Task.FromResult(null as IList <ApiValidationResult>));
        }
Beispiel #27
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            try
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                var context = contextResolver
                              .GetContext()
                              .SetThreadCulure();

                var apiServiceConfiguration = context?.RequestServices?.GetService <IDeepSleepServiceConfiguration>();

                await context.ProcessHttpResponseUnhandledException(contextResolver, ex, apiServiceConfiguration).ConfigureAwait(false);
            }
        }
Beispiel #28
0
        /// <summary>Authenticates the specified API request context resolver.</summary>
        /// <param name="contextResolver">The API request context resolver.</param>
        /// <returns></returns>
        public Task <AuthenticationResult> Authenticate(IApiRequestContextResolver contextResolver)
        {
            var context    = contextResolver?.GetContext();
            var acceptable = "T0RrMlJqWXpNVFF0UmtReFF5MDBRamN5TFVJeE5qZ3RPVGxGTlRBek5URXdNVUkz";
            var authValue  = context.Request.ClientAuthenticationInfo.AuthValue ?? string.Empty;

            if (string.IsNullOrWhiteSpace(authValue))
            {
                return(Task.FromResult(new AuthenticationResult("EmptyStaticToken")));
            }

            if (authValue != acceptable)
            {
                return(Task.FromResult(new AuthenticationResult("InvalidStaticToken")));
            }

            return(Task.FromResult(new AuthenticationResult(true)));
        }
Beispiel #29
0
        /// <summary>Invokes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public override async Task Invoke(IApiRequestContextResolver contextResolver)
        {
            var context = contextResolver
                          .GetContext()
                          .SetThreadCulure();

            var beforePipelines = context?.Configuration?.PipelineComponents?
                                  .Where(p => p.Placement == PipelinePlacement.BeforeEndpointValidation)
                                  .OrderBy(p => p.Order)
                                  .ToList() ?? new List <IRequestPipelineComponent>();

            foreach (var pipeline in beforePipelines)
            {
                await pipeline.Invoke(contextResolver).ConfigureAwait(false);
            }

            if (await context.ProcessHttpEndpointValidation().ConfigureAwait(false))
            {
                await apinext.Invoke(contextResolver).ConfigureAwait(false);
            }
        }
Beispiel #30
0
        /// <summary>Authorizes the specified context resolver.</summary>
        /// <param name="contextResolver">The context resolver.</param>
        /// <returns></returns>
        public Task <AuthorizationResult> Authorize(IApiRequestContextResolver contextResolver)
        {
            var context     = contextResolver.GetContext();
            var rolesNeeded = new List <string> {
                "AdminUser"
            };

            var principal = context.Request.ClientAuthenticationInfo.Principal;

            if ((principal?.Identity?.IsAuthenticated ?? false) == false)
            {
                return(Task.FromResult(new AuthorizationResult("NotAuthenticated")));
            }

            foreach (var role in rolesNeeded)
            {
                if (!principal.IsInRole(role))
                {
                    return(Task.FromResult(new AuthorizationResult("InaccessibleRole")));
                }
            }

            return(Task.FromResult(new AuthorizationResult(true)));
        }