/// <summary>
        /// Tries to find a secret on the environment that can be used for authentication
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <returns>
        /// A parsed secret
        /// </returns>
        public async Task<ParsedSecret> ParseAsync(IDictionary<string, object> environment)
        {
            Logger.Debug("Start parsing for secret in post body");

            var context = new OwinContext(environment);
            var body = await context.ReadRequestFormAsync();

            if (body != null)
            {
                var id = body.Get("client_id");
                var secret = body.Get("client_secret");

                if (id.IsPresent() && secret.IsPresent())
                {
                    var parsedSecret = new ParsedSecret
                    {
                        Id = id,
                        Credential = secret,
                        Type = Constants.ParsedSecretTypes.SharedSecret
                    };

                    return parsedSecret;
                }
            }

            Logger.Debug("No secet in post body found");
            return null;
        }
        public async Task Invoke(IDictionary<string, object> env)
        {
            var context = new OwinContext(env);

            if (context.Request.Uri.Scheme != Uri.UriSchemeHttps)
            {
                context.Response.StatusCode = 403;
                context.Response.ReasonPhrase = "SSL is required.";

                return;
            }

            if (_options.RequireClientCertificate)
            {
                var cert = context.Get<X509Certificate2>("ssl.ClientCertificate");
                if (cert == null)
                {
                    context.Response.StatusCode = 403;
                    context.Response.ReasonPhrase = "SSL client certificate is required.";

                    return;
                }
            }

            await _next(env);
        }
 public bool Authorize(IDictionary<string, object> owinEnvironment)
 {
     var context = new OwinContext(owinEnvironment);
     var principal = context.Authentication.User;
     var isAuthorized = IsAuthorized(_permissionService, principal);
     return isAuthorized;
 }
예제 #4
0
        public static IAppBuilder UseHangfireServer(
            [NotNull] this IAppBuilder builder,
            [NotNull] BackgroundJobServerOptions options,
            [NotNull] JobStorage storage)
        {
            if (builder == null) throw new ArgumentNullException("builder");
            if (options == null) throw new ArgumentNullException("options");
            if (storage == null) throw new ArgumentNullException("storage");

            var server = new BackgroundJobServer(options, storage);
            Servers.Add(server);

            var context = new OwinContext(builder.Properties);
            var token = context.Get<CancellationToken>("host.OnAppDisposing");
            if (token == default(CancellationToken))
            {
                // https://github.com/owin/owin/issues/27
                token = context.Get<CancellationToken>("server.OnDispose");
            }

            if (token == default(CancellationToken))
            {
                throw new InvalidOperationException("Current OWIN environment does not contain an instance of the `CancellationToken` class under `host.OnAppDisposing` key.");
            }

            token.Register(server.Dispose);

            return builder;
        }
예제 #5
0
        /// <summary>
        /// Evaluates and applies the CORS policy. Responses will be generated for preflight requests.
        /// Requests that are permitted by the CORS policy will be passed onto the next middleware.
        /// </summary>
        /// <param name="environment"></param>
        /// <returns></returns>
        public async Task Invoke(IDictionary<string, object> environment)
        {
            IOwinContext context = new OwinContext(environment);

            CorsRequestContext corsRequestContext = GetCorsRequestContext(context);
            
            CorsPolicy policy = null;
            if (corsRequestContext != null)
            {
                // only obtain a policy if request is a CORS request
                policy = await _corsPolicyProvider.GetCorsPolicyAsync(context.Request);
            }

            if (policy != null && corsRequestContext != null)
            {
                if (corsRequestContext.IsPreflight)
                {
                    await HandleCorsPreflightRequestAsync(context, policy, corsRequestContext);
                }
                else
                {
                    await HandleCorsRequestAsync(context, policy, corsRequestContext);
                }
            }
            else
            {
                await _next(environment);
            }
        }
예제 #6
0
 public async Task Invoke(IDictionary<string, object> env)
 {
     var context = new OwinContext(env);
     await context.Response.WriteAsync("Middleware 2 ");
     await this.next(env);
     await context.Response.WriteAsync("middleware 2 way back: ");
 }
        public OnSendingHeadersTests()
        {
            AppFunc inner = async env =>
            {
                var context = new OwinContext(env);
                context.Response.StatusCode = 404;
                await context.Response.WriteAsync("Test");
            };

            AppFunc inner2 = async env =>
            {
                var context = new OwinContext(env);
                context.Response.OnSendingHeaders(_ =>
                {
                    if (context.Response.StatusCode ==  404)
                    {
                        context.Response.Cookies.Append(CookieName1, "c1");
                    }
                }, null);
                await inner(env);
            };

            _appFunc = async env =>
            {
                var context = new OwinContext(env);
                context.Response.OnSendingHeaders(_ =>
                {
                    if (context.Response.Headers.ContainsKey("Set-Cookie"))
                    {
                        context.Response.Cookies.Append(CookieName2, "c2");
                    }
                }, null);
                await inner2(env);
            };
        }
        public async void EmptyOwinEnvironment()
        {
            var context = new OwinContext();
            var secret = await _parser.ParseAsync(context.Environment);

            secret.Should().BeNull();
        }
 private async Task DeepEndpoint(OwinContext context)
 {
     if (await this.healthCheck().ConfigureAwait(false))
         context.Response.StatusCode = 204;
     else
         context.Response.StatusCode = 503;
 }
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="environment">The OWIN environment.</param>
        /// <returns>Task.</returns>
        /// <exception cref="InvalidOperationException">No SelfTester set on the SelfTestMiddlewareOptions provided.</exception>
        public async Task Invoke(IDictionary<string, object> environment)
        {
            if (_options.SelfTester == null)
            {
                throw new InvalidOperationException("No SelfTester set on the SelfTestMiddlewareOptions provided.");
            }

            var context = new OwinContext(environment);

            if (!IsEndPointUrl(context))
            {
                await _next(environment);
            }
            else {

                if (!await CheckToken(context))
                {
                    return;
                }

                context.Response.ContentType = "application/json";

                ISelfTestResult result = await _options.SelfTester.RunTests();

                string output = JsonConvert.SerializeObject(result, new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                });

                context.Response.StatusCode = (int)HttpStatusCode.OK;

                await context.Response.WriteAsync(output);
                // No call to _next since this is a terminal middleware
            }
        }
		public async Task Invoke(IDictionary<string, object> env)
		{
			IOwinContext context = new OwinContext(env);
			 
			// Buffer the request body
			var requestBuffer = new MemoryStream();
			await context.Request.Body.CopyToAsync(
				requestBuffer);
			requestBuffer.Seek(0, SeekOrigin.Begin);
			 
			context.Request.Body = requestBuffer;
			 
			// Read the body
			var reader = new StreamReader(context.Request.Body);
			string content = await reader.ReadToEndAsync();
			 
			// Seek to the beginning of the stream for the
			// other components to correctly read the request body.
			((MemoryStream)context.Request.Body)
				.Seek(0, SeekOrigin.Begin);
			 
			Console.WriteLine(content);
			 
			await this.next(env);
		}
예제 #12
0
        public void ExpectedKeysAreAvailable()
        {
            var handler = new OwinClientHandler(env =>
            {
                IOwinContext context = new OwinContext(env);

                Assert.Equal("1.0", context.Get<string>("owin.Version"));
                Assert.NotNull(context.Get<CancellationToken>("owin.CallCancelled"));
                Assert.Equal("HTTP/1.1", context.Request.Protocol);
                Assert.Equal("GET", context.Request.Method);
                Assert.Equal("https", context.Request.Scheme);
                Assert.Equal(string.Empty, context.Get<string>("owin.RequestPathBase"));
                Assert.Equal("/A/Path/and/file.txt", context.Get<string>("owin.RequestPath"));
                Assert.Equal("and=query", context.Get<string>("owin.RequestQueryString"));
                Assert.NotNull(context.Request.Body);
                Assert.NotNull(context.Get<IDictionary<string, string[]>>("owin.RequestHeaders"));
                Assert.NotNull(context.Get<IDictionary<string, string[]>>("owin.ResponseHeaders"));
                Assert.NotNull(context.Response.Body);
                Assert.Equal(200, context.Get<int>("owin.ResponseStatusCode"));
                Assert.Null(context.Get<string>("owin.ResponseReasonPhrase"));

                Assert.Equal("example.com", context.Request.Headers.Get("Host"));

                return Task.FromResult(0);
            });
            var httpClient = new HttpClient(handler);
            httpClient.GetAsync("https://example.com/A/Path/and/file.txt?and=query").Wait();
        }
        public void Configuration(IAppBuilder app)
        {
            // Loads the config from our App.config
            XmlConfigurator.Configure();

            // MassTransit to use Log4Net
            Log4NetLogger.Use();

            var container = IocConfig.RegisterDependencies();

            // Sets the Mvc resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // Sets Mvc Owin resolver as well
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            // Starts Mass Transit Service bus, and registers stopping of bus on app dispose
            var bus = container.Resolve<IBusControl>();
            var busHandle = bus.StartAsync().Result;

            if (app.Properties.ContainsKey("host.OnAppDisposing"))
            {
                var context = new OwinContext(app.Properties);
                var token = context.Get<CancellationToken>("host.OnAppDisposing");
                if (token != CancellationToken.None)
                {
                    token.Register(() => busHandle.Stop(TimeSpan.FromSeconds(30)));
                }
            }
        }
        /// <summary>
        ///     Limits the bandwith used by the subsequent stages in the owin pipeline.
        /// </summary>
        /// <param name="getMaxBytesPerSecond">
        ///     A delegate to retrieve the maximum number of bytes per second to be transferred.
        ///     Allows you to supply different values at runtime. Use 0 or a negative number to specify infinite bandwidth.
        /// </param>
        /// <returns>An OWIN middleware delegate.</returns>
        /// <exception cref="System.ArgumentNullException">getMaxBytesPerSecond</exception>
        public static MidFunc MaxBandwidthPerRequest(Func<RequestContext, int> getMaxBytesPerSecond)
        {
            getMaxBytesPerSecond.MustNotNull("getMaxBytesPerSecond");

            return
                next =>
                async env =>
                {
                    var context = new OwinContext(env);
                    Stream requestBodyStream = context.Request.Body ?? Stream.Null;
                    Stream responseBodyStream = context.Response.Body;

                    var limitsRequestContext = new RequestContext(context.Request);

                    var requestTokenBucket = new FixedTokenBucket(
                        () => getMaxBytesPerSecond(limitsRequestContext));
                    var responseTokenBucket = new FixedTokenBucket(
                        () => getMaxBytesPerSecond(limitsRequestContext));

                    using (requestTokenBucket.RegisterRequest())
                    using (responseTokenBucket.RegisterRequest())
                    {

                        context.Request.Body = new ThrottledStream(requestBodyStream, requestTokenBucket);
                        context.Response.Body = new ThrottledStream(responseBodyStream, responseTokenBucket);

                        //TODO consider SendFile interception
                        await next(env).ConfigureAwait(false);
                    }
                };
        }
예제 #15
0
        public async Task Invoke(IDictionary<string, object> env)
        {
            var context = new OwinContext(env);

            var claimsPrincipal = context.Request.User as ClaimsPrincipal;

            if (claimsPrincipal != null &&
                !(claimsPrincipal is WindowsPrincipal) &&
                claimsPrincipal.Identity.IsAuthenticated &&
                !claimsPrincipal.IsAuthenticated() &&
                claimsPrincipal.HasClaim(ClaimTypes.NameIdentifier))
            {
                var identity = new ClaimsIdentity(claimsPrincipal.Claims, Constants.JabbRAuthType);

                var providerName = claimsPrincipal.GetIdentityProvider();

                if (String.IsNullOrEmpty(providerName))
                {
                    // If there's no provider name just add custom as the name
                    identity.AddClaim(new Claim(ClaimTypes.AuthenticationMethod, "Custom"));
                }

                context.Authentication.SignIn(identity);
            }

            await _next(env);
        }
예제 #16
0
 public Task Invoke(EnvDict env)
 {
     var ctx = new OwinContext(env);
     var v = ctx.Request.Headers.Get(this.header);
     RouteParams.Set(env, this.paramKey, v);
     return next.Invoke(env);
 }
예제 #17
0
        public async Task Dispatch(RequestDispatcherContext context)
        {
            var owinContext = new OwinContext(context.OwinEnvironment);
            var form = await owinContext.Request.ReadFormAsync();
            var requestedMetrics = new HashSet<string>(form.GetValues("metrics[]") ?? new string[0]);

            var page = new StubPage();
            page.Assign(context);

            var metrics = DashboardMetrics.GetMetrics().Where(x => requestedMetrics.Contains(x.Name));
            var result = new Dictionary<string, Metric>();

            foreach (var metric in metrics)
            {
                var value = metric.Func(page);
                result.Add(metric.Name, value);
            }

            var settings = new JsonSerializerSettings
            {
                ContractResolver = new CamelCasePropertyNamesContractResolver(),
                Converters = new JsonConverter[]{ new StringEnumConverter { CamelCaseText = true } }
            };
            var serialized = JsonConvert.SerializeObject(result, settings);

            owinContext.Response.ContentType = "application/json";
            await owinContext.Response.WriteAsync(serialized);
        }
예제 #18
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 == "kevin";
            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);
            }
        }
        public async Task Invoke(IDictionary<string, object> environment)
        {
            var context = new OwinContext(environment);

            Exception exception = null;
            ITransform transformer = null;

            try
            {
                await _next.Invoke(environment);
                exception = GetSwallowedException(context);

                if (exception != null)
                {
                    transformer = _transformsCollection.FindTransform(exception);
                }
            }
            catch (Exception catchedException)
            {
                exception = catchedException;

                // check if we can transform it, otherwise we should throw it
                transformer = _transformsCollection.FindTransform(exception);
                if (transformer == null)
                {
                    throw;
                }
            }

            if (transformer != null)
            {
                await TransformException(context, transformer, exception);
            }
        }
        public static MidFunc HandleCommands(HandlerSettings options, string commandPath = "/commands")
        {
            Guard.EnsureNotNull(options, "options");

            return next => env =>
            {
                // PUT "/{guid}" with a Json body.
                var context = new OwinContext(env);
                if (!context.Request.Method.Equals("PUT", StringComparison.OrdinalIgnoreCase))
                {
                    // Not a PUT, pass through.
                    return next(env);
                }

                var path = context.Request.Path;
                if (!path.StartsWithSegments(new PathString(commandPath), out path))
                {
                    // not routed to us
                    return next(env);
                }

                var commandIdString = path.Value.Substring(1);
                Guid commandId;
                if (!Guid.TryParse(commandIdString, out commandId))
                {
                    // Resource is not a GUID, pass through
                    return next(env);
                }

                return BuildHandlerCall(commandId).ExecuteWithExceptionHandling(context, options);
            };
        }
        /// <summary>
        /// Called when it's invoked
        /// </summary>
        /// <param name="env">Environment variables</param>
        /// <returns>The task object</returns>
        public async Task Invoke(IDictionary<string, object> env)
        {
            Contract.Requires<ArgumentNullException>(env != null, "env");
            OwinContext Context = new OwinContext(env);
            if (Context.Request.User == null && Context.Request.Path != new PathString("/Account/Login"))
            {
                Context.Response.Redirect((Context.Request.PathBase + new PathString("/Account/Login")).Value);
            }
            WindowsPrincipal Principal = Context.Request.User as WindowsPrincipal;
            if (Principal == null || !Principal.Identity.IsAuthenticated)
            {
                await Next(env);
                return;
            }
            User CurrentUser = User.LoadCurrentUser();
            if (CurrentUser == null)
            {
                User TempUser = GetUser(Principal);
                SetupDefaultClaims(Principal, TempUser);
                TempUser.Save();
                ClaimsIdentity Identity = new ClaimsIdentity(TempUser.Claims.Select(x => new Claim(x.Type, x.Value)), "WindowsAuthType");
                Context.Authentication.SignIn(Identity);
                Context.Response.Redirect((Context.Request.PathBase + Context.Request.Path).Value);
            }

            await Next(env);

            if (Context.Response.StatusCode == 401)
            {
                User TempUser = GetUser(Principal);
                ClaimsIdentity Identity = new ClaimsIdentity(TempUser.Claims.Select(x => new Claim(x.Type, x.Value)), "WindowsAuthType");
                Context.Authentication.SignIn(Identity);
                Context.Response.Redirect((Context.Request.PathBase + Context.Request.Path).Value);
            }
        }
예제 #22
0
        public HomeModule()
        {
            Get["/"] = x =>
            {
                var owinContext = new OwinContext(Context.GetOwinEnvironment());

                var inputModel = this.Bind<HomeBindingModel>();

                var model = new HomeViewModel
                {
                    Text = string.Format("Input from Query String: {0} - {1}", inputModel.Input1, inputModel.Input2),
                    Method = owinContext.Request.Method
                };
                return View["home", model];
            };

            Post["/"] = x =>
            {
                var owinContext = new OwinContext(Context.GetOwinEnvironment());

                var inputModel = this.Bind<HomeBindingModel>();

                var model = new HomeViewModel
                {
                    Text = string.Format("Input from Form Post: {0} - {1}", inputModel.Input1, inputModel.Input2),
                    Method = owinContext.Request.Method
                };
                return View["home", model];
            };
        }
        public void ShouldFailOnMissingAuthAttribute()
        {
            var logger = new Logger();
            var builder = new AppBuilderFactory().Create();
            builder.SetLoggerFactory(new LoggerFactory(logger));
            var context = new OwinContext();
            var request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " + 
                "ts = \"1353788437\", mac = \"/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=\", ext = \"hello\""});

            var response = (OwinResponse)context.Response;
            response.StatusCode = 401;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) => 
                    {
                        response.StatusCode = 401;
                        return Task.FromResult<object>(null);
                    }),
                builder,
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Missing attributes", logger.Messages[0]);
        }
예제 #24
0
 public static void SignOut(this NancyModule module)
 {
     var env = module.Context.GetOwinEnvironment();
     var owinContext = new OwinContext(env);
     
     owinContext.Authentication.SignOut(TheBenchConstants.TheBenchAuthType);
 }
        public void ShouldSkipAuthOnWrongAuthScheme()
        {
            var builder = new AppBuilderFactory().Create();

            var context = new OwinContext();
            OwinRequest request = (OwinRequest)context.Request;
            request.Set<Action<Action<object>, object>>("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Basic " });

            var response = context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) => 
                    {
                        response.StatusCode = 200;
                        return Task.FromResult<object>(null);
                    }), 
                builder, 
                new HawkAuthenticationOptions
                {
                    Credentials = GetCredential
                }
            );

            middleware.Invoke(context);

            Assert.IsNotNull(response);
            Assert.AreEqual(200, response.StatusCode);
        }
        public async Task Invoke(IDictionary<string, object> env)
        {
            var context = new OwinContext(env);
            context.Authentication.User = this.CreateUser();

            await this._next(env);
        }
예제 #27
0
        /// <summary>
        /// Executes the given operation on a different thread, and waits for the result.
        /// </summary>
        /// <param name="env">The environment.</param>
        /// <returns>
        /// A Task.
        /// </returns>
        public async Task Invoke(IDictionary<string, object> env)
        {
            var context = new OwinContext(env);

            if (context.Request.Uri.LocalPath.ToLower().StartsWith("/post"))
            {
                var content = Uri.UnescapeDataString(context.Request.Uri.Query.Substring(1));
                var msg = (IMessage)await this.serializationService.JsonDeserializeAsync<PostMessage>(content).PreserveThreadContext();

                var msgResponse = await this.messageProcessor.ProcessAsync(msg).PreserveThreadContext();
                var msgJson = await this.serializationService.JsonSerializeAsync(msgResponse).PreserveThreadContext();

                context.Response.StatusCode = (int)HttpStatusCode.OK;
                context.Response.ContentType = "application/json";
                await context.Response.WriteAsync(msgJson);

                return;
            }

            try
            {
                await this.next(env);
            }
            catch (OperationCanceledException)
            {
                // be silent on cancelled.
            }
        }
 private static string BuildHtmlTable(OwinContext context) {
     var builder = new StringBuilder();
     builder.Append("<table border='1'><tr><th>Key</th><th>Value</th></tr>");
     List<string> keys = context.Environment.Keys.OrderBy(key => key)
                                .ToList();
     foreach (var key in keys) {
         var value = context.Environment[key];
         var valueDictionary = value as IDictionary<string, string[]>;
         if (valueDictionary == null) {
             builder.AppendFormat("<tr><td>{0}</td><td>{1}</td></tr>", key, value);
         }
         else {
             builder.AppendFormat("<tr><td>{0}</td><td>count ={1}</td></tr>", key, valueDictionary.Count);
             if (valueDictionary.Count == 0) {
                 continue;
             }
             builder.Append("<tr><td>&nbsp;</td><td><table border='1'><tr><th>Key</th><th>Value</th></tr>");
             List<string> valueKeys = valueDictionary.Keys.OrderBy(key2 => key2)
                                                     .ToList();
             foreach (var valueKey in valueKeys) {
                 builder.AppendFormat("<tr><td>{0}</td><td>{1}</td><tr>", valueKey, string.Join("<br />", valueDictionary[valueKey]));
             }
             builder.Append("</table></td></tr>");
         }
     }
     builder.Append("</table>");
     return builder.ToString();
 }
        /// <summary>
        /// Limits the length of the URL.
        /// </summary>
        /// <param name="getMaxUrlLength">A delegate to get the maximum URL length.</param>
        /// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
        /// <returns>An OWIN middleware delegate.</returns>
        /// <exception cref="System.ArgumentNullException">getMaxUrlLength</exception>
        public static MidFunc MaxUrlLength(Func<RequestContext, int> getMaxUrlLength, string loggerName = null)
        {
            getMaxUrlLength.MustNotNull("getMaxUrlLength");

            loggerName = string.IsNullOrWhiteSpace(loggerName)
                ? "LimitsMiddleware.MaxUrlLength"
                : loggerName;
            var logger = LogProvider.GetLogger(loggerName);

            return
                next =>
                env =>
                {
                    var context = new OwinContext(env);
                    int maxUrlLength = getMaxUrlLength(new RequestContext(context.Request));
                    string unescapedUri = Uri.UnescapeDataString(context.Request.Uri.AbsoluteUri);

                    logger.Debug("Checking request url length.");
                    if (unescapedUri.Length > maxUrlLength)
                    {
                        logger.Info(
                            "Url \"{0}\"(Length: {2}) exceeds allowed length of {1}. Request rejected.".FormatWith(
                            unescapedUri,
                            maxUrlLength,
                            unescapedUri.Length));
                        context.Response.StatusCode = 414;
                        context.Response.ReasonPhrase = "Request-URI Too Large";
                        context.Response.Write(context.Response.ReasonPhrase);
                        return Task.FromResult(0);
                    }
                    logger.Debug("Check passed. Request forwarded.");
                    return next(env);
                };
        }
예제 #30
0
		public async Task Invoke(IDictionary<string, object> env)
		{
			var context = new OwinContext(env);
			context.Response.ContentType = "text/html";
			await context.Response.WriteAsync(this.options.Greeting);
			await this.next(env);
		}
예제 #31
0
        /// <summary>
        /// Starts a new instance of the <see cref="BackgroundJobServer"/> class with
        /// the given arguments, and registers its disposal on application shutdown.
        /// </summary>
        ///
        /// <param name="builder">OWIN application builder.</param>
        /// <param name="storage">Storage to use by background job server.</param>
        /// <param name="options">Options for background job server.</param>
        /// <param name="additionalProcesses">Collection of additional background processes.</param>
        ///
        /// <exception cref="ArgumentNullException"><paramref name="builder"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="storage"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="options"/> is null.</exception>
        /// <exception cref="ArgumentNullException"><paramref name="additionalProcesses"/> is null.</exception>
        /// <exception cref="InvalidOperationException">
        /// OWIN environment does not contain the application shutdown cancellation token.
        /// </exception>
        ///
        /// <remarks>
        /// Please see <see cref="AppBuilderExtensions"/> for details and examples.
        /// </remarks>
        public static IAppBuilder UseHangfireServer(
            [NotNull] this IAppBuilder builder,
            [NotNull] JobStorage storage,
            [NotNull] BackgroundJobServerOptions options,
            [NotNull] params IBackgroundProcess[] additionalProcesses)
        {
            if (builder == null)
            {
                throw new ArgumentNullException(nameof(builder));
            }
            if (storage == null)
            {
                throw new ArgumentNullException(nameof(storage));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (additionalProcesses == null)
            {
                throw new ArgumentNullException(nameof(additionalProcesses));
            }

            var server = new BackgroundJobServer(options, storage, additionalProcesses);

            Servers.Add(server);

            var context = new OwinContext(builder.Properties);
            var token   = context.Get <CancellationToken>("host.OnAppDisposing");

            if (token == default(CancellationToken))
            {
                // https://github.com/owin/owin/issues/27
                token = context.Get <CancellationToken>("server.OnDispose");
            }

            if (token == default(CancellationToken))
            {
                throw new InvalidOperationException(
                          "Current OWIN environment does not contain an instance of the `CancellationToken` class neither under `host.OnAppDisposing`, nor `server.OnDispose` key.\r\n"
                          + "Please use another OWIN host or create an instance of the `BackgroundJobServer` class manually.");
            }

            token.Register(OnAppDisposing, server);
            return(builder);
        }
예제 #32
0
        public void UseHandlerWithIOwinContext()
        {
            var builder = new AppBuilder();

            builder.Use((context, next) =>
            {
                context.Response.ReasonPhrase = "Set In Middleware";
                return(next());
            });

            AppFunc      theApp      = builder.Build();
            IOwinContext baseContext = new OwinContext();

            theApp(baseContext.Environment).Wait();
            Assert.Equal(404, baseContext.Response.StatusCode);
            Assert.Equal("Set In Middleware", baseContext.Response.ReasonPhrase);
        }
예제 #33
0
 public static AppFunc Inject(AppFunc next)
 {
     return(async env =>
     {
         var owinContext = new OwinContext(env);
         var existingCorrelationToken = owinContext.Request.Headers[Constants.FabricHeaders.CorrelationTokenHeaderName];
         if (!Guid.TryParse(existingCorrelationToken, out Guid correlationToken))
         {
             correlationToken = Guid.NewGuid();
         }
         owinContext.Set(Constants.FabricLogContextProperties.CorrelationTokenContextName, correlationToken.ToString());
         using (LogContext.PushProperty(Constants.FabricLogContextProperties.CorrelationTokenContextName, correlationToken))
         {
             await next(env);
         }
     });
 }
예제 #34
0
        /// <summary>
        /// Gets the sign in message.
        /// </summary>
        /// <param name="env">The OWIN environment.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentNullException">
        /// env
        /// or
        /// id
        /// </exception>
        public static SignInMessage GetSignInMessage(this IDictionary <string, object> env)
        {
            if (env == null)
            {
                throw new ArgumentNullException("env");
            }

            var ctx = new OwinContext(env);
            var id  = ctx.Request.Query.Get(Constants.Authentication.SigninId);

            if (String.IsNullOrWhiteSpace(id))
            {
                return(null);
            }

            return(env.GetSignInMessage(id));
        }
        public async Task Valid_Body_Post()
        {
            var ctx = new OwinContext();

            ctx.Request.Method      = "POST";
            ctx.Request.ContentType = "application/x-www-form-urlencoded";
            var body = "access_token=token";

            ctx.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(body));

            var validator = new BearerTokenUsageValidator();
            var result    = await validator.ValidateAsync(ctx);

            result.TokenFound.Should().BeTrue();
            result.Token.Should().Be("token");
            result.UsageType.Should().Be(BearerTokenUsageType.PostBody);
        }
        public async Task Invoke(IDictionary <string, object> env)
        {
            IOwinContext context = new OwinContext(env);

            context.Response.OnSendingHeaders(state =>
            {
                var response = (OwinResponse)state;

                if (response.StatusCode >= 400)
                {
                    response.Headers.Add("X-Box", new[] { Environment.MachineName });
                }
            },
                                              context.Response);

            await this.next(env);
        }
        private static async Task ValidateTokens(HttpActionContext actionContext)
        {
            var env = actionContext.Request.GetOwinEnvironment();

            var success = actionContext.Request.Method == HttpMethod.Post &&
                          actionContext.Request.Content.IsFormData();

            if (success)
            {
                // ReadAsByteArrayAsync buffers the request body stream
                // we then put the buffered copy into the owin context
                // so we can read it in the IsTokenValid API without
                // disturbing the actual stream in the HttpRequestMessage
                // that WebAPI uses it later for model binding. #lame
                var bytes = await actionContext.Request.Content.ReadAsByteArrayAsync();

                var ms = new MemoryStream(bytes);
                ms.Seek(0, SeekOrigin.Begin);
                var ctx = new OwinContext(env);
                ctx.Request.Body = ms;

                var antiForgeryToken = env.ResolveDependency <AntiForgeryToken>();
                success = await antiForgeryToken.IsTokenValid();
            }

            if (!success)
            {
                Logger.ErrorFormat("AntiForgery validation failed -- returning error page");

                var options      = env.ResolveDependency <IdentityServerOptions>();
                var viewSvc      = env.ResolveDependency <IViewService>();
                var localization = env.ResolveDependency <ILocalizationService>();

                var errorModel = new ErrorViewModel
                {
                    RequestId    = env.GetRequestId(),
                    SiteName     = options.SiteName,
                    SiteUrl      = env.GetIdentityServerBaseUrl(),
                    ErrorMessage = localization.GetMessage(Resources.MessageIds.UnexpectedError),
                    CurrentUser  = env.GetCurrentUserDisplayName(),
                    LogoutUrl    = env.GetIdentityServerLogoutUrl(),
                };
                var errorResult = new ErrorActionResult(viewSvc, errorModel);
                actionContext.Response = await errorResult.GetResponseMessage();
            }
        }
예제 #38
0
        public void Configuration(IAppBuilder app)
        {
            RunStartup(app);

            // Register shutdown action
            var context = new OwinContext(app.Properties);
            var token   = context.Get <CancellationToken>("host.OnAppDisposing");

            if (token != CancellationToken.None)
            {
                token.Register(RunShutdown);
            }
            else
            {
                Log.Warn("Failed to register shutdown action.");
            }
        }
예제 #39
0
파일: ImageServer.cs 프로젝트: J0hnLiu/vrs
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc AppFuncBuilder(AppFunc next)
        {
            return(async(IDictionary <string, object> environment) => {
                var handled = false;
                var context = OwinContext.Create(environment);

                if (context.RequestPathNormalised.StartsWith("/images/", StringComparison.OrdinalIgnoreCase))
                {
                    handled = ServeImage(context);
                }

                if (!handled)
                {
                    await next(environment);
                }
            });
        }
예제 #40
0
        private async Task ParseKerberosHeader(OwinContext context)
        {
            string[] authzHeader = null;

            if (!context.Request.Headers.TryGetValue("Authorization", out authzHeader) || authzHeader.Length != 1)
            {
                return;
            }

            var header = authzHeader.First();

            var authenticator = new KerberosAuthenticator(validator);

            var identity = await authenticator.Authenticate(header);

            context.Request.User = new ClaimsPrincipal(identity);
        }
        public static AppFunc Middleware(AppFunc next)
        {
            return(async env =>
            {
                Guid correlationToken;
                var owinContext = new OwinContext(env);
                if (!(owinContext.Request.Headers["Correlation-Token"] != null && Guid.TryParse(owinContext.Request.Headers["Correlation-Token"], out correlationToken)))
                {
                    correlationToken = Guid.NewGuid();
                }

                owinContext.Set("correlationToken", correlationToken.ToString());

                using (LogContext.PushProperty("CorrelationToken", correlationToken))
                    await next(env).ConfigureAwait(false);
            });
        }
 public static AppFunc Middleware(AppFunc next)
 {
     return(env =>
     {
         var ctx = new OwinContext(env);
         if (ctx.Request.Headers.ContainsKey("microservice.NET-end-user"))
         {
             var tokenHandler = new JwtSecurityTokenHandler();
             SecurityToken token;
             var userPrincipal =
                 tokenHandler.ValidateToken(ctx.Request.Headers["microservice.NET-end-user"],
                                            new TokenValidationParameters(), out token);
             ctx.Set("pos-end-user", userPrincipal);
         }
         return next(env);
     });
 }
        public async Task Invoke(IDictionary <string, object> env)
        {
            var context = new OwinContext(env);

            // this creates a per-request, disposable scope
            using (var scope = _container.BeginLifetimeScope(b =>
            {
                // this makes owin context resolvable in the scope
                b.RegisterInstance(context).As <IOwinContext>();
            }))
            {
                // this makes scope available for downstream frameworks
                env.SetLifetimeScope(scope);

                await _next(env);
            }
        }
예제 #44
0
        public void ChainedPredicatesAsync_Success()
        {
            IAppBuilder builder = new AppBuilder();

            builder.MapWhenAsync(TruePredicateAsync, map1 =>
            {
                map1.MapWhenAsync((PredicateAsync)FalsePredicateAsync, UseNotImplemented);
                map1.MapWhenAsync((PredicateAsync)TruePredicateAsync, map2 => map2.MapWhenAsync((PredicateAsync)TruePredicateAsync, UseSuccess));
                map1.Run(NotImplemented);
            });
            var app = builder.Build <OwinMiddleware>();

            IOwinContext context = new OwinContext();

            app.Invoke(context).Wait();
            Assert.Equal(200, context.Response.StatusCode);
        }
예제 #45
0
        public async Task Environment_should_contain_content_length_header()
        {
            OwinContext owinContext = null;
            var         handler     = new OwinHttpMessageHandler(env =>
            {
                owinContext = new OwinContext(env);
                return(Task.FromResult(0));
            });

            using (var client = new HttpClient(handler))
            {
                var stringContent = new StringContent("hello");
                await client.PostAsync("http://localhost/", stringContent);
            }

            owinContext.Request.Headers.ContainsKey("Content-Length").ShouldBeTrue();
        }
예제 #46
0
        public async void Valid_BasicAuthentication_Request()
        {
            var parser  = new BasicAuthenticationSecretParser();
            var context = new OwinContext();

            var headerValue = string.Format("Basic {0}",
                                            Convert.ToBase64String(Encoding.UTF8.GetBytes("client:secret")));

            context.Request.Headers.Add(
                new KeyValuePair <string, string[]>("Authorization", new[] { headerValue }));

            var secret = await parser.ParseAsync(context.Environment);

            secret.Type.Should().Be(Constants.ParsedSecretTypes.SharedSecret);
            secret.Id.Should().Be("client");
            secret.Credential.Should().Be("secret");
        }
예제 #47
0
        public async Task Run(IDictionary <string, object> environment)
        {
            var context = new OwinContext(environment);

            if (context.Request.Path.Equals(_shallowSegment, StringComparison.OrdinalIgnoreCase))
            {
                await ShallowCheck(context);
            }
            else if (context.Request.Path.Equals(_deepSegment, StringComparison.OrdinalIgnoreCase))
            {
                await DeepCheck(context);
            }
            else
            {
                await _next(environment);
            }
        }
예제 #48
0
        public async Task Invoke(IDictionary <string, object> environment)
        {
            Guid correlationToken;

            var owinContext = new OwinContext(environment);

            if (!(owinContext.Request.Headers["Correlation-Token"] != null && Guid.TryParse(owinContext.Request.Headers["Correlation-Token"],
                                                                                            out correlationToken)))
            {
                correlationToken = Guid.NewGuid();
            }

            owinContext.Set("correlationToken", correlationToken.ToString());

            using (Logger.PushProperty("CorrelationToken", correlationToken))
                await _next.Invoke(environment);
        }
예제 #49
0
        public async Task Invoke(IDictionary <string, object> env)
        {
            IOwinContext context = new OwinContext(env);

            string message = this.options.Message;

            if (this.options.IsHtml)
            {
                message = String.Format("<h1>{0}</h1>", message);
            }

            byte[] bytes = Encoding.UTF8.GetBytes(message);

            await context.Response.WriteAsync(bytes);

            await this.next(env);
        }
예제 #50
0
        public void Inject_ReturnsNoContentStatus(string path, int statusCode, Func <Task <bool> > healthCheck)
        {
            var ctx = new OwinContext
            {
                Request =
                {
                    Scheme = LibOwin.Infrastructure.Constants.Https,
                    Path   = new PathString(path),
                    Method = "GET"
                }
            };

            var pipeline = new MonitoringMiddleware(_noOp, healthCheck);

            pipeline.Inject(ctx.Environment);
            Assert.Equal(statusCode, ctx.Response.StatusCode);
        }
예제 #51
0
        public void ShouldReturnChallengeOnEmptyAuthHeaderWithStatusUnauthorized()
        {
            var logger  = new Logger();
            var builder = new AppBuilderFactory().Create();

            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var context = new OwinContext();
            var request = (OwinRequest)context.Request;

            request.Set <Action <Action <object>, object> >("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));

            var response = (OwinResponse)context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
            {
                response.StatusCode = 401;
                return(Task.FromResult <object>(null));
            }),
                builder,
                new HawkAuthenticationOptions
            {
                Credentials = (id) =>
                {
                    return(Task.FromResult(new HawkCredential
                    {
                        Id = "123",
                        Algorithm = "hmac-sha-0",
                        Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                        User = "******"
                    }));
                }
            }
                );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.IsNotNull(((IDictionary <string, string[]>)response.Environment["owin.ResponseHeaders"])["WWW-Authenticate"]);
        }
예제 #52
0
        public void ShouldExecuteControllerAndHaveLoggingForExceptions()
        {
            this.applicationMode = ApplicationMode.Dev;
            OwinContext context        = OwinExtender.CreateRequestForPath("/exception");
            var         inMemoryLogger = new InMemoryLogger(LogLevels.Always);
            var         rezult         = context.ProcessRequest(this.Manager, null, this.CommonSalt, inMemoryLogger);

            inMemoryLogger.Messages.Length.Should().BeGreaterOrEqualTo(2);
            var message = inMemoryLogger.Messages.FirstOrDefault(x => x.Message.Contains("Oh Boy!"));

            message.Should().NotBeNull();
            message.ToString().Should().Contain("[ApplicationError]");
            message.ToString().Should().Contain("Op Ex");
//            rezult.Content.Body.Should().Contain("[ApplicationError]");
            rezult.Content.BodyAsString.Should().Contain("Op Ex");
            rezult.Content.BodyAsString.Should().Contain("Oh Boy!");
        }
예제 #53
0
        /// <summary>
        /// Invokes the middleware.
        /// </summary>
        /// <param name="environment">The environment.</param>
        /// <returns></returns>
        public async Task Invoke(IDictionary <string, object> environment)
        {
            var context = new OwinContext(environment);

            var token = await GetTokenAsync(context);

            if (token == null)
            {
                await _next(environment);

                return;
            }

            context.Set("idsrv:tokenvalidation:token", token);

            // seems to be a JWT
            if (token.Contains('.'))
            {
                // see if local validation is setup
                if (_localValidationFunc != null)
                {
                    await _localValidationFunc(environment);

                    return;
                }
                // otherwise use validation endpoint
                if (_endpointValidationFunc != null)
                {
                    await _endpointValidationFunc(environment);

                    return;
                }
            }
            else
            {
                // use validation endpoint
                if (_endpointValidationFunc != null)
                {
                    await _endpointValidationFunc(environment);

                    return;
                }
            }

            await _next(environment);
        }
예제 #54
0
        public void Configuration(IAppBuilder app)
        {
            IUrlShortnerService service = new UrlShortnerService(AppSettingsReader.StorageAccountName, AppSettingsReader.StorageAccountSecret, AppSettingsReader.Baseurl, AppSettingsReader.MasterToken, AppSettingsReader.UseCache);

            var token = new OwinContext(app.Properties).Get <CancellationToken>("host.OnAppDisposing");

            if (token != CancellationToken.None)
            {
                token.Register(service.Dispose);
            }


            app.UseCors(CorsOptions.AllowAll);


            var options = new FileServerOptions
            {
                EnableDirectoryBrowsing = true,
                EnableDefaultFiles      = true,
                DefaultFilesOptions     = { DefaultFileNames = { "index.html" } },
                FileSystem        = new PhysicalFileSystem(@"./html"),
                RequestPath       = new PathString("/html"),
                StaticFileOptions = { OnPrepareResponse = (ContextCallback) =>
                                      {
                                          ContextCallback.OwinContext.Response.Headers.Add("X-Frame-Options", new[] { "DENY" });
                                          ContextCallback.OwinContext.Response.Headers.Add("Content-Security-Policy", new string[]
                        {
                            "script-src 'self' https://ajax.googleapis.com https://code.jquery.com https://maxcdn.bootstrapcdn.com; style-src https://maxcdn.bootstrapcdn.com; img-src https://az280641.vo.msecnd.net; font-src https://maxcdn.bootstrapcdn.com;"
                        });

                                          if (!string.IsNullOrWhiteSpace(AppSettingsReader.PublicKeyPinning))
                                          {
                                              ContextCallback.OwinContext.Response.Headers.Add("Public-Key-Pins", new[] { AppSettingsReader.PublicKeyPinning });
                                          }

                                          if (!string.IsNullOrWhiteSpace(AppSettingsReader.HstsHeader))
                                          {
                                              ContextCallback.OwinContext.Response.Headers.Add("Strict-Transport-Security", new[] { AppSettingsReader.HstsHeader });
                                          }
                                      } }
            };

            app.UseFileServer(options);

            app.UseUrlShortner(service);
        }
예제 #55
0
        public async void Valid_BasicAuthentication_Request_ClientId_Too_Long()
        {
            var context = new OwinContext();

            var longClientId = "x".Repeat(_options.InputLengthRestrictions.ClientId + 1);
            var credential   = string.Format("{0}:secret", longClientId);

            var headerValue = string.Format("Basic {0}",
                                            Convert.ToBase64String(Encoding.UTF8.GetBytes(credential)));

            context.Request.Headers.Add(
                new KeyValuePair <string, string[]>("Authorization", new[] { headerValue }));

            var secret = await _parser.ParseAsync(context.Environment);

            secret.Should().BeNull();
        }
예제 #56
0
        /// <summary>
        ///     Limits the number of concurrent requests that can be handled used by the subsequent stages in the owin pipeline.
        /// </summary>
        /// <param name="getMaxConcurrentRequests">
        ///     A delegate to retrieve the maximum number of concurrent requests. Allows you
        ///     to supply different values at runtime. Use 0 or a negative number to specify unlimited number of concurrent
        ///     requests.
        /// </param>
        /// <param name="loggerName">(Optional) The name of the logger log messages are written to.</param>
        /// <returns>An OWIN middleware delegate.</returns>
        /// <exception cref="System.ArgumentNullException">getMaxConcurrentRequests</exception>
        public static MidFunc MaxConcurrentRequests(
            Func <RequestContext, int> getMaxConcurrentRequests,
            string loggerName = null)
        {
            getMaxConcurrentRequests.MustNotNull("getMaxConcurrentRequests");

            loggerName = string.IsNullOrWhiteSpace(loggerName)
                ? "LimitsMiddleware.MaxConcurrentRequests"
                : loggerName;
            var logger = LogProvider.GetLogger(loggerName);
            var concurrentRequestCounter = 0;

            return
                (next =>
                 async env =>
            {
                var owinRequest = new OwinRequest(env);
                var limitsRequestContext = new RequestContext(owinRequest);
                int maxConcurrentRequests = getMaxConcurrentRequests(limitsRequestContext);
                if (maxConcurrentRequests <= 0)
                {
                    maxConcurrentRequests = int.MaxValue;
                }
                try
                {
                    int concurrentRequests = Interlocked.Increment(ref concurrentRequestCounter);
                    logger.Debug("Concurrent request {0}/{1}.".FormatWith(concurrentRequests, maxConcurrentRequests));
                    if (concurrentRequests > maxConcurrentRequests)
                    {
                        logger.Info("Limit ({0}). Request rejected."
                                    .FormatWith(maxConcurrentRequests, concurrentRequests));
                        var response = new OwinContext(env).Response;
                        response.StatusCode = 503;
                        response.ReasonPhrase = "Service Unavailable";
                        response.Write(response.ReasonPhrase);
                        return;
                    }
                    await next(env);
                }
                finally
                {
                    int concurrentRequests = Interlocked.Decrement(ref concurrentRequestCounter);
                    logger.Debug("Concurrent request {0}/{1}.".FormatWith(concurrentRequests, maxConcurrentRequests));
                }
            });
        }
예제 #57
0
        public void ShouldFailOnInvalidCredentials()
        {
            var logger  = new Logger();
            var builder = new AppBuilderFactory().Create();

            builder.SetLoggerFactory(new LoggerFactory(logger));

            var ts = Hawk.ConvertToUnixTimestamp(DateTime.Now).ToString();

            var context = new OwinContext();
            var request = (OwinRequest)context.Request;

            request.Set <Action <Action <object>, object> >("server.OnSendingHeaders", RegisterForOnSendingHeaders);
            request.Method = "get";
            request.SetHeader("Host", new string[] { "localhost" });
            request.SetUri(new Uri("http://example.com:8080/resource/4?filter=a"));
            request.SetHeader("Authorization", new string[] { "Hawk " +
                                                              "id = \"456\", ts = \"" + ts + "\", nonce=\"k3j4h2\", mac = \"qrP6b5tiS2CO330rpjUEym/USBM=\", ext = \"hello\"" });

            var response = (OwinResponse)context.Response;

            var middleware = new HawkAuthenticationMiddleware(
                new AppFuncTransition((env) =>
            {
                response.StatusCode = 401;
                return(Task.FromResult <object>(null));
            }),
                builder,
                new HawkAuthenticationOptions
            {
                Credentials = (id) =>
                {
                    return(Task.FromResult(new HawkCredential
                    {
                        Key = "werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn",
                        User = "******"
                    }));
                }
            }
                );

            middleware.Invoke(context);

            Assert.AreEqual(401, response.StatusCode);
            Assert.AreEqual("Invalid credentials", logger.Messages[0]);
        }
예제 #58
0
        public void Configuration(IAppBuilder app)
        {
            //ConfigureAuth(app);
            CouchbaseConfig.Initialize();

            var context = new OwinContext(app.Properties);
            var token   = context.Get <CancellationToken>("host.OnAppDisposing");

            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    // code to run on shutdown
                    CouchbaseConfig.Close();
                });
            }
        }
예제 #59
0
        public bool Authorize(DashboardContext context)
        {
            try
            {
                var owinContext = new OwinContext(context.GetOwinEnvironment());

                var user = owinContext.Authentication.User;

                return
                    (user.Identity.IsAuthenticated &&
                     ApplicationPermissionAuthorizeAttribute.HasPermission(user, BusinessLayer.Authorization.ApplicationPermissionNames.BackgroundJobDashboard));
            }
            catch (Exception)
            {
                return(false);
            }
        }
예제 #60
0
        protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string ipAddress = string.Empty;

            if (request.Properties.ContainsKey("MS_OwinContext"))
            {
                OwinContext owinContext = (OwinContext)request.Properties["MS_OwinContext"];
                ipAddress = owinContext.Request.RemoteIpAddress;
            }

            var corrId      = string.Format("{0}{1}", DateTime.Now.Ticks, Thread.CurrentThread.ManagedThreadId);
            var requestInfo = string.Format("{0} {1} {2}", request.Method, request.RequestUri, ipAddress);

            var requestMessage = await request.Content.ReadAsByteArrayAsync();

            await IncommingMessageAsync(corrId, requestInfo, requestMessage);

            var response = await base.SendAsync(request, cancellationToken);

            byte[] responseMessage;

            if (response.IsSuccessStatusCode)
            {
                responseMessage = Encoding.UTF8.GetBytes(response.StatusCode.ToString());
                if (response.Content != null)
                {
                    responseMessage = await response.Content.ReadAsByteArrayAsync();
                }
                await OutgoingMessageAsync(corrId, requestInfo, responseMessage);
            }
            else
            {
                string ex = response.Content.ReadAsStringAsync().Result;
                responseMessage = Encoding.UTF8.GetBytes(ex);
                await OutgoingMessageAsync(corrId, requestInfo, responseMessage);

                XmlSerializer   mySerializer   = new XmlSerializer(typeof(ResponseMessage));
                MemoryStream    myMemoryStream = new MemoryStream(responseMessage);
                ResponseMessage rm             = (ResponseMessage)mySerializer.Deserialize(myMemoryStream);
                rm.StackTrace    = rm.Message;
                response.Content = new ObjectContent <ResponseMessage>(rm, new IgnoreNamespacesXmlMediaTypeFormatter());
            }

            return(response);
        }