public async Task Invoke(IDictionary <string, object> env)
        {
            var requestPath = (string)env["owin.RequestPath"];

            requestPath = PathUtil.CheckRequestPath(requestPath, options.DefaultFile);
            var filePath       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, options.RootDirectory, requestPath);
            var fileTag        = options.ETagProvider.GetETag(filePath);
            var requestHeaders = (IDictionary <string, string[]>)env["owin.RequestHeaders"];

            if (!string.IsNullOrEmpty(fileTag))
            {
                if (requestHeaders.ContainsKey("If-None-Match"))
                {
                    var tagValue = requestHeaders["If-None-Match"];
                    if (tagValue != null && tagValue.Length > 0)
                    {
                        if (options.ETagProvider.CompareETag(filePath, tagValue[0]))
                        {
                            env["owin.ResponseStatusCode"]   = (int)HttpStatusCode.NotModified;
                            env["owin.ResponseReasonPhrase"] = "Not Modified";
                            return;
                        }
                    }
                }
                else
                {
                    await next.Invoke(env);

                    var responseHeaders = (IDictionary <string, string[]>)env["owin.ResponseHeaders"];
                    responseHeaders["ETag"] = new [] { fileTag };
                    return;
                }
            }
            await next.Invoke(env);
        }
        public async Task Invoke(IDictionary <string, Object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            context.Get <TextWriter>("host.TraceOutput").WriteLine("Currently in ActiveDirectory authentication middleware");

            var debug = true;

            if (ActiveDirectoryLogin("x", "x", debug))
            {
                // _next is only invoked if authentication succeeds:
                context.Response.StatusCode   = 200;
                context.Response.ReasonPhrase = "OK";
                await _next.Invoke(environment);
            }
            else
            {
                context.Response.StatusCode   = 401;
                context.Response.ReasonPhrase = "Not Authorized";

                await context.Response.WriteAsync(string.Format("<h1>Error {0}-{1}",
                                                                context.Response.StatusCode,
                                                                context.Response.ReasonPhrase));
            }
        }
Пример #3
0
        public AppFunc AuthenticationMiddleWare(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) =>
            {
                IOwinContext context = new OwinContext(environment);

                string[] query = context.Request.QueryString.Value.Split(Convert.ToChar(PARAGRAPH_SEPARATOR));

                var isAuthorized = query[0] == AUTHENTICATION_CODE;
                if (!isAuthorized)
                {
                    context.Response.StatusCode   = 401;
                    context.Response.ReasonPhrase = "Not Authorized";

                    // Send back an error page:
                    await context.Response.WriteAsync(string.Format("<h1>Error {0}-{1}",
                                                                    context.Response.StatusCode,
                                                                    context.Response.ReasonPhrase));
                }
                else
                {
                    // we will only continue if authentication succeeds:
                    context.Response.StatusCode   = 200;
                    context.Response.ReasonPhrase = "OK";
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #4
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);
            await context.Response.WriteAsync(_message);

            await _next.Invoke(environment);
        }
Пример #5
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            // get owin context from environment
            IOwinContext context = new OwinContext(environment);

            // check for token.
            var user = context.Authentication.User;

            if (user != null)
            {
                // if there was a token and user is set, make sure claims are up to date
                var issuedUtc = new DateTime(long.Parse(user.FindFirst(OwinKeys.Ticks).Value));
                var id        = int.Parse(user.FindFirst(OwinKeys.AuthUserId).Value);
                var role      = int.Parse(user.FindFirst(OwinKeys.UserRoleId).Value);
                if (!_roleManager.CheckRoleTimes(id, role, issuedUtc))
                {
                    if (role > 0)
                    {
                        // reject - add inidcation header
                        context.Response.Headers.Add("Access-Control-Expose-Headers", new[] { "X-Update-Roles" });
                        context.Response.Headers.Add("X-Update-Roles", new[] { "true" });
                    }
                    // manually add cors header for this response
                    context.Response.Headers.Add("Access-Control-Allow-Origin", new[] { AppSettings.GetAdminSite() });
                    context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                    return;
                }
            }
            await _next.Invoke(environment);
        }
Пример #6
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                try {
                    await next.Invoke(environment);
                } catch (Exception ex) {
                    try {
                        var context = PipelineContext.GetOrCreate(environment);
                        var log     = Factory.ResolveSingleton <ILog>();
                        log.WriteLine($"Exception caught during handling of request {context.Request.Uri}: {ex}");
                    } catch {
                    }

                    if (environment != null)
                    {
                        if (environment.ContainsKey("owin.ResponseStatusCode"))
                        {
                            environment["owin.ResponseStatusCode"] = 500;
                        }
                        else
                        {
                            environment.Add("owin.ResponseStatusCode", 500);
                        }
                    }
                }
            };

            return(appFunc);
        }
Пример #7
0
        private async void ProcessRequest(HttpListenerContext context, AppFunc app, OwinLogger logger)
        {
            OwinHttpListenerContext owinContext = null;

            try
            {
                GetPathAndQuery(context.Request, out var pathBase, out var path, out var query);
                owinContext = new OwinHttpListenerContext(context, pathBase, path, query);
                await app.Invoke(owinContext.Environment);

                if (!context.Connection.IsClosed)
                {
                    owinContext.Response.CompleteResponse();
                }

                owinContext.Response.Close();

                owinContext.End();
                owinContext.Dispose();
            }
            catch (Exception ex)
            {
                if (owinContext != null)
                {
                    owinContext.End(ex);
                    owinContext.Dispose();
                }
            }
        }
        public async Task Invoke(IDictionary <string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            // If this is a logging request (based on its url), do the logging and don't pass on the request
            // to the rest of the pipeline.

            if (LoggingUrlHelpers.IsLoggingUrl(context.Request.Uri.OriginalString))
            {
                try
                {
                    ProcessRequest(context);
                }
                catch
                {
                    // An exception was thrown while processing a log request.
                    // Just eat it here, seeing there doesn't seem to be an easy and reliable way
                    // to log the exception.
                }
                return;
            }

            // It was not a logging request
            await _next.Invoke(environment);
        }
Пример #9
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            // In the real world we would do REAL auth processing here...

            var isAuthorized = context.Request.QueryString.Value == "ahmed";

            if (!isAuthorized)
            {
                context.Response.StatusCode   = 401;
                context.Response.ReasonPhrase = "Not Authorized";

                // Send back a really silly error page:
                await context.Response.WriteAsync(string.Format("<h1>Error {0}-{1}",
                                                                context.Response.StatusCode,
                                                                context.Response.ReasonPhrase));
            }
            else
            {
                // _next is only invoked is authentication succeeds:
                context.Response.StatusCode   = 200;
                context.Response.ReasonPhrase = "OK";
                await _next.Invoke(environment);
            }
        }
Пример #10
0
        public async Task Invoke(Env environment)
        {
            if (IsCallToHealthCheck(environment))
            {
                var responseHeaders = (IDictionary <string, string[]>)environment["owin.ResponseHeaders"];
                responseHeaders["Content-Type"] = new[] { Constants.Response.ContentType.Json + "; charset=utf-8" };

                var responseStream = (Stream)environment["owin.ResponseBody"];

                var healthCheckService = new HealthCheckService(configuration, new VersionProvider(configuration),
                                                                systemCheckerResolverFactory());
                var result = healthCheckService.CheckHealth(IsIntrusive(environment));

                using (var writeStream = new MemoryStream())
                {
                    var contentLength = new HealthResultJsonSerializer().SerializeToStream(writeStream, result);
                    responseHeaders["Content-Length"] = new[] { contentLength.ToString("D") };
                    writeStream.Position = 0;

                    await writeStream.CopyToAsync(responseStream);
                }
            }
            else
            {
                await next.Invoke(environment);
            }
        }
Пример #11
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            if (environment == null)
            {
                throw new ArgumentNullException(nameof(environment));
            }

            var envCopy = environment;

            var context       = new OwinContext(environment);
            var userPrincipal = context.Authentication.User;

            var newUserClaims = ReadyNewClaimsList(userPrincipal);

            if (_options.UseCaching)
            {
                newUserClaims.AddRange(await _options.ClaimsCacheManager.GetClaimsFromCache(context));
            }
            else
            {
                var newClaims = await _options.ProviderRunner.RunAllProviderTasksAsync(envCopy, _options.Providers);

                await _options.ClaimsCacheManager.SetClaimsInCache(context, newClaims);

                newUserClaims.AddRange(newClaims);
            }

            var identity     = new ClaimsIdentity(newUserClaims, context.Authentication.User.Identity.AuthenticationType);
            var newPrincipal = new ClaimsPrincipal(identity);

            context.Request.User = newPrincipal;

            await _next.Invoke(environment);
        }
Пример #12
0
 protected override Task Invoke(
     IDictionary <string, object> env,
     HttpRequestMessage requestMessage,
     CancellationToken cancellationToken)
 {
     return(_next.Invoke(env));
 }
Пример #13
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            Console.WriteLine("{0} {1} {2}", DateTime.Now, env["owin.RequestMethod"], env["owin.RequestPath"]);
            await next.Invoke(env);

            Console.WriteLine("Return HTTP status: {0}", env["owin.ResponseStatusCode"]);
        }
Пример #14
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);
            await context.Response.WriteAsync("<h1>Middleware 3 triggered</h1>");

            await _next.Invoke(environment);
        }
Пример #15
0
        public async Task Invoke(IDictionary <string, object> envionment)
        {
            await _next.Invoke(envionment);

            IOwinContext owinContext = new OwinContext(envionment);

            Console.WriteLine($"URI: {owinContext.Request.Uri} Status Code: {owinContext.Response.StatusCode}");
        }
Пример #16
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            var owinContext = new  OwinContext(env);

            Debug.WriteLine($"incoming Request Path:{owinContext.Request.Path}");
            await _next.Invoke(env);

            Debug.WriteLine($"outgoing Respose path{owinContext.Request.Path}");
        }
Пример #17
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            // inbound
            IOwinContext context = new OwinContext(env);
            await context.Response.WriteAsync("<h1>Hello from My 2nd Middleware</h1>");

            // call next middleware func
            await _next.Invoke(env);
        }
Пример #18
0
        public async Task Invoke(IDictionary <string, Object> environment)
        {
            await _next.Invoke(environment);

            IOwinContext context = new OwinContext(environment);
            await context.Response.WriteAsync($"<h1>{_options.GetGreetingsfromUser()}</h1>");

            context.Response.StatusCode   = 200;
            context.Response.ReasonPhrase = "OK";
        }
Пример #19
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            // Pass everything up through the pipeline first:
            await _next.Invoke(environment);

            // Do the logging on the way out:
            IOwinContext context = new OwinContext(environment);

            Console.WriteLine("URI: {0} Status Code: {1}", context.Request.Uri, context.Response.StatusCode);
        }
Пример #20
0
        static AppFunc LoggingMiddleware(AppFunc next)
        {
            return(async environment =>
            {
                Console.WriteLine("Receiving request for \"{0}\"", environment["owin.RequestPath"]);

                await next.Invoke(environment);

                Console.WriteLine("Returning with status {0}", environment["owin.ResponseStatusCode"]);
            });
        }
Пример #21
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                if (AddCorsHeaders(environment))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #22
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc FilterRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                if (Authenticated(environment))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #23
0
        private AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                var context = PipelineContext.GetOrCreate(environment);
                if (!ProcessRequest(context))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #24
0
            //	{Microsoft.Owin.Host.SystemWeb.CallEnvironment.AspNetDictionary}
            public Task Invoke(IDictionary <string, object> environment)
            {
                PrintMessage("TypeMiddleWare invoke");
                UpdateInvokeCount(environment);
                if (_next != null)
                {
                    return(_next.Invoke(environment));
                }
                var context = new OwinContext(environment);

                return(_middleware.Invoke(context));
            }
Пример #25
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                var context = PipelineContext.GetOrCreate(environment);
                if (!ServeFromFileSystem(environment))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #26
0
        private static AppFunc InterfaceMiddleware(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> dic) =>
            {
                IOwinContext context = new OwinContext(dic);
                await context.Response.WriteAsync("usando a IOwinContext <br>");

                await next.Invoke(dic);
            };

            return(appFunc);
        }
Пример #27
0
        public Task Invoke(IDictionary <string, object> env)
        {
            var path = env[OwinConstants.RequestPath].ToString();

            if (urls.Any(path.StartsWith))
            {
                return(fileServer.Invoke(env));
            }
            else
            {
                return(app.Invoke(env));
            }
        }
Пример #28
0
		public AppFunc AuthMiddleWare(AppFunc next)
		{
			AppFunc appFunc = async (IDictionary<string, object> environment) =>
			{
				var response = environment["owin.ResponseBody"] as Stream;
				using (var writer = new StreamWriter(response))
				{
					// await writer.WriteAsync("<h1>Hello from My First Middleware</h1>");
				}

				await next.Invoke(environment);
			};
			return appFunc;
		}
Пример #29
0
 public async Task InvokeAsync(IDictionary <string, object> context)
 {
     if (context["owin.RequestPath"] as string == "/")
     {
         using (var writer = new StreamWriter(context["owin.ResponseBody"] as Stream))
         {
             await writer.WriteAsync("Hello World!");
         }
     }
     else
     {
         await next.Invoke(context);
     }
 }
Пример #30
0
 // Este método é um middleware.
 private static AppFunc MetodoTrataRequisicaoMiddleware(AppFunc next)
 {
     return(
         // Contexto é um dicionário que contém toda a informação sobre a requisição.
         async context =>
     {
         using (var sw = new StreamWriter((Stream)context["owin.ResponseBody"]))
         {
             await sw.WriteAsync("usando o metodo Use <br>");
         }
         await next.Invoke(context);
     }
         );
 }
Пример #31
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            // If there is no next component, a 404 Not Found will be written as the response code here:
            await _next.Invoke(environment);

            IOwinContext context = new OwinContext(environment);

            // Insert the _greeting into the display text:
            await context.Response.WriteAsync(string.Format("<h1>{0}</h1>", _configOptions.GetGreeting()));

            // Update the response code to 200 OK:
            context.Response.StatusCode   = 200;
            context.Response.ReasonPhrase = "OK";
        }
Пример #32
0
 private async Task Invoke(AppFunc next, IDictionary<string, object> env)
 {
     Console.WriteLine("Begin #3");
     await next.Invoke(env);
     Console.WriteLine("End #3");
 }