public ForceSslWhenAuthenticatedMiddleware(OwinMiddleware next, IAppBuilder app, string cookieName, int sslPort)
     : base(next)
 {
     CookieName = cookieName;
     SslPort = sslPort;
     _logger = app.CreateLogger<ForceSslWhenAuthenticatedMiddleware>();
 }
Example #2
0
        public void Configuration(IAppBuilder app)
        {
            ILogger webApiLogger = app.CreateLogger("System.Web.Http");
            OwinWebApiTracer tracer = new OwinWebApiTracer(webApiLogger);
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute("DefaultHttpRoute", "api/{controller}");
            config.Services.Replace(typeof(ITraceWriter), tracer);

            app.Use<MyMiddleware>(app)
               .UseWebApi(config);
        }
        public void Configuration(IAppBuilder app)
        {
            //app.UseLog4Net();//from Web.config
            app.UseLog4Net("~/log4net.config");

            var logger = app.CreateLogger<Startup>();
            
            logger.WriteInformation("Application is started.");

            var config = new HttpConfiguration();
            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);            
        }
Example #4
0
File: Startup.cs Project: lx223/Q3
        public void Configuration(IAppBuilder app)
        {
            initLog();
            app.UseNLog();

            var manager = new QManager(new QEventsListener(GlobalHost.ConnectionManager));

            GlobalHost.DependencyResolver.Register(
                typeof(QHub),
                () => new QHub(
                    manager,
                    app.CreateLogger<QHub>()));

            app.Use<SimpleHeaderAuthenticator>();
            app.MapSignalR();

            var logger = LogManager.GetCurrentClassLogger();
            logger.Info("Application started");
        }
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder app)
        {
            this.logger = app.CreateLogger(this.GetType().Name);
            app.Run(async (context) => {
                logger.WriteInformation("Configuring...");

                var path = context.Request.Path;
                logger.WriteInformation("Has request for " + path + "!");
                if (!path.Value.Equals("/"))
                    return;
                logger.WriteInformation("Ok, processing request...");

                using (var client = new HttpClient())
                {
                    client.BaseAddress = new Uri("https://hacker-news.firebaseio.com");
                    client.DefaultRequestHeaders.Accept.Clear();
                    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    HttpResponseMessage response = await client.GetAsync("/v0/topstories.json?print=pretty");
                    logger.WriteInformation("Got first response.");
                    if (response.IsSuccessStatusCode)
                    {
                        var arr = await response.Content.ReadAsAsync<dynamic>();
                        var responseId = (String)arr[0];
                        var itemUrl = String.Format("/v0/item/{0}.json?print=pretty", responseId);
                        response = await client.GetAsync(itemUrl);
                        logger.WriteInformation("Got second response.");
                        if (response.IsSuccessStatusCode)
                        {
                            var dict = await response.Content.ReadAsAsync<dynamic>();
                            var title = (String)dict["title"];
                            logger.WriteInformation(title);
                            await context.Response.WriteAsync(title);
                            return;
                        }
                    }
                    logger.WriteInformation("Error:" + await response.Content.ReadAsStringAsync());
                    await context.Response.WriteAsync("Service is not available!");
                }
            });
        }
Example #6
0
        private void Log1(IAppBuilder app)
        {
            ILogger logger = app.CreateLogger<Startup>();
            logger.WriteError("App is starting up");
            logger.WriteCritical("App is starting up");
            logger.WriteWarning("App is starting up");
            logger.WriteVerbose("App is starting up");
            logger.WriteInformation("App is starting up");

            int foo = 1;
            int bar = 0;

            try
            {
                int fb = foo / bar;
            }
            catch (Exception ex)
            {
                logger.WriteError("Error on calculation", ex);
            }
        }
Example #7
0
        public AzureADAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, AzureADAuthenticationOptions options)
            : base(next, options)
        {
            if (String.IsNullOrWhiteSpace(Options.ClientId))
            {
                throw new ArgumentException("ClientId option must be provided.");
            }
            if (String.IsNullOrWhiteSpace(Options.ClientSecret))
            {
                throw new ArgumentException("ClientSecret option must be provided.");
            }
            _logger = app.CreateLogger <AzureADAuthenticationMiddleware>();

            if (Options.Provider == null)
            {
                Options.Provider = new AzureADAuthenticationProvider();
            }

            if (Options.StateDataFormat == null)
            {
                IDataProtector dataProtector = app.CreateDataProtector(
                    typeof(AzureADAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
            {
                Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            _httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
            {
                Timeout = Options.BackchannelTimeout,
                MaxResponseContentBufferSize = 1024 * 1024 * 10 // 10 MB
            };
        }
        public LinkedInAuthenticationMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            LinkedInAuthenticationOptions options)
            : base(next, options)
        {
            if (string.IsNullOrWhiteSpace(Options.AppId))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The '{0}' option must be provided.", "AppId"));
            }
            if (string.IsNullOrWhiteSpace(Options.AppSecret))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The '{0}' option must be provided.", "AppSecret"));
            }

            _logger = app.CreateLogger <LinkedInAuthenticationMiddleware>();

            if (Options.Provider == null)
            {
                Options.Provider = new LinkedInAuthenticationProvider();
            }
            if (Options.StateDataFormat == null)
            {
                IDataProtector dataProtector = app.CreateDataProtector(
                    typeof(LinkedInAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }
            if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
            {
                Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            _httpClient         = new HttpClient(ResolveHttpMessageHandler(Options));
            _httpClient.Timeout = Options.BackchannelTimeout;
            _httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
        }
        /// <summary>
        /// Initializes a <see cref="YandexAuthenticationMiddleware"/>
        /// </summary>
        /// <param name="next">The next middleware in the OWIN pipeline to invoke</param>
        /// <param name="app">The OWIN application</param>
        /// <param name="options">Configuration options for the middleware</param>
        public YandexAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, YandexAuthenticationOptions options)
            : base(next, options)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }

            if (options == null)
            {
                throw new ArgumentException("options can't be null or empty");
            }

            _logger = app.CreateLogger <YandexAuthenticationMiddleware>();

            _logger.WriteVerbose("App is starting up");

            if (Options.Provider == null)
            {
                Options.Provider = new YandexAuthenticationProvider();
            }
            if (Options.StateDataFormat == null)
            {
                IDataProtector dataProtector = app.CreateDataProtector(
                    typeof(YandexAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }
            if (String.IsNullOrEmpty(Options.SignInAsAuthenticationType))
            {
                Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            _httpClient         = new HttpClient(ResolveHttpMessageHandler(Options));
            _httpClient.Timeout = Options.BackchannelTimeout;
            _httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
        }
        public OAuthBearerAuthenticationMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            OAuthBearerAuthenticationOptions options) : base(next, options)
        {
            _logger = app.CreateLogger <OAuthBearerAuthenticationMiddleware>();

            if (string.IsNullOrWhiteSpace(options.Realm))
            {
                _challenge = "Bearer";
            }
            else
            {
                _challenge = "Bearer realm=\"" + options.Realm + "\"";
            }

            if (options.AccessTokenHandler == null)
            {
                var dataProtecter = app.CreateDataProtecter(
                    typeof(OAuthBearerAuthenticationMiddleware).Namespace,
                    "Access Token");
                options.AccessTokenHandler = new TicketDataHandler(dataProtecter);
            }
        }
Example #11
0
        public void Configuration(IAppBuilder app)
        {
            app.UseErrorPage();
            app.Use(AddEmployeeClaimBeforeAuthorizationCheck);

            var config = new HttpConfiguration();

            WebApiConfig.Register(config);

            app.UseAuthorization(options =>
            {
                options.AddPolicy(ExampleConstants.EmployeeNumber2Policy, policyBuilder =>
                {
                    policyBuilder.AddRequirements(new EmployeeNumber2Requirement());
                });

                var policyProvider           = new DefaultAuthorizationPolicyProvider(options);
                var handlers                 = new IAuthorizationHandler[] { new EmployeeNumber2Handler() };
                var logger                   = app.CreateLogger("my logger");
                options.Dependencies.Service = new DefaultAuthorizationService(policyProvider, handlers, logger);
            });

            app.UseWebApi(config);
        }
        /// <summary>
        /// Initializes a <see cref="OapCookieAuthenticationMiddleware"/>
        /// </summary>
        /// <param name="next">The next middleware in the OWIN pipeline to invoke</param>
        /// <param name="app">The OWIN application</param>
        /// <param name="options">Configuration options for the middleware</param>
        public OapCookieAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions options) : base(next, options)
        {
            Options.Provider = Options.Provider ?? new CookieAuthenticationProvider();

            if (String.IsNullOrEmpty(Options.CookieName))
            {
                Options.CookieName = CookieAuthenticationDefaults.CookiePrefix + Options.AuthenticationType;
            }

            _logger = app.CreateLogger <OapCookieAuthenticationMiddleware>();

            if (Options.TicketDataFormat == null)
            {
                IDataProtector dataProtector = app.CreateDataProtector(
                    typeof(OapCookieAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");

                Options.TicketDataFormat = new TicketDataFormat(dataProtector);
            }
            if (Options.CookieManager == null)
            {
                Options.CookieManager = new ChunkingCookieManager();
            }
        }
Example #13
0
        public Saml2AuthenticationMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            Saml2AuthenticationOptions options)
            : base(next, options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            if (options.SPOptions == null)
            {
                throw new ConfigurationErrorsException(
                          "The options.SPOptions property cannot be null. There is an implementation class Sustainsys.Saml2.Configuration.SPOptions that you can instantiate. The EntityId property of that class is mandatory. It must be set to the EntityId used to represent this system.");
            }

            if (options.SPOptions.EntityId == null)
            {
                throw new ConfigurationErrorsException(
                          "The SPOptions.EntityId property cannot be null. It must be set to the EntityId used to represent this system.");
            }

            if (string.IsNullOrEmpty(options.SignInAsAuthenticationType))
            {
                options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            options.DataProtector = app.CreateDataProtector(
                typeof(Saml2AuthenticationMiddleware).FullName);

            if (options.SPOptions.Logger == null)
            {
                options.SPOptions.Logger = new OwinLoggerAdapter(app.CreateLogger <Saml2AuthenticationMiddleware>());
            }
        }
Example #14
0
        /// <summary>Creates a new <see cref="ImgurAuthenticationMiddleware"/>.</summary>
        /// <param name="next">The next <see cref="OwinMiddleware"/> in the configuration chain.</param>
        /// <param name="appBuilder">The OWIN <see cref="IAppBuilder"/> being configured.</param>
        /// <param name="options">The <see cref="ImgurAuthenticationOptions"/> to be used to set up the <see cref="ImgurAuthenticationMiddleware"/>.</param>
        public ImgurAuthenticationMiddleware(OwinMiddleware next, IAppBuilder appBuilder, ImgurAuthenticationOptions options)
            : base(next, options)
        {
            if (appBuilder == null)
            {
                throw new ArgumentNullException(nameof(appBuilder));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            CheckClientId();
            CheckClientSecret();
            SetProvider();
            SetSignInAsAuthenticationType(appBuilder);
            SetStateDataFormat(appBuilder);

            var httpMessageHandler = ResolveHttpMessageHandler(Options);

            _httpClient = new HttpClient(httpMessageHandler);
            _logger     = appBuilder.CreateLogger <ImgurAuthenticationMiddleware>();
        }
        public VkAuthenticationMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            VkAuthenticationOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <VkAuthenticationMiddleware>();

            if (Options.Provider == null)
            {
                Options.Provider = new VkAuthenticationProvider();
            }
            if (Options.StateDataFormat == null)
            {
                var dataProtector = app.CreateDataProtector(
                    typeof(VkAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            _httpClient         = new HttpClient(ResolveHttpMessageHandler(Options));
            _httpClient.Timeout = Options.BackchannelTimeout;
            _httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10;             // 10 MB
        }
Example #16
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger(GetType());

            app.SetDataProtectionProvider(new SharedSecretDataProtectionProvider(
                "af98j3pf98ja3fdopa32hr !!!! DO NOT USE THIS STRING IN YOUR APP !!!!",
                "AES",
                "HMACSHA256"));

            // example of a filter - writeline each request
            app.UseFilter(req => logger.WriteInformation(string.Format(
                "{0} {1}{2} {3}",
                req.Method,
                req.PathBase,
                req.Path,
                req.QueryString)));

            // example of a handler - all paths reply Hello, Owin!
            app.UseHandler(async (req, res) =>
            {
                res.ContentType = "text/plain";
                await res.WriteAsync("Hello, OWIN!");
            });
        }
Example #17
0
        /// <summary>
        /// Initializes a <see cref="DoYouBuzzAuthenticationMiddleware"/>
        /// </summary>
        /// <param name="next">The next middleware in the OWIN pipeline to invoke</param>
        /// <param name="app">The OWIN application</param>
        /// <param name="options">Configuration options for the middleware</param>
        public DoYouBuzzAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, DoYouBuzzAuthenticationOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <DoYouBuzzAuthenticationMiddleware>();

            if (string.IsNullOrWhiteSpace(Options.ConsumerSecret))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "ConsumerSecret"));
            }

            if (string.IsNullOrWhiteSpace(Options.ConsumerKey))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "ConsumerKey"));
            }

            if (Options.Provider == null)
            {
                Options.Provider = new DoYouBuzzAuthenticationProvider();
            }
            if (Options.StateDataFormat == null)
            {
                var dataProtector = app.CreateDataProtector(typeof(DoYouBuzzAuthenticationMiddleware).FullName, Options.AuthenticationType, "v1");
                Options.StateDataFormat = new SecureDataFormat <RequestToken>(Serializers.RequestToken, dataProtector, TextEncodings.Base64Url);
            }
            if (string.IsNullOrEmpty(Options.SignInAsAuthenticationType))
            {
                Options.SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            _httpClient         = new HttpClient(ResolveHttpMessageHandler(Options));
            _httpClient.Timeout = Options.BackchannelTimeout;
            _httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
            _httpClient.DefaultRequestHeaders.Accept.ParseAdd("*/*");
            _httpClient.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft Owin DoYouBuzz middleware");
            _httpClient.DefaultRequestHeaders.ExpectContinue = false;
        }
Example #18
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger(GetType());

            app.SetDataProtectionProvider(new SharedSecretDataProtectionProvider(
                                              "af98j3pf98ja3fdopa32hr !!!! DO NOT USE THIS STRING IN YOUR APP !!!!",
                                              "AES",
                                              "HMACSHA256"));

            // example of a filter - writeline each request
            app.UseFilter(req => logger.WriteInformation(string.Format(
                                                             "{0} {1}{2} {3}",
                                                             req.Method,
                                                             req.PathBase,
                                                             req.Path,
                                                             req.QueryString)));

            // example of a handler - all paths reply Hello, Owin!
            app.UseHandler(async(req, res) =>
            {
                res.ContentType = "text/plain";
                await res.WriteAsync("Hello, OWIN!");
            });
        }
Example #19
0
        public KachingApiAuthenticationMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            KachingApiAuthenticationOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <KachingApiAuthenticationMiddleware>();

            if (Options.Provider == null)
            {
                Options.Provider = new KachingApiAuthenticationProvider
                {
                    OnValidateIdentity = context =>
                    {
                        if (string.Equals(context.ApiKey, Options.ApiKey, StringComparison.Ordinal))
                        {
                            context.Validate();
                        }

                        return(Task.FromResult(0));
                    }
                };
            }
        }
Example #20
0
        public OAuthAuthorizationServerMiddleware(
            OwinMiddleware next,
            IAppBuilder app,
            OAuthAuthorizationServerOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <OAuthAuthorizationServerMiddleware>();

            if (options.AccessCodeHandler == null)
            {
                var dataProtecter = app.CreateDataProtecter(
                    typeof(OAuthAuthorizationServerMiddleware).FullName,
                    "Access Code");

                options.AccessCodeHandler = new TicketDataHandler(dataProtecter);
            }
            if (options.AccessTokenHandler == null)
            {
                var dataProtecter = app.CreateDataProtecter(
                    typeof(OAuthAuthorizationServerMiddleware).Namespace,
                    "Access Token");
                options.AccessTokenHandler = new TicketDataHandler(dataProtecter);
            }
        }
Example #21
0
        /// <summary>
        /// Configure a custom BackOfficeUserManager for Umbraco
        /// </summary>
        /// <param name="app"></param>
        /// <param name="runtimeState"></param>
        /// <param name="globalSettings"></param>
        /// <param name="userManager"></param>
        public static void ConfigureUserManagerForUmbracoBackOffice <TManager, TUser>(this IAppBuilder app,
                                                                                      IRuntimeState runtimeState,
                                                                                      IGlobalSettings globalSettings,
                                                                                      Func <IdentityFactoryOptions <TManager>, IOwinContext, TManager> userManager)
            where TManager : BackOfficeUserManager <TUser>
            where TUser : BackOfficeIdentityUser
        {
            if (runtimeState == null)
            {
                throw new ArgumentNullException(nameof(runtimeState));
            }
            if (userManager == null)
            {
                throw new ArgumentNullException(nameof(userManager));
            }

            //Configure Umbraco user manager to be created per request
            app.CreatePerOwinContext <TManager>(userManager);

            app.SetBackOfficeUserManagerType <TManager, TUser>();

            //Create a sign in manager per request
            app.CreatePerOwinContext <BackOfficeSignInManager>(
                (options, context) => BackOfficeSignInManager.Create(options, context, globalSettings, app.CreateLogger(typeof(BackOfficeSignInManager).FullName)));
        }
 public APIOpenIdConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, OpenIdConnectAuthenticationOptions options) : base(next, app, options)
 {
     _logger  = app.CreateLogger <APIOpenIdConnectAuthenticationMiddleware>();
     _options = options;
 }
Example #23
0
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap = new Dictionary <string, string>
            {
                { "name", ClaimTypes.Name },
                { "role", ClaimTypes.Role },
                { "email", ClaimTypes.NameIdentifier },
                { "sid", SessionClaimType },
                { "tenantid", TenantIdClaimType },
                { "locale", ClaimTypes.Locality }
            };

            app.Use(async(context, next) =>
            {
                if (Trace.CorrelationManager.ActivityId == Guid.Empty)
                {
                    Trace.CorrelationManager.ActivityId = Guid.NewGuid();
                }

                await next();
            });


            app.UseCors(new CorsOptions()
            {
                PolicyProvider = new DynamicCorsPolicy()
            });

            logger = app.CreateLogger <Startup>();


            app.Use <LogoutMiddleware>(app);


            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);


            //Use https protocol in case of SSL Offload (for OWIN middleware correct reply address generation)
            app.Use(async(context, next) =>
            {
                if (String.Equals(ConfigurationManager.AppSettings["SslOffload"],
                                  bool.TrueString, StringComparison.InvariantCultureIgnoreCase))
                {
                    context.Request.Scheme = Uri.UriSchemeHttps;
                }

                await next.Invoke();
            });



            app.Use(async(context, next) =>
            {
                var redirectHost =
                    $"{new Uri(OpenIdConnectAuthentication.Default.RedirectUri).GetComponents(UriComponents.Host, UriFormat.Unescaped)}".TrimEnd('/');
                var redirectHostAndPort =
                    $"{new Uri(OpenIdConnectAuthentication.Default.RedirectUri).GetComponents(UriComponents.HostAndPort, UriFormat.Unescaped)}".TrimEnd('/');
                if (!context.Request.Host.ToString().Equals(redirectHost, StringComparison.Ordinal) &&
                    !context.Request.Host.ToString().Equals(redirectHostAndPort, StringComparison.Ordinal))
                {
                    context.Request.Host = new HostString(redirectHost);
                }
                var baseRedirectPath =
                    $"/{new Uri(OpenIdConnectAuthentication.Default.RedirectUri).GetComponents(UriComponents.Path, UriFormat.Unescaped)}".TrimEnd('/');
                if (context.Request.PathBase == new PathString(baseRedirectPath) &&
                    !context.Request.PathBase.ToString().Equals(baseRedirectPath, StringComparison.Ordinal))
                {
                    context.Request.PathBase = new PathString(baseRedirectPath);
                }
                await next.Invoke();
            });


            app.UseCustomBearerTokenAuthentication(new BearerTokenAuthenticationOptions()
            {
                Authority          = OpenIdConnectAuthentication.Default.Authority,
                AuthenticationMode = AuthenticationMode.Active,
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = CookieAuthenticationDefaults.AuthenticationType,
                CookieManager      = new SystemWebChunkingCookieManager(),
                CookiePath         =
                    $"/{new Uri(OpenIdConnectAuthentication.Default.RedirectUri).GetComponents(UriComponents.Path, UriFormat.Unescaped)}",
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = ctx =>
                    {
                        //Here we mix-into the token a new claim based on request query parameter
                        //if (!ctx.Identity.HasClaim(c => c.Type == EmploymentIdClaimType) && ctx.Request.Query.Any(q => q.Key == "aeid"))
                        //{
                        //    ctx.Identity.AddClaim(new Claim(EmploymentIdClaimType, ctx.Request.Query["aeid"]));
                        //}
                        return(Task.FromResult(0));
                    },

                    OnApplyRedirect = ctx =>
                    {
                        if (!ctx.Request.IsAjaxRequest())
                        {
                            ctx.Response.Redirect(ctx.RedirectUri);
                        }
                    }
                },
                ExpireTimeSpan    = TimeSpan.FromSeconds(600),
                SlidingExpiration = true
            });

            //tenant check
            //compare the setting in configuration file with the value coming from idp
            app.Use(async(context, next) =>
            {
                if (context.Authentication?.User?.Identity.IsAuthenticated == true &&
                    !String.IsNullOrWhiteSpace(TenantIdSetting) &&
                    !String.Equals(context.Authentication.User.FindFirst(TenantIdClaimType)?.Value, TenantIdSetting, StringComparison.InvariantCultureIgnoreCase))
                {
                    context.Authentication.SignOut(CookieAuthenticationDefaults.AuthenticationType);
                    context.Response.Redirect(OpenIdConnectAuthentication.Default.Authority.TrimEnd('/') +
                                              "/home/error?errorId=tenant-mismatch");
                }
                else
                {
                    await next();
                }
            });



            app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions()
            {
                RequireHttpsMetadata = false,
                //Authority = "http://localhost:5100", //ID Server
                Authority    = OpenIdConnectAuthentication.Default.Authority,
                ClientId     = OpenIdConnectAuthentication.Default.ClientId,     //"spa-client",
                ResponseType = OpenIdConnectAuthentication.Default.ResponseType, //"id_token","id_token code"
                ClientSecret = OpenIdConnectAuthentication.Default.ClientSecret,
                SignInAsAuthenticationType = Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie,
                //UseTokenLifetime = false,
                //ProtocolValidator = new OpenIdConnectProtocolValidator()
                //{
                //    NonceLifetime = new TimeSpan(0,0,20,0)
                //    //RequireNonce = false,
                //},
                CookieManager = new SystemWebChunkingCookieManager(),

                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateAudience = false
                },
                RedirectUri           = OpenIdConnectAuthentication.Default.RedirectUri, //URL of website
                Scope                 = OpenIdConnectAuthentication.Default.Scope,       // "openid email roles", //", profile
                PostLogoutRedirectUri = OpenIdConnectAuthentication.Default.RedirectUri, //"http://google.com",
                Notifications         = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = notification =>
                    {
                        if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Logout &&
                            notification.OwinContext.Authentication.User?.Claims.FirstOrDefault(_ => _.Type == "id_token") !=
                            null)
                        {
                            var idTokenHint = notification.OwinContext.Authentication.User.FindFirst("id_token").Value;
                            notification.ProtocolMessage.IdTokenHint           = idTokenHint;
                            notification.ProtocolMessage.PostLogoutRedirectUri =
                                notification.OwinContext.Authentication?.AuthenticationResponseRevoke?.Properties?.RedirectUri ??
                                OpenIdConnectAuthentication.Default.RedirectUri;
                        }

                        if (notification.ProtocolMessage.RequestType == OpenIdConnectRequestType.Authentication)
                        {
                            if (notification.Request.IsAjaxRequest() || notification.Request.Uri.OriginalString.IndexOf("/api/", StringComparison.InvariantCultureIgnoreCase) >= 0)
                            {
                                var builder = new StringBuilder();
                                builder.AppendLine("Ajax call to restricted content.");
                                builder.AppendLine($" request uri:{notification.Request.Uri}");
                                var headers = notification.Request?.Headers?.Select(x => $"{x.Key}:{String.Join(", ", x.Value)};");
                                if (headers != null)
                                {
                                    builder.AppendLine($"request headers:");
                                }
                                if (headers != null)
                                {
                                    foreach (var header in headers)
                                    {
                                        builder.AppendLine(header);
                                    }
                                }
                                logger.WriteInformation(builder.ToString());



                                notification.HandleResponse();
                            }
                        }

                        return(Task.FromResult(0));
                    },

                    AuthenticationFailed = context =>
                    {
                        //helps to solve some issues of nonce validation with IFrame
                        //most likely this case never occur in normal scenario
                        if (context.Exception.Message.StartsWith("OICE_20004") ||
                            context.Exception.Message.Contains("IDX10311"))
                        {
                            context.SkipToNextMiddleware();
                            return(Task.FromResult(0));
                        }

                        context.HandleResponse();

                        logger.WriteError(context.Exception.Message, context.Exception);
                        context.Response.WriteAsync(context.Exception.Message);
                        return(Task.FromResult(0));
                    },

                    SecurityTokenValidated = async n =>
                    {
                        var id    = n.AuthenticationTicket.Identity;
                        var props = n.AuthenticationTicket.Properties;
                        var t     = n.ProtocolMessage.AccessToken;

                        // we want to keep name and roles
                        var email = id.FindFirst(ClaimTypes.NameIdentifier);
                        var sub   = id.FindFirst("sub");
                        //var sub = id.FindFirst(JwtClaimTypes.Subject);
                        var roles  = id.FindAll(ClaimTypes.Role).Distinct();
                        var locale = id.FindFirst(ClaimTypes.Locality) ?? new Claim(ClaimTypes.Locality, DefaultLocale);

                        var idp = id.FindFirst("idp");
                        var iss = id.FindFirst("iss");
                        var exp = id.FindFirst("exp");
                        //var idp = id.FindFirst(JwtClaimTypes.IdentityProvider);
                        //var iss = id.FindFirst(JwtClaimTypes.Issuer);
                        //var exp = id.FindFirst(JwtClaimTypes.Expiration);
                        //var aud =  id.FindFirst("aud");
                        var sid = id.FindFirst(SessionClaimType);
                        var tid = id.FindFirst(TenantIdClaimType);

                        // create new identity and set name and role claim type
                        var nid = new ClaimsIdentity(
                            id.AuthenticationType,
                            ClaimTypes.NameIdentifier,
                            ClaimTypes.Role);

                        nid.AddClaim(email);
                        nid.AddClaims(roles);
                        nid.AddClaim(idp);
                        nid.AddClaim(iss);
                        //nid.AddClaim(aud);
                        nid.AddClaim(sub);
                        nid.AddClaim(sid);
                        //nid.AddClaim(tid);
                        nid.AddClaim(locale);
                        nid.AddClaim(new Claim(CultureClaimType, locale.Value, locale.ValueType, locale.Issuer));
                        nid.AddClaim(new Claim("id_token", n.ProtocolMessage.IdToken));
                        if (n.ProtocolMessage.AccessToken != null)
                        {
                            nid.AddClaim(new Claim("token", n.ProtocolMessage.AccessToken));
                            var handler = new JwtSecurityTokenHandler();
                            var tokenS  = handler.ReadToken(n.ProtocolMessage.AccessToken) as JwtSecurityToken;
                            foreach (var module in tokenS.Claims.Where(c => c.Type == SupportedModuleClaimType))
                            {
                                nid.AddClaim(module);
                            }
                        }


                        // add some other app specific claim
                        //nid.AddClaim(new Claim("app_specific", "some data"));
                        nid.AddClaim(new Claim(ClaimTypes.Name, email.Value, email.ValueType, email.Issuer));

                        if (n.ProtocolMessage.AccessToken != null)
                        {
                            var delegatedToken = await DelegateAsync(n.ProtocolMessage.AccessToken);
                        }

                        //var timeInTicks = long.Parse(exp.Value) * TimeSpan.TicksPerSecond;
                        //var expTime = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddTicks(timeInTicks);
                        //n.AuthenticationTicket.Properties.ExpiresUtc = expTime;
                        //n.Response
                        n.AuthenticationTicket = new AuthenticationTicket(
                            nid,
                            n.AuthenticationTicket.Properties);


                        n.AuthenticationTicket.Properties.AllowRefresh = true;
                        n.AuthenticationTicket.Properties.IsPersistent = true;


                        await Task.FromResult(0);
                    }
                }
            });

            app.UseStageMarker(PipelineStage.Authenticate);
        }
Example #24
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger("Katana.Sandbox.WebServer");

            logger.WriteInformation("Application Started");

            app.UseHandlerAsync(async(req, res, next) =>
            {
                req.TraceOutput.WriteLine("{0} {1}{2}", req.Method, req.PathBase, req.Path);
                await next();
                req.TraceOutput.WriteLine("{0} {1}{2}", res.StatusCode, req.PathBase, req.Path);
            });

            app.UseFormsAuthentication(new FormsAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = AuthenticationMode.Passive,
                LoginPath          = "/Login",
                LogoutPath         = "/Logout",
            });

            app.UseExternalSignInCookie();

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                SignInAsAuthenticationType = "External",
                AppId     = "615948391767418",
                AppSecret = "c9b1fa6b68db835890ce469e0d98157f",
                // Scope = "email user_birthday user_website"
            });

            app.UseGoogleAuthentication();

            app.UseTwitterAuthentication("6XaCTaLbMqfj6ww3zvZ5g", "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI");

            app.UseMicrosoftAccountAuthentication("000000004C0EA787", "QZde5m5HHZPxdieV0lOy7bBVTbVqR9Ju");

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
            });

            // CORS support
            app.UseHandlerAsync(async(req, res, next) =>
            {
                // for auth2 token requests, and web api requests
                if (req.Path == "/Token" || req.Path.StartsWith("/api/"))
                {
                    // if there is an origin header
                    var origin = req.GetHeader("Origin");
                    if (!string.IsNullOrEmpty(origin))
                    {
                        // allow the cross-site request
                        res.AddHeader("Access-Control-Allow-Origin", origin);
                    }

                    // if this is pre-flight request
                    if (req.Method == "OPTIONS")
                    {
                        // respond immediately with allowed request methods and headers
                        res.StatusCode = 200;
                        res.AddHeaderJoined("Access-Control-Allow-Methods", "GET", "POST");
                        res.AddHeaderJoined("Access-Control-Allow-Headers", "authorization");
                        // no further processing
                        return;
                    }
                }
                // continue executing pipeline
                await next();
            });

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath = "/Authorize",
                TokenEndpointPath     = "/Token",
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientCredentials        = OnValidateClientCredentials,
                    OnValidateResourceOwnerCredentials = OnValidateResourceOwnerCredentials,
                },
            });

            var config = new HttpConfiguration();

            config.Routes.MapHttpRoute("Default", "api/{controller}");
            app.UseWebApi(config);
        }
Example #25
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger("Katana.Sandbox.WebServer");

            logger.WriteInformation("Application Started");

            app.Use(async (context, next) =>
            {
                context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Request.Method, context.Request.PathBase, context.Request.Path);
                await next();
                context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Response.StatusCode, context.Request.PathBase, context.Request.Path);
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Federation",
            });

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
            {
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive, // or active
                CallbackPath = new PathString("/signin-wsfed"), // optional constraint
                Wtrealm = "http://Katana.Sandbox.WebServer",
                MetadataAddress = "https://login.windows.net/cdc690f9-b6b8-4023-813a-bae7143d1f87/FederationMetadata/2007-06/FederationMetadata.xml",
                Notifications = new WsFederationAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = new Func<RedirectToIdentityProviderNotification<WsFederationMessage>, Task>(context =>
                        {
                            context.ProtocolMessage.Wctx += "&foo=bar";
                            return Task.FromResult(0);
                        }),
                },
            });
            /*
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = AuthenticationMode.Passive,
                LoginPath = new PathString("/Login"),
                LogoutPath = new PathString("/Logout"),
            });

            app.SetDefaultSignInAsAuthenticationType("External");

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "External",
                AuthenticationMode = AuthenticationMode.Passive,
                CookieName = CookieAuthenticationDefaults.CookiePrefix + "External",
                ExpireTimeSpan = TimeSpan.FromMinutes(5),
            });

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId = "615948391767418",
                AppSecret = "c9b1fa6b68db835890ce469e0d98157f",
                // Scope = "email user_birthday user_website"
            });

            app.UseGoogleAuthentication(clientId: "41249762691.apps.googleusercontent.com", clientSecret: "oDWPQ6e09MN5brDBDAnS_vd9");

            app.UseTwitterAuthentication("6XaCTaLbMqfj6ww3zvZ5g", "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI");

            app.UseMicrosoftAccountAuthentication("000000004C0EA787", "QZde5m5HHZPxdieV0lOy7bBVTbVqR9Ju");

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
            });

            // CORS support
            app.Use(async (context, next) =>
            {
                IOwinRequest req = context.Request;
                IOwinResponse res = context.Response;
                // for auth2 token requests, and web api requests
                if (req.Path.StartsWithSegments(new PathString("/Token")) ||
                    req.Path.StartsWithSegments(new PathString("/api")))
                {
                    // if there is an origin header
                    var origin = req.Headers.Get("Origin");
                    if (!string.IsNullOrEmpty(origin))
                    {
                        // allow the cross-site request
                        res.Headers.Set("Access-Control-Allow-Origin", origin);
                    }

                    // if this is pre-flight request
                    if (req.Method == "OPTIONS")
                    {
                        // respond immediately with allowed request methods and headers
                        res.StatusCode = 200;
                        res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                        res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization");
                        // no further processing
                        return;
                    }
                }
                // continue executing pipeline
                await next();
            });

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath = new PathString("/Authorize"),
                TokenEndpointPath = new PathString("/Token"),
                ApplicationCanDisplayErrors = true,
#if DEBUG
                AllowInsecureHttp = true,
#endif
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientRedirectUri = ValidateClientRedirectUri,
                    OnValidateClientAuthentication = ValidateClientAuthentication,
                    OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                },
                AuthorizationCodeProvider = new AuthenticationTokenProvider
                {
                    OnCreate = CreateAuthenticationCode,
                    OnReceive = ReceiveAuthenticationCode,
                },
                RefreshTokenProvider = new AuthenticationTokenProvider
                {
                    OnCreate = CreateRefreshToken,
                    OnReceive = ReceiveRefreshToken,
                }
            });
            */
            app.Map("/api", map => map.Run(async context =>
            {
                var response = context.Response;
                var user = context.Authentication.User;
                // var result = await context.Authentication.AuthenticateAsync("Federation");
                if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
                {
                    context.Authentication.Challenge("Federation");
                    return;
                }
                var identity = user.Identities.First();
                // var properties = result.Properties.Dictionary;

                response.ContentType = "application/json";
                response.Write("{\"Details\":[");
                foreach (var claim in identity.Claims)
                {
                    response.Write("{\"Name\":\"");
                    response.Write(claim.Type);
                    response.Write("\",\"Value\":\"");
                    response.Write(claim.Value);
                    response.Write("\",\"Issuer\":\"");
                    response.Write(claim.Issuer);
                    response.Write("\"},"); // TODO: No comma on the last one
                }
                response.Write("],\"Properties\":[");
                /*
                foreach (var pair in properties)
                {
                    response.Write("{\"Name\":\"");
                    response.Write(pair.Key);
                    response.Write("\",\"Value\":\"");
                    response.Write(pair.Value);
                    response.Write("\"},"); // TODO: No comma on the last one
                }*/
                response.Write("]}");
            }));
        }
Example #26
0
 private CustomListenerHost(IListen listener, Func <IDictionary <string, object>, Task> app, IAppBuilder builder)
 {
     _listener = listener;
     _app      = app;
     _logger   = builder.CreateLogger("HttpOS.Owin.CLH");
 }
Example #27
0
 public void Configuration(IAppBuilder app)
 {
     ILogger logger = app.CreateLogger<Startup>();
     logger.WriteError("App is starting up");
     ConfigureAuth(app);
 }
 public ForceSslAlwaysMiddleware(OwinMiddleware next, IAppBuilder app, int sslPort)
     : base(next)
 {
     SslPort = sslPort;
     _logger = app.CreateLogger<ForceSslAlwaysMiddleware>();
 }
Example #29
0
        /// <summary>
        /// Configure a custom UserStore with the Identity User Manager for Umbraco
        /// </summary>
        /// <param name="app"></param>
        /// <param name="appContext"></param>
        /// <param name="userMembershipProvider"></param>
        /// <param name="customUserStore"></param>
        public static void ConfigureUserManagerForUmbracoBackOffice(this IAppBuilder app,
                                                                    ApplicationContext appContext,
                                                                    MembershipProviderBase userMembershipProvider,
                                                                    BackOfficeUserStore customUserStore)
        {
            if (appContext == null)
            {
                throw new ArgumentNullException("appContext");
            }
            if (userMembershipProvider == null)
            {
                throw new ArgumentNullException("userMembershipProvider");
            }
            if (customUserStore == null)
            {
                throw new ArgumentNullException("customUserStore");
            }

            //Configure Umbraco user manager to be created per request
            app.CreatePerOwinContext <BackOfficeUserManager>(
                (options, owinContext) => BackOfficeUserManager.Create(
                    options,
                    customUserStore,
                    userMembershipProvider));

            //Create a sign in manager per request
            app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, app.CreateLogger(typeof(BackOfficeSignInManager).FullName)));
        }
Example #30
0
        /// <summary>
        /// Configure Default Identity User Manager for Umbraco
        /// </summary>
        /// <param name="app"></param>
        /// <param name="appContext"></param>
        /// <param name="userMembershipProvider"></param>
        public static void ConfigureUserManagerForUmbracoBackOffice(this IAppBuilder app,
                                                                    ApplicationContext appContext,
                                                                    MembershipProviderBase userMembershipProvider)
        {
            if (appContext == null)
            {
                throw new ArgumentNullException("appContext");
            }
            if (userMembershipProvider == null)
            {
                throw new ArgumentNullException("userMembershipProvider");
            }

            //Configure Umbraco user manager to be created per request
            app.CreatePerOwinContext <BackOfficeUserManager>(
                (options, owinContext) => BackOfficeUserManager.Create(
                    options,
                    appContext.Services.UserService,
                    appContext.Services.ExternalLoginService,
                    userMembershipProvider));

            //Create a sign in manager per request
            app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, app.CreateLogger <BackOfficeSignInManager>()));
        }
Example #31
0
        /// <summary>
        /// Configure a custom BackOfficeUserManager for Umbraco
        /// </summary>
        /// <param name="app"></param>
        /// <param name="appContext"></param>
        /// <param name="userManager"></param>
        public static void ConfigureUserManagerForUmbracoBackOffice <TManager, TUser>(this IAppBuilder app,
                                                                                      ApplicationContext appContext,
                                                                                      Func <IdentityFactoryOptions <TManager>, IOwinContext, TManager> userManager)
            where TManager : BackOfficeUserManager <TUser>
            where TUser : BackOfficeIdentityUser
        {
            if (appContext == null)
            {
                throw new ArgumentNullException("appContext");
            }
            if (userManager == null)
            {
                throw new ArgumentNullException("userManager");
            }

            //Configure Umbraco user manager to be created per request
            app.CreatePerOwinContext <TManager>(userManager);

            //Create a sign in manager per request
            app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, app.CreateLogger(typeof(BackOfficeSignInManager).FullName)));
        }
 public MyCookieAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, CookieAuthenticationOptions options)
     : base(next, app, options)
 {
     _logger = app.CreateLogger<CookieAuthenticationMiddleware>();
 }
Example #33
0
 public MyOpenIDConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app,
     OpenIdConnectAuthenticationOptions options) : base(next, app, options)
 {
     _logger = app.CreateLogger<MyOpenIDConnectAuthenticationMiddleware>();
 }
Example #34
0
        /// <summary>
        /// Configure Default Identity User Manager for Umbraco
        /// </summary>
        /// <param name="app"></param>
        /// <param name="services"></param>
        /// <param name="contentSettings"></param>
        /// <param name="globalSettings"></param>
        /// <param name="userMembershipProvider"></param>
        public static void ConfigureUserManagerForUmbracoBackOffice(this IAppBuilder app,
                                                                    ServiceContext services,
                                                                    IContentSection contentSettings,
                                                                    IGlobalSettings globalSettings,
                                                                    MembershipProviderBase userMembershipProvider)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            if (userMembershipProvider == null)
            {
                throw new ArgumentNullException(nameof(userMembershipProvider));
            }

            //Configure Umbraco user manager to be created per request
            app.CreatePerOwinContext <BackOfficeUserManager>(
                (options, owinContext) => BackOfficeUserManager.Create(
                    options,
                    services.UserService,
                    services.MemberTypeService,
                    services.EntityService,
                    services.ExternalLoginService,
                    userMembershipProvider,
                    contentSettings,
                    globalSettings));

            app.SetBackOfficeUserManagerType <BackOfficeUserManager, BackOfficeIdentityUser>();

            //Create a sign in manager per request
            app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, globalSettings, app.CreateLogger <BackOfficeSignInManager>()));
        }
Example #35
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger("Katana.Sandbox.WebServer");

            logger.WriteInformation("Application Started");

            app.UseErrorPage(Microsoft.Owin.Diagnostics.ErrorPageOptions.ShowAll);

            app.Use(async(context, next) =>
            {
                context.Get <TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Request.Method, context.Request.PathBase, context.Request.Path);
                await next();
                context.Get <TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Response.StatusCode, context.Request.PathBase, context.Request.Path);
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                // LoginPath = new PathString("/Account/Login"),
            });

            app.SetDefaultSignInAsAuthenticationType("External");

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "External",
                AuthenticationMode = AuthenticationMode.Active,
                CookieName         = CookieAuthenticationDefaults.CookiePrefix + "External",
                ExpireTimeSpan     = TimeSpan.FromMinutes(5),
                CookieManager      = new SystemWebChunkingCookieManager()
            });

            // https://developers.facebook.com/apps/
            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId         = Environment.GetEnvironmentVariable("facebook:appid"),
                AppSecret     = Environment.GetEnvironmentVariable("facebook:appsecret"),
                Scope         = { "email" },
                Fields        = { "name", "email" },
                CookieManager = new SystemWebCookieManager()
            });

            // https://console.developers.google.com/apis/credentials
            // https://developers.google.com/identity/protocols/OAuth2WebServer
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = Environment.GetEnvironmentVariable("google:clientid"),
                ClientSecret = Environment.GetEnvironmentVariable("google:clientsecret"),
            });

            //// Flow to get user identifier in OpenID for migration to OAuth 2.0
            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "448955186993-2vmtajdpl41ipktlg809780c0craq88e.apps.googleusercontent.com",
            //    ClientSecret = "Ngdb_GRmO3X2pC3WVt73Rod0",
            //    Provider = new GoogleOAuth2AuthenticationProvider()
            //    {
            //        OnApplyRedirect = context =>
            //        {
            //            // Add openid realm to get openid identifier in token response
            //            context.Response.Redirect(context.RedirectUri + "&openid.realm=http://localhost:49222/");
            //        },

            //        OnAuthenticated = context =>
            //        {
            //            var idToken = context.TokenResponse.Value<string>("id_token");
            //            var jwtIdToken = new JwtSecurityToken(idToken);
            //            var claims = jwtIdToken.Claims;

            //            var openid_id = claims.FirstOrDefault(x => x.Type.Equals("openid_id", StringComparison.CurrentCulture));
            //            return Task.FromResult(0);
            //        }
            //    }
            //});

            // https://apps.twitter.com/
            // https://dev.twitter.com/web/sign-in/implementing
            app.UseTwitterAuthentication(Environment.GetEnvironmentVariable("twitter:consumerkey"), Environment.GetEnvironmentVariable("twitter:consumersecret"));

            // https://azure.microsoft.com/en-us/documentation/articles/active-directory-v2-app-registration/
            app.UseMicrosoftAccountAuthentication(Environment.GetEnvironmentVariable("microsoftaccount:clientid"), Environment.GetEnvironmentVariable("microsoftaccount:clientsecret"));

            // app.UseAspNetAuthSession();

            /*
             * app.UseCookieAuthentication(new CookieAuthenticationOptions()
             * {
             *  SessionStore = new InMemoryAuthSessionStore()
             * });
             * app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
             */

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
            {
                Wtrealm         = "https://tratcheroutlook.onmicrosoft.com/AspNetCoreSample",
                MetadataAddress = "https://login.windows.net/cdc690f9-b6b8-4023-813a-bae7143d1f87/FederationMetadata/2007-06/FederationMetadata.xml",
            });

            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions()
            {
                Authority     = Environment.GetEnvironmentVariable("oidc:authority"),
                ClientId      = Environment.GetEnvironmentVariable("oidc:clientid"),
                RedirectUri   = "https://localhost:44318/",
                CookieManager = new SystemWebCookieManager()
            });

            /*
             * app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
             * {
             * });
             *
             * // CORS support
             * app.Use(async (context, next) =>
             * {
             *  IOwinRequest req = context.Request;
             *  IOwinResponse res = context.Response;
             *  // for auth2 token requests, and web api requests
             *  if (req.Path.StartsWithSegments(new PathString("/Token")) ||
             *      req.Path.StartsWithSegments(new PathString("/api")))
             *  {
             *      // if there is an origin header
             *      var origin = req.Headers.Get("Origin");
             *      if (!string.IsNullOrEmpty(origin))
             *      {
             *          // allow the cross-site request
             *          res.Headers.Set("Access-Control-Allow-Origin", origin);
             *      }
             *
             *      // if this is pre-flight request
             *      if (req.Method == "OPTIONS")
             *      {
             *          // respond immediately with allowed request methods and headers
             *          res.StatusCode = 200;
             *          res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
             *          res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization");
             *          // no further processing
             *          return;
             *      }
             *  }
             *  // continue executing pipeline
             *  await next();
             * });
             *
             * app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
             * {
             *  AuthorizeEndpointPath = new PathString("/Authorize"),
             *  TokenEndpointPath = new PathString("/Token"),
             *  ApplicationCanDisplayErrors = true,
             #if DEBUG
             *  AllowInsecureHttp = true,
             #endif
             *  Provider = new OAuthAuthorizationServerProvider
             *  {
             *      OnValidateClientRedirectUri = ValidateClientRedirectUri,
             *      OnValidateClientAuthentication = ValidateClientAuthentication,
             *      OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
             *  },
             *  AuthorizationCodeProvider = new AuthenticationTokenProvider
             *  {
             *      OnCreate = CreateAuthenticationCode,
             *      OnReceive = ReceiveAuthenticationCode,
             *  },
             *  RefreshTokenProvider = new AuthenticationTokenProvider
             *  {
             *      OnCreate = CreateRefreshToken,
             *      OnReceive = ReceiveRefreshToken,
             *  }
             * });
             */
            app.Map("/signout", map =>
            {
                map.Run(context =>
                {
                    context.Authentication.SignOut("External");
                    var response         = context.Response;
                    response.ContentType = "text/html";
                    response.Write("<body><html>Signed out. <a href=\"/\">Home</a></html></body>");
                    return(Task.FromResult(0));
                });
            });
            app.Map("/challenge", map =>
            {
                map.Run(context =>
                {
                    var properties                  = new AuthenticationProperties();
                    properties.RedirectUri          = "/";              // Go back to the home page after authenticating.
                    properties.Dictionary["prompt"] = "select_account"; // Google
                    context.Authentication.Challenge(properties, context.Request.Query["scheme"]);
                    return(Task.FromResult(0));
                });
            });

            /*
             * app.Map("/Account/Login", map =>
             * {
             *  map.Run(context =>
             *  {
             *      // context.Authentication.Challenge("Google");
             *      return Task.FromResult(0);
             *  });
             * });
             */
            app.Use((context, next) =>
            {
                var user = context.Authentication.User;
                if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
                {
                    var response         = context.Response;
                    response.ContentType = "text/html";
                    response.Write("<html><body>Providers:<br>\r\n");
                    foreach (var provider in context.Authentication.GetAuthenticationTypes())
                    {
                        response.Write("- <a href=\"/challenge?scheme=");
                        response.Write(provider.AuthenticationType);
                        response.Write("\">");
                        response.Write(provider.AuthenticationType);
                        response.Write("</a><br>\r\n");
                    }
                    response.Write("</body></html>\r\n");
                    return(Task.FromResult(0));
                }
                return(next());
            });

            /*
             * app.Use((context, next) =>
             * {
             *  var user = context.Authentication.User;
             *  if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
             *  {
             *      context.Authentication.Challenge();
             *      // context.Authentication.Challenge("Facebook");
             *      return Task.FromResult(0);
             *  }
             *  return next();
             * });
             */
            app.Run(async context =>
            {
                var response = context.Response;
                var user     = context.Authentication.User;
                var identity = user.Identities.First();

                response.ContentType = "text/html";
                await response.WriteAsync("<html><body>Details:<br>\r\n");
                foreach (var claim in identity.Claims)
                {
                    response.Write("- ");
                    response.Write(claim.Type);
                    response.Write(": ");
                    response.Write(claim.Value);
                    response.Write("<br>\r\n");
                }
                response.Write("<a href=\"/signout\">Signout</a>\r\n");
                response.Write("</body></html>\r\n");
            });
        }
Example #36
0
        /// <summary>
        /// Configure a custom UserStore with the Identity User Manager for Umbraco
        /// </summary>
        /// <param name="app"></param>
        /// <param name="runtimeState"></param>
        /// <param name="globalSettings"></param>
        /// <param name="userMembershipProvider"></param>
        /// <param name="customUserStore"></param>
        /// <param name="contentSettings"></param>
        public static void ConfigureUserManagerForUmbracoBackOffice(this IAppBuilder app,
                                                                    IRuntimeState runtimeState,
                                                                    IContentSection contentSettings,
                                                                    IGlobalSettings globalSettings,
                                                                    MembershipProviderBase userMembershipProvider,
                                                                    BackOfficeUserStore customUserStore)
        {
            if (runtimeState == null)
            {
                throw new ArgumentNullException(nameof(runtimeState));
            }
            if (userMembershipProvider == null)
            {
                throw new ArgumentNullException(nameof(userMembershipProvider));
            }
            if (customUserStore == null)
            {
                throw new ArgumentNullException(nameof(customUserStore));
            }

            //Configure Umbraco user manager to be created per request
            app.CreatePerOwinContext <BackOfficeUserManager>(
                (options, owinContext) => BackOfficeUserManager.Create(
                    options,
                    customUserStore,
                    userMembershipProvider,
                    contentSettings));

            app.SetBackOfficeUserManagerType <BackOfficeUserManager, BackOfficeIdentityUser>();

            //Create a sign in manager per request
            app.CreatePerOwinContext <BackOfficeSignInManager>((options, context) => BackOfficeSignInManager.Create(options, context, globalSettings, app.CreateLogger(typeof(BackOfficeSignInManager).FullName)));
        }
Example #37
0
 public LogoutMiddleware(OwinMiddleware next, IAppBuilder app) : base(next)
 {
     this.logger = app.CreateLogger <LogoutMiddleware>();
 }
Example #38
0
        public OpenIdConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, OpenIdConnectAuthenticationOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <OpenIdConnectAuthenticationMiddleware>();

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.AuthenticationType))
            {
                Options.TokenValidationParameters.AuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            if (Options.StateDataFormat == null)
            {
                var dataProtector = app.CreateDataProtector(
                    typeof(OpenIdConnectAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            // if the user has not set the AuthorizeCallback, set it from the redirect_uri
            if (!Options.CallbackPath.HasValue)
            {
                Uri redirectUri;
                if (!string.IsNullOrEmpty(Options.RedirectUri) && Uri.TryCreate(Options.RedirectUri, UriKind.Absolute, out redirectUri))
                {
                    // Redirect_Uri must be a very specific, case sensitive value, so we can't generate it. Instead we generate AuthorizeCallback from it.
                    Options.CallbackPath = PathString.FromUriComponent(redirectUri);
                }
            }

            if (Options.Notifications == null)
            {
                Options.Notifications = new OpenIdConnectAuthenticationNotifications();
            }

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrWhiteSpace(Options.ClientId))
            {
                Options.TokenValidationParameters.ValidAudience = Options.ClientId;
            }

            if (Options.ConfigurationManager == null)
            {
                if (Options.Configuration != null)
                {
                    Options.ConfigurationManager = new StaticConfigurationManager <OpenIdConnectConfiguration>(Options.Configuration);
                }
                else if (!(string.IsNullOrEmpty(Options.MetadataAddress) && string.IsNullOrEmpty(Options.Authority)))
                {
                    if (string.IsNullOrEmpty(Options.MetadataAddress) && !string.IsNullOrEmpty(Options.Authority))
                    {
                        Options.MetadataAddress = Options.Authority;
                        if (!Options.MetadataAddress.EndsWith("/", StringComparison.Ordinal))
                        {
                            Options.MetadataAddress += "/";
                        }

                        Options.MetadataAddress += ".well-known/openid-configuration";
                    }

                    if (Options.RequireHttpsMetadata && !Options.MetadataAddress.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
                    {
                        throw new InvalidOperationException("The MetadataAddress or Authority must use HTTPS unless disabled for development by setting RequireHttpsMetadata=false.");
                    }

                    if (Options.Backchannel == null)
                    {
                        var backchannel = new HttpClient(ResolveHttpMessageHandler(Options));
                        backchannel.DefaultRequestHeaders.UserAgent.ParseAdd("Microsoft ASP.NET Core OpenIdConnect middleware");
                        backchannel.Timeout = Options.BackchannelTimeout;
                        backchannel.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
                        Options.Backchannel = backchannel;
                    }

                    Options.ConfigurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(Options.MetadataAddress, new OpenIdConnectConfigurationRetriever(),
                                                                                                         new HttpDocumentRetriever(Options.Backchannel)
                    {
                        RequireHttps = Options.RequireHttpsMetadata
                    });
                }
            }

            if (Options.ConfigurationManager == null)
            {
                throw new InvalidOperationException("Provide Authority, MetadataAddress, Configuration, or ConfigurationManager to OpenIdConnectAuthenticationOptions");
            }
        }
Example #39
0
 public Middleware(OwinMiddleware next, IAppBuilder app)
     : base(next)
 {
     _logger = app.CreateLogger <Middleware>();
 }
Example #40
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger("Katana.Sandbox.WebServer");

            logger.WriteInformation("Application Started");

            app.Use(async (context, next) =>
            {
                context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Request.Method, context.Request.PathBase, context.Request.Path);
                await next();
                context.Get<TextWriter>("host.TraceOutput").WriteLine("{0} {1}{2}", context.Response.StatusCode, context.Request.PathBase, context.Request.Path);
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Application",
                // LoginPath = new PathString("/Account/Login"),
            });

            app.SetDefaultSignInAsAuthenticationType("External");

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "External",
                AuthenticationMode = AuthenticationMode.Active,
                CookieName = CookieAuthenticationDefaults.CookiePrefix + "External",
                ExpireTimeSpan = TimeSpan.FromMinutes(5),
            });

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId = "454990987951096",
                AppSecret = "ca7cbddf944f91f23c1ed776f265478e",
                // Scope = "email user_birthday user_website"
            });

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "1033034290282-6h0n78feiepoltpqkmsrqh1ngmeh4co7.apps.googleusercontent.com",
                ClientSecret = "6l7lHh-B0_awzoTrlTGWh7km",
            });

            app.UseTwitterAuthentication("6XaCTaLbMqfj6ww3zvZ5g", "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI");

            app.UseMicrosoftAccountAuthentication("000000004C0EA787", "QZde5m5HHZPxdieV0lOy7bBVTbVqR9Ju");

            // app.UseAspNetAuthSession();
            /*
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                SessionStore = new InMemoryAuthSessionStore()
            });
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            */
            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
            {
                Wtrealm = "http://Katana.Sandbox.WebServer",
                MetadataAddress = "https://login.windows.net/cdc690f9-b6b8-4023-813a-bae7143d1f87/FederationMetadata/2007-06/FederationMetadata.xml",
            });
            /*
            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions()
            {
                // Change vdir to http://localhost:63786/
                // User [email protected]
                Authority = "https://login.windows-ppe.net/adale2etenant1.ccsctp.net",
                ClientId = "a81cf7a1-5a2d-4382-9f4b-0fa91a8992dc",
            });
            */
            /*
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
            });

            // CORS support
            app.Use(async (context, next) =>
            {
                IOwinRequest req = context.Request;
                IOwinResponse res = context.Response;
                // for auth2 token requests, and web api requests
                if (req.Path.StartsWithSegments(new PathString("/Token")) ||
                    req.Path.StartsWithSegments(new PathString("/api")))
                {
                    // if there is an origin header
                    var origin = req.Headers.Get("Origin");
                    if (!string.IsNullOrEmpty(origin))
                    {
                        // allow the cross-site request
                        res.Headers.Set("Access-Control-Allow-Origin", origin);
                    }

                    // if this is pre-flight request
                    if (req.Method == "OPTIONS")
                    {
                        // respond immediately with allowed request methods and headers
                        res.StatusCode = 200;
                        res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                        res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization");
                        // no further processing
                        return;
                    }
                }
                // continue executing pipeline
                await next();
            });

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath = new PathString("/Authorize"),
                TokenEndpointPath = new PathString("/Token"),
                ApplicationCanDisplayErrors = true,
#if DEBUG
                AllowInsecureHttp = true,
#endif
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientRedirectUri = ValidateClientRedirectUri,
                    OnValidateClientAuthentication = ValidateClientAuthentication,
                    OnGrantResourceOwnerCredentials = GrantResourceOwnerCredentials,
                },
                AuthorizationCodeProvider = new AuthenticationTokenProvider
                {
                    OnCreate = CreateAuthenticationCode,
                    OnReceive = ReceiveAuthenticationCode,
                },
                RefreshTokenProvider = new AuthenticationTokenProvider
                {
                    OnCreate = CreateRefreshToken,
                    OnReceive = ReceiveRefreshToken,
                }
            });
            /*
            app.Map("/Account/Login", map =>
            {
                map.Run(context =>
                {
                    // context.Authentication.Challenge("Google");
                    return Task.FromResult(0);
                });
            });
            */
            app.Use((context, next) =>
            {
                var user = context.Authentication.User;
                if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)
                {
                    context.Authentication.Challenge();
                    return Task.FromResult(0);
                }
                return next();
            });

            app.Run(async context =>
            {
                var response = context.Response;
                var user = context.Authentication.User;
                var identity = user.Identities.First();
                // var properties = result.Properties.Dictionary;

                response.ContentType = "application/json";
                response.Write("{\"Details\":[");
                foreach (var claim in identity.Claims)
                {
                    response.Write("{\"Name\":\"");
                    response.Write(claim.Type);
                    response.Write("\",\"Value\":\"");
                    response.Write(claim.Value);
                    response.Write("\",\"Issuer\":\"");
                    response.Write(claim.Issuer);
                    response.Write("\"},"); // TODO: No comma on the last one
                }
                response.Write("],\"Properties\":[");
                /*
                foreach (var pair in properties)
                {
                    response.Write("{\"Name\":\"");
                    response.Write(pair.Key);
                    response.Write("\",\"Value\":\"");
                    response.Write(pair.Value);
                    response.Write("\"},"); // TODO: No comma on the last one
                }*/
                response.Write("]}");
            });
        }
Example #41
0
 public MyCustomMiddleware(OwinMiddleware next, IAppBuilder app)
     : base(next)
 {
     _logger = app.CreateLogger<MyCustomMiddleware>();
 }
 public DotNetDoodleOAuthAuthorizationServerProvider(IAppBuilder app, IConfigurationManager configManager)
 {
     _configManager = configManager;
     _logger        = app.CreateLogger <DotNetDoodleOAuthAuthorizationServerProvider>();
 }
Example #43
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger("Katana.Sandbox.WebServer");

            logger.WriteInformation("Application Started");

            app.UseHandlerAsync(async (req, res, next) =>
            {
                req.TraceOutput.WriteLine("{0} {1}{2}", req.Method, req.PathBase, req.Path);
                await next();
                req.TraceOutput.WriteLine("{0} {1}{2}", res.StatusCode, req.PathBase, req.Path);
            });

            app.UseFormsAuthentication(new FormsAuthenticationOptions
            {
                AuthenticationType = "Application",
                AuthenticationMode = AuthenticationMode.Passive,
                LoginPath = "/Login",
                LogoutPath = "/Logout",
            });

            app.UseExternalSignInCookie();

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                SignInAsAuthenticationType = "External",
                AppId = "615948391767418",
                AppSecret = "c9b1fa6b68db835890ce469e0d98157f",
                // Scope = "email user_birthday user_website"
            });

            app.UseGoogleAuthentication();

            app.UseTwitterAuthentication("6XaCTaLbMqfj6ww3zvZ5g", "Il2eFzGIrYhz6BWjYhVXBPQSfZuS4xoHpSSyD9PI");

            app.UseMicrosoftAccountAuthentication("000000004C0EA787", "QZde5m5HHZPxdieV0lOy7bBVTbVqR9Ju");

            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
            {
            });

            // CORS support
            app.UseHandlerAsync(async (req, res, next) =>
            {
                // for auth2 token requests, and web api requests
                if (req.Path == "/Token" || req.Path.StartsWith("/api/"))
                {
                    // if there is an origin header
                    var origin = req.GetHeader("Origin");
                    if (!string.IsNullOrEmpty(origin))
                    {
                        // allow the cross-site request
                        res.AddHeader("Access-Control-Allow-Origin", origin);
                    }

                    // if this is pre-flight request
                    if (req.Method == "OPTIONS")
                    {
                        // respond immediately with allowed request methods and headers
                        res.StatusCode = 200;
                        res.AddHeaderJoined("Access-Control-Allow-Methods", "GET", "POST");
                        res.AddHeaderJoined("Access-Control-Allow-Headers", "authorization");
                        // no further processing
                        return;
                    }
                }
                // continue executing pipeline
                await next();
            });

            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath = "/Authorize",
                TokenEndpointPath = "/Token",
                Provider = new OAuthAuthorizationServerProvider
                {
                    OnValidateClientCredentials = OnValidateClientCredentials,
                    OnValidateResourceOwnerCredentials = OnValidateResourceOwnerCredentials,
                },
            });

            var config = new HttpConfiguration();
            config.Routes.MapHttpRoute("Default", "api/{controller}");
            app.UseWebApi(config);
        }
Example #44
0
 public ElmoMiddleware(OwinMiddleware next, IAppBuilder app, IErrorLog errorLog)
     : base(next)
 {
     this.errorLog = errorLog;
     logger = app.CreateLogger<ElmoMiddleware>();
 }
 public ContainerMiddleware(AppFunc nextFunc, IAppBuilder app)
 {
     _nextFunc = nextFunc;
     _app = app;
     _logger = app.CreateLogger<ContainerMiddleware>();
 }
Example #46
0
 public LogRequestMiddleware(OwinMiddleware next, IAppBuilder app, string label)
     : base(next)
 {
     _logger = app.CreateLogger(label);
     _timer  = new Stopwatch();
 }
 public SiteMapAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, CookieAuthenticationOptions options)
     : base(next, options)
 {
     _logger = app.CreateLogger <SiteMapAuthenticationHandler>();
 }