public void Configuration(Owin.IAppBuilder app) { app.UseErrorPage(); app.UseLightNode( new LightNodeOptions(AcceptVerbs.Get | AcceptVerbs.Post, new JavaScriptContentTypeFormatter())); }
public void Configuration(Owin.IAppBuilder app) { app.UseLightNode(new LightNodeOptions(AcceptVerbs.Get | AcceptVerbs.Post, new JilContentFormatter(), new GZipJilContentFormatter()) { StreamWriteOption = StreamWriteOption.BufferAndWrite }); }
public override void AttachToHttpApp(IRobot robo, Owin.IAppBuilder app) { app.Map("/system/version", subapp => subapp.UseGate((req, resp) => { resp.StatusCode = 200; resp.Write(Version.ToString()); })); app.Map("/system/parts", subapp => subapp.UseGate((req, resp) => { resp.StatusCode = 200; resp.Write(FormatParts(robo)); })); }
public void Configuration(Owin.IAppBuilder app) { app.Map("/api", builder => { builder.UseLightNode(new LightNodeOptions(AcceptVerbs.Get | AcceptVerbs.Post, new JsonNetContentFormatter()) { StreamWriteOption = StreamWriteOption.BufferAndWrite, ParameterEnumAllowsFieldNameParse = true, ErrorHandlingPolicy = ErrorHandlingPolicy.ReturnInternalServerErrorIncludeErrorDetails, OperationMissingHandlingPolicy = OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails, }); }); }
public void Configuration(Owin.IAppBuilder app) { // using Owin; you can use UseRequestScopeContext extension method. // enabled timing is according to Pipeline. // so I recommend enable as far in advance as possible. app.UseRequestScopeContext(); app.UseErrorPage(); app.Run(async _ => { // get global context like HttpContext.Current. var context = OwinRequestScopeContext.Current; // Environment is raw Owin Environment as IDictionary<string, object>. var __ = context.Environment; // optional:If you want to change Microsoft.Owin.OwinContext, you can wrap. new Microsoft.Owin.OwinContext(context.Environment); // Timestamp is request started(correctly called RequestScopeContextMiddleware timing). var ___ = context.Timestamp; // Items is IDictionary<string, object> like HttpContext#Items. // Items is threadsafe(as ConcurrentDictionary) by default. var ____ = context.Items; // DisposeOnPipelineCompleted can register dispose when request finished(correctly RequestScopeContextMiddleware underling Middlewares finished) // return value is cancelToken. If call token.Dispose() then canceled register. var cancelToken = context.DisposeOnPipelineCompleted(new TraceDisposable()); // OwinRequestScopeContext over async/await also ConfigureAwait(false) context.Items["test"] = "foo"; await Task.Delay(TimeSpan.FromSeconds(1)).ConfigureAwait(false); var _____ = OwinRequestScopeContext.Current.Items["test"]; // foo await Task.Run(() => { // OwinRequestScopeContext over new thread/threadpool. var ______ = OwinRequestScopeContext.Current.Items["test"]; // foo }); _.Response.ContentType = "text/plain"; await _.Response.WriteAsync("Hello OwinRequestScopeContext! => "); await _.Response.WriteAsync(OwinRequestScopeContext.Current.Items["test"] as string); // render foo }); }
public void Configuration(Owin.IAppBuilder app) { // enable RedisSession Middleware. // RedisSession app.UseRedisSession(new RedisSessionOptions(new RedisSettings("127.0.0.1"))); app.Run(async context => // request begin, Get all values from Redis server. { // take session from owin environment(IDictionary<string, object>) var session = context.Environment.AsRedisSession(); // TryGet(or Get) take from local storage. DateTime lastAccess; int accessCount = 1; if (session.TryGet<DateTime>("LastAccess", out lastAccess) && session.TryGet<int>("Counter", out accessCount)) { accessCount++; await context.Response.WriteAsync("AccessCount " + accessCount); await context.Response.WriteAsync(", LastAccess from RedisSession => " + lastAccess.ToString()); } else { await context.Response.WriteAsync("First Access"); } // Set(or Remove) set to local storage and enqueue operation. session.Set("Counter", accessCount); session.Set("LastAccess", DateTime.Now); context.Response.ContentType = "text/plain"; }); // request end, queued set(or delete) values to Redis server. // context save pattern, can take everywhere. //app.UseRequestScopeContext(); //app.UseRedisSession(new RedisSessionOptions(new RedisSettings("127.0.0.1"))); //app.Run(async context => //{ // Store(); // int v = -1; // context.Environment.AsRedisSession().TryGet<int>("test", out v); // context.Response.ContentType = "text/plain"; // await context.Response.WriteAsync(v.ToString()); //}); }
protected override void SetupThrottling(Owin.IAppBuilder app) { MemoryCacheRepository cache = new MemoryCacheRepository(); cache.Clear(); app.Use(typeof(CustomThrottlingMiddleware), new ThrottlePolicy(perHour: 600) { IpThrottling = false, ClientThrottling = true, ClientRules = new Dictionary<string, RateLimits> { { CustomThrottlingMiddleware.IS_AUTHENTICATE, new RateLimits {PerHour = 4000}} }, EndpointThrottling = true, EndpointRules = new Dictionary<string, RateLimits>() { { "api/ip", new RateLimits { PerMinute = 2 } } } }, new PolicyMemoryCacheRepository(), cache, new ThrottlingLogger()); }
public void ConfigureWebApi(Owin.IAppBuilder app) { var config = new System.Web.Http.HttpConfiguration(); // Web API configuration and services // Configure Web API to use only bearer token authentication. config.SuppressDefaultHostAuthentication(); config.Filters.Add(new System.Web.Http.HostAuthenticationFilter(Microsoft.Owin.Security.OAuth.OAuthDefaults.AuthenticationType)); // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); app.UseWebApi(config); }
public static void Configure(Owin.IAppBuilder app) { var config = new HttpConfiguration(); app.UseWebApi(config); app.UseCors(CorsOptions.AllowAll); config.EnableCors(new EnableCorsAttribute("*", "*", "*")); config.MapHttpAttributeRoutes(); var settings = config.Formatters.JsonFormatter.SerializerSettings; //Use camelCaseFormatting settings.ContractResolver = new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver(); //Ignore null values settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore; config.Formatters.XmlFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("xml", "text/xml")); config.Formatters.JsonFormatter.MediaTypeMappings.Add(new UriPathExtensionMapping("json", "application/json")); }
public void Configuration(Owin.IAppBuilder app) { app.EnableGlimpse(); app.Map("/api", builder => { builder.UseLightNode(new LightNodeOptions(AcceptVerbs.Get | AcceptVerbs.Post, new JilContentFormatter(), new GZipJilContentFormatter()) { OperationCoordinatorFactory = new GlimpseProfilingOperationCoordinatorFactory(), StreamWriteOption = StreamWriteOption.BufferAndWrite, ParameterEnumAllowsFieldNameParse = true, ErrorHandlingPolicy = ErrorHandlingPolicy.ReturnInternalServerErrorIncludeErrorDetails, OperationMissingHandlingPolicy = OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails, Logger = LightNode.Diagnostics.LightNodeEventSource.Log }); }); app.Map("/swagger", builder => { var xmlName = "LightNode.Sample.GlimpseUse.xml"; var xmlPath = HttpContext.Current.Server.MapPath("~/bin/" + xmlName); //var xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + xmlName; builder.UseLightNodeSwagger(new Swagger.SwaggerOptions("LightNodeSample", "/api") { XmlDocumentPath = xmlPath, IsEmitEnumAsString = true }); }); app.MapWhen(x => !x.Request.Path.Value.StartsWith("/Glimpse.axd", StringComparison.InvariantCultureIgnoreCase), builder => { builder.Run(ctx => { ctx.Response.StatusCode = 404; return Task.FromResult(0); }); }); }
public void Configuration(Owin.IAppBuilder app) { app.Map("/api", builder => { builder.UseLightNode(new LightNodeOptions(AcceptVerbs.Get | AcceptVerbs.Post, new JilContentFormatter(), new GZipJilContentFormatter()) { StreamWriteOption = StreamWriteOption.BufferAndWrite, ParameterEnumAllowsFieldNameParse = true, ErrorHandlingPolicy = ErrorHandlingPolicy.ReturnInternalServerErrorIncludeErrorDetails, OperationMissingHandlingPolicy = OperationMissingHandlingPolicy.ReturnErrorStatusCodeIncludeErrorDetails, }); }); app.Map("/swagger", builder => { var xmlName = "LightNode.Sample.Server.SelfHost.xml"; var xmlPath = System.AppDomain.CurrentDomain.BaseDirectory + "\\" + xmlName; builder.UseLightNodeSwagger(new Swagger.SwaggerOptions("LightNodeSample", "/api") { XmlDocumentPath = xmlPath, IsEmitEnumAsString = true }); }); }
// Defined in in Owin.dll. public void Configuration( Owin.IAppBuilder builder) { this.starter.ConfigureApplication(builder); logger.Info("####################### Configuration called"); }
public void Configuration(Owin.IAppBuilder app) { app.MapSignalR(); }
public void Configuration(Owin.IAppBuilder app) { //app.UseErrorPage(); app.UseOAuthAuthorizationServer(ServerOptions); app.UseOAuthBearerAuthentication(BearerOptions); // app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); app.UseWebApi(WebServer.Config); // app.SetDataProtectionProvider( TODO app.UseFileServer(new Microsoft.Owin.StaticFiles.FileServerOptions() { RequestPath = new Microsoft.Owin.PathString("/web"), FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(WebServer.StaticFileDirectory), EnableDirectoryBrowsing = false }); }
private static void Describe(IOwinResponse res, Owin.Security.AuthenticateResult result) { res.StatusCode = 200; res.ContentType = "text/xml"; var xml = new XElement("xml"); if (result != null && result.Identity != null) { xml.Add(result.Identity.Claims.Select(claim => new XElement("claim", new XAttribute("type", claim.Type), new XAttribute("value", claim.Value)))); } if (result != null && result.Properties != null) { xml.Add(result.Properties.Dictionary.Select(extra => new XElement("extra", new XAttribute("type", extra.Key), new XAttribute("value", extra.Value)))); } using (var memory = new MemoryStream()) { using (var writer = new XmlTextWriter(memory, Encoding.UTF8)) { xml.WriteTo(writer); } res.Body.Write(memory.ToArray(), 0, memory.ToArray().Length); } }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(Owin.IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); app.UseTwitterAuthentication(new TwitterAuthenticationOptions { ConsumerKey= "dQqy5fDOVtkj4q8gJHajWSNku", ConsumerSecret= "bPWadI7teNoQY466wsxzY5TkkffTzizo8Y59Zj5Rj0l9CVxRqk", BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server CA "B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High Assurance EV Root CA }) }); app.UseVkontakteAuthentication("5272668", "tky4WngIs9mei5sKD4js", "Email"); app.UseFacebookAuthentication( appId: "823839521057747", appSecret: "939fcfaf59c34bb8967553b0e8337ba9"); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
public void Configuration(Owin.IAppBuilder app) { app.MapSignalR();//new HubConfiguration() { EnableCrossDomain = true }); app.UseNancy(new NancyOptions() { Bootstrapper = new ApplicationBootstrapper() }); app.UseCors(CorsOptions.AllowAll); }
static void Startup(OwinMain.IAppBuilder app) { Console.WriteLine("Sample Middleware loaded..."); //app.Use(new SampleMiddleware(null)); }
static string ToText(Owin.BodyDelegate body, Encoding encoding) { var sb = new StringBuilder(); var wait = new ManualResetEvent(false); Exception exception = null; body.Invoke( (data, _) => { sb.Append(encoding.GetString(data.Array, data.Offset, data.Count)); return false; }, ex => { exception = ex; wait.Set(); }, CancellationToken.None); wait.WaitOne(); if (exception != null) throw new AggregateException(exception); return sb.ToString(); }
// This code configures Web API. The Startup class is specified as a type // parameter in the WebApp.Start method. public void Configuration(Owin.IAppBuilder appBuilder) { // Configure Web API for self-host. var config = new System.Web.Http.HttpConfiguration(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = System.Web.Http.RouteParameter.Optional } ); appBuilder.UseWebApi(config); }