public override void Configure(IAppBuilder app)
        {
            if (String.IsNullOrEmpty(FederationSettings.MetadataAddress))
            {
                throw new ArgumentException("Missing federation declaration in config", "FederationMetadataAddress");
            }

            if (String.IsNullOrEmpty(FederationSettings.Realm))
            {
                throw new ArgumentException("Missing federation declaration in config", "FederationRealm");

            }

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                MetadataAddress = FederationSettings.MetadataAddress,
                Wtrealm = FederationSettings.Realm,
                Notifications = new WsFederationAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (context) =>
                    {
                        if (context.OwinContext.Response.StatusCode == (int)HttpStatusCode.Unauthorized && context.Request.Headers.ContainsKey("AuthNoRedirect"))
                        {
                            context.HandleResponse();
                        }

                        return Task.FromResult(0);
                    }
                }
            });
        }
Example #2
0
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

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

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                MetadataAddress = String.Format("https://{0}/wsfed/{1}/FederationMetadata/2007-06/FederationMetadata.xml", 
                    ConfigurationManager.AppSettings["auth0:Domain"], 
                    ConfigurationManager.AppSettings["auth0:ClientId"]),
                Wtrealm = "urn:" + ConfigurationManager.AppSettings["auth0:ApplicationName"],
                Notifications = new WsFederationAuthenticationNotifications
                {
                    SecurityTokenValidated = notification =>
                    {
                        notification.AuthenticationTicket.Identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", "Auth0"));
                        return Task.FromResult(true);
                    }
                }
            });
        }
        public void ConfigureAuth(IAppBuilder app, IConfigurationProvider configProvider)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            // Primary authentication method for web site to Azure AD via the WsFederation below
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            string federationMetadataAddress = configProvider.GetConfigurationSettingValue("ida.FederationMetadataAddress");
            string federationRealm = configProvider.GetConfigurationSettingValue("ida.FederationRealm");

            if (string.IsNullOrEmpty(federationMetadataAddress) || string.IsNullOrEmpty(federationRealm))
            {
                throw new ApplicationException("Config issue: Unable to load required federation values from web.config or other configuration source.");
            }

            // check for default values that will cause app to fail to startup with an unhelpful 404 exception
            if (federationMetadataAddress.StartsWith("-- ", StringComparison.Ordinal) ||
                federationRealm.StartsWith("-- ", StringComparison.Ordinal))
            {
                throw new ApplicationException("Config issue: Default federation values from web.config need to be overridden or replaced.");
            }

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = federationMetadataAddress,
                    Wtrealm = federationRealm
                });

            string aadTenant = configProvider.GetConfigurationSettingValue("ida.AADTenant");
            string aadAudience = configProvider.GetConfigurationSettingValue("ida.AADAudience");

            if (string.IsNullOrEmpty(aadTenant) || string.IsNullOrEmpty(aadAudience))
            {
                throw new ApplicationException("Config issue: Unable to load required AAD values from web.config or other configuration source.");
            }

            // check for default values that will cause failure
            if (aadTenant.StartsWith("-- ", StringComparison.Ordinal) ||
                aadAudience.StartsWith("-- ", StringComparison.Ordinal))
            {
                throw new ApplicationException("Config issue: Default AAD values from web.config need to be overridden or replaced.");
            }

            // Fallback authentication method to allow "Authorization: Bearer <token>" in the header for WebAPI calls
            app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                {
                    Tenant = aadTenant,
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudience = aadAudience,
                        RoleClaimType = "http://schemas.microsoft.com/identity/claims/scope" // Used to unwrap token roles and provide them to [Authorize(Roles="")] attributes
                    }
                });
        }
        public void ConfigureWsFederationAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                AuthenticationType = FedAuth,
                Wtrealm = ConfigurationManager.AppSettings["app:URI"],
                MetadataAddress = ConfigurationManager.AppSettings["wsFederation:MetadataEndpoint"],
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Wtrealm = realm,
                    MetadataAddress = adfsMetadata
                });
        }
        private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var wsFederation = new WsFederationAuthenticationOptions
            {
                AuthenticationType = "windows",
                Caption = "Windows",
                SignInAsAuthenticationType = signInAsType,

                MetadataAddress = "https://localhost:44333/windows",
                Wtrealm = "urn:idsrv3"
            };
            app.UseWsFederationAuthentication(wsFederation);
        }
 public static void ConfigureAdditionalIdentityProviders(IAppBuilder app, string signInAsType)
 {
     var windowsAuthentication = new WsFederationAuthenticationOptions
     {
         AuthenticationType = "windows",
         Caption = "Windows",
         SignInAsAuthenticationType = signInAsType,
         MetadataAddress = GlobalConfiguration.WinAdMetadataUri.ToString(),
         Wtrealm = "urn:idsrv3",
         Wreply = $"{GlobalConfiguration.AuthorityRoute}/callback",
         Notifications = GetWsFedAuthNotifications()
     };
     app.UseWsFederationAuthentication(windowsAuthentication);
 }
Example #8
0
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = "http://localhost:29702/FederationMetadata",
                    Wtrealm = "urn:SupaDoopaRealm",
                    Wreply             = "http://localhost:16635/"
                }
            );
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                MetadataAddress = MVC_Owin_WsFederation.Configuration.CFS_METADATA,
                Wtrealm = MVC_Owin_WsFederation.Configuration.CFS_RP_REALM,

                SignInAsAuthenticationType = "Cookies"
            });
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "Cookies"
            });

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
                {
                    MetadataAddress = Constants.BaseAddress + "/wsfed/metadata",
                    Wtrealm = "urn:owinrp",

                    SignInAsAuthenticationType = "Cookies"
                });
        }
Example #11
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = UserAccountType.External,
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Passive,
            });

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = UserAccountType.Twitter,
                AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
            });

            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
                    AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active
                });

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = ConfigurationManager.AppSettings["FederationMetadataAddress"],
                    Wtrealm = ConfigurationManager.AppSettings["FederationWtrealm"],
                    SignInAsAuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
                });

            app.UseTwitterAuthentication(
                new TwitterAuthenticationOptions
               {
                   ConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"],
                   ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                   Provider = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationProvider
                   {
                       OnAuthenticated = async context =>
                       {
                           context.Identity.AddClaim(new Claim("urn:twitter:accesstoken", context.AccessToken));
                           context.Identity.AddClaim(new Claim("urn:twitter:accesstokensecret", context.AccessTokenSecret));
                       }
                   },
                   SignInAsAuthenticationType = UserAccountType.External
               });
        }
Example #12
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    AuthenticationType =
                       CookieAuthenticationDefaults.AuthenticationType
                });
            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = "https://login.microsoftonline.com/2c2a63d4-465c-464d-b7f5-6ccfd0dce5b8/federationmetadata/2007-06/federationmetadata.xml",
                    Wtrealm = "https://testService.local/",
                });

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
        }
Example #13
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var notifications = new WsFederationAuthenticationNotifications
            {
                SecurityTokenReceived = (context) =>
                {
                    Debug.WriteLine("SecurityTokenReceived");
                    return Task.CompletedTask;
                },

                AuthenticationFailed = (context) =>
                {
                    Debug.WriteLine("AuthenticationFailed");
                    return Task.CompletedTask;
                },

                MessageReceived = (context) =>
                {
                    Debug.WriteLine("MessageReceived");
                    return Task.CompletedTask;
                },

                RedirectToIdentityProvider = (context) =>
                {
                    Debug.WriteLine("RedirectToIdentityProvider");
                    return Task.CompletedTask;
                },

                SecurityTokenValidated = (context) =>
                {
                    Debug.WriteLine("SecurityTokenValidated");
                    return Task.CompletedTask;
                }
            };

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Notifications = notifications,
                    Wtrealm = _realm,
                    MetadataAddress = _adfsMetadata
                });
        }
        public void Configuration(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
            });

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                MetadataAddress = IdentityUrl + "/wsfed/metadata",
                Wtrealm = ServerUrl,
                SignOutWreply = ServerUrl,
                SignInAsAuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
                UseTokenLifetime = false,
                Notifications = new WsFederationAuthenticationNotifications
                {
                    RedirectToIdentityProvider = ctx =>
                    {
                        if (ctx.OwinContext.Response.StatusCode == 401 &&
                             ctx.OwinContext.Authentication.User.Identity.IsAuthenticated)
                        {
                            ctx.OwinContext.Response.StatusCode = 403;
                            ctx.HandleResponse();
                        }
                        return Task.FromResult(0);
                    },
                    SecurityTokenValidated = ctx =>
                    {
                        //ctx.AuthenticationTicket.Properties.IsPersistent = true; //Always False. Will remember when closing browser, but should only happen when user ticks Remember Me
                        var isPersistent = ctx.AuthenticationTicket.Properties.IsPersistent;//Should vary based on remember me-checkbox? 

                        var redirectUri = new Uri(ctx.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);
                        if (redirectUri.IsAbsoluteUri)
                            ctx.AuthenticationTicket.Properties.RedirectUri = redirectUri.PathAndQuery;

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

            app.UseStageMarker(PipelineStage.Authenticate);

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
        }
        public void Configuration(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions {AuthenticationType = "cookies"});

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
            {
                Wtrealm = "urn:encryptedrealmV2",
                MetadataAddress = "https://localhost:44388/wsfed/metadata",
                Wreply = "https://localhost:44344/",
                SignInAsAuthenticationType = "cookies",
                TokenValidationParameters = new TokenValidationParameters
                {
                    AuthenticationType = "cookies",
                    ClientDecryptionTokens =
                        new ReadOnlyCollection<SecurityToken>(new List<SecurityToken>
                        {
                            new X509SecurityToken(Cert.LoadEncrypting())
                        })
                }
            });
        }
Example #16
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.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.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            //app.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //    AuthenticationType = OpenIdConnectAuthenticationDefaults.AuthenticationType,
            //});

            ////app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            ////app.UseCookieAuthentication(new CookieAuthenticationOptions { });

            //app.UseOpenIdConnectAuthentication(
            //    new OpenIdConnectAuthenticationOptions
            //    {
            //        Client_Id = "TesteWebApi",
            //        Client_Secret = "P@ssw0rd",
            //        Authority = "https://pasteur",
            //    });

            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    AuthenticationType =
                       WsFederationAuthenticationDefaults.AuthenticationType
                });
            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = "https://pasteur/FederationMetadata/2007-06/FederationMetadata.xml",
                    Wtrealm = "urn:mvcjwtrp",
                });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Wtrealm = realm,
                    MetadataAddress = metadata,
                    Notifications = new WsFederationAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            context.Response.Redirect("Home/Error?message=" + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    }
                });
        }
         public void Configuration(IAppBuilder app)
         {
             // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=316888


             app.UseCookieAuthentication(new CookieAuthenticationOptions
             {
                 AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
             });
             app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions
             {
                 TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                 {
                     //UPDATE Bug has been confirmed that this is not working as intented.
                     // I will update this demo as more information is avalibe.
                     //ValidateIssuer  = false -> this causes IssuereValidator to not be run. 
                     IssuerValidator = (issuer, token) =>
                     {
                         return false; // it still sign in the user even though its false.

                         //     return DatabaseIssuerNameRegistry.ContainsTenant(issuer);

                     }
                 },
                 Wtrealm = "https://cvservice.s-innovations.net",
                 MetadataAddress = "https://login.windows.net/802626c6-0f5c-4293-a8f5-198ecd481fe3/FederationMetadata/2007-06/FederationMetadata.xml"
             });

             app.Map("/login", OwinControllers.Login);
             app.Map("/logout", OwinControllers.Logout);
             app.Map("/signup", OwinControllers.Signup);
             app.Map("/signup-callback", OwinControllers.SignupCallback);

             app.Map("/api/getAuthorizationUri", OwinControllers.GetAuthorizationUri);
             app.Map("/api/getUserInfo", OwinControllers.GetUserInfo);
             app.Map("/api/getAccessToken", OwinControllers.GetAccessToken);
             app.Map("/api/getStorageAccountInfo", OwinControllers.GetStorageAccountInfo);
             app.Map("/api/getStorageAccounts", OwinControllers.GetStorageAccounts);
         }
Example #19
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(DefaultAuthenticationTypes.ExternalCookie);

            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    CookieName = "Dragon.SecurityServer.Demo",
                    AuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                    AuthenticationMode = AuthenticationMode.Passive,
                });
            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = FederatedAuthentication.WSFederationAuthenticationModule.Issuer + "federationmetadata/2007-06/federationmetadata.xml",
                    Wtrealm = FederatedAuthentication.WSFederationAuthenticationModule.Realm,
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudiences = new[] { ConfigurationManager.AppSettings["WtRealm"], ConfigurationManager.AppSettings["WtRealm"].ToLower() },
                        ValidIssuer = ConfigurationManager.AppSettings["ValidIssuer"],
                    }
                });
        }
        public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType         = "Google",
                Caption                    = "Google",
                SignInAsAuthenticationType = signInAsType,

                ClientId     = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze"
            };

            app.UseGoogleAuthentication(google);

            var fb = new FacebookAuthenticationOptions
            {
                AuthenticationType         = "Facebook",
                Caption                    = "Facebook",
                SignInAsAuthenticationType = signInAsType,

                AppId     = "676607329068058",
                AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63"
            };

            app.UseFacebookAuthentication(fb);

            var twitter = new TwitterAuthenticationOptions
            {
                AuthenticationType         = "Twitter",
                Caption                    = "Twitter",
                SignInAsAuthenticationType = signInAsType,

                ConsumerKey    = "N8r8w7PIepwtZZwtH066kMlmq",
                ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM"
            };

            app.UseTwitterAuthentication(twitter);

            var aad = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType         = "aad",
                Caption                    = "Azure AD",
                SignInAsAuthenticationType = signInAsType,

                Authority   = "https://login.windows.net/4ca9cb4c-5e5f-4be9-b700-c532992a3705",
                ClientId    = "65bbbda8-8b85-4c9d-81e9-1502330aacba",
                RedirectUri = "https://localhost:44333/core/aadcb"
            };

            app.UseOpenIdConnectAuthentication(aad);

            var adfs = new WsFederationAuthenticationOptions
            {
                AuthenticationType         = "adfs",
                Caption                    = "ADFS",
                SignInAsAuthenticationType = signInAsType,
                CallbackPath               = new PathString("/core/adfs"),

                MetadataAddress = "https://adfs.leastprivilege.vm/federationmetadata/2007-06/federationmetadata.xml",
                Wtrealm         = "urn:idsrv3"
            };

            app.UseWsFederationAuthentication(adfs);

            var was = new WsFederationAuthenticationOptions
            {
                AuthenticationType         = "was",
                Caption                    = "Windows",
                SignInAsAuthenticationType = signInAsType,
                CallbackPath               = new PathString("/core/was"),

                MetadataAddress = "https://localhost:44350",
                Wtrealm         = "urn:idsrv3"
            };

            app.UseWsFederationAuthentication(was);
        }
Example #21
0
        public void Configuration(IAppBuilder app)
        {
            app.UseAbp();

            app.RegisterDataProtectionProvider();

            app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);


            //使应用程序可以使用 Cookie 来存储已登录用户的信息
            //UseCookieAuthentication方法告诉ASP.NET Identity如何用Cookie去标识已认证的用户,
            //  以及通过CookieAuthenticationOptions类指定的选项在哪儿。
            //  这里重要的部分是LoginPath属性,它指定了一个URL,这是未认证客户端请求内容时要重定向的地址。
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login")
            });


            //Use a cookie to temporarily store information about a user logging in with a third party login provider
            //使应用程序可以使用cookie方式来存储第三方认证的信息
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);


            //土牛:You can remove these lines if you don't like to use two factor auth (while it has no problem if you don't remove)
            //使应用程序能够临时存储时,他们正在核实在双因素身份验证过程的第二个因素用户信息。
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            //使应用程序能够记住第二次登录验证的因素,如电话或电子邮件。
            //一旦选中此选项,在登录过程中验证的第二个步骤将是你从登录的设备记住。
            //这是类似的,当你登录了rememberMe选项。
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);


            if (IsTrue("ExternalAuth.Facebook.IsEnabled"))
            {
                app.UseFacebookAuthentication(CreateFacebookAuthOptions());
            }

            if (IsTrue("ExternalAuth.Twitter.IsEnabled"))
            {
                app.UseTwitterAuthentication(CreateTwitterAuthOptions());
            }

            if (IsTrue("ExternalAuth.Google.IsEnabled"))
            {
                app.UseGoogleAuthentication(CreateGoogleAuthOptions());
            }

            if (IsTrue("ExternalAuth.WsFederation.IsEnabled"))
            {
                app.UseWsFederationAuthentication(CreateWsFederationAuthOptions());
            }

            if (IsTrue("ExternalAuth.OpenId.IsEnabled"))
            {
                app.UseOpenIdConnectAuthentication(CreateOpenIdOptions());
            }

            app.MapSignalR();

            //Enable it to use HangFire dashboard (uncomment only if it's enabled in AbpZeroTemplateWebModule)
            //app.UseHangfireDashboard("/hangfire", new DashboardOptions
            //{
            //    Authorization = new[] { new AbpHangfireAuthorizationFilter(AppPermissions.Pages_Administration_HangfireDashboard) }
            //});
        }
Example #22
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app, Container container)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // 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
            {
                CookieName = "Dragon.SecurityServer.PermissionSTS",
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                ExpireTimeSpan = TimeSpan.FromMinutes(1),
                SlidingExpiration = false,
                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, AppMember>(
                        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);

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    AuthenticationType = "securityserver",
                    Wreply = ConfigurationManager.AppSettings["SecurityTokenServiceEndpointUrl"],
                    Wtrealm = ConfigurationManager.AppSettings["WtRealm"],
                    MetadataAddress = ConfigurationManager.AppSettings["WsFederationEndpointUrl"] + "/FederationMetadata/2007-06/FederationMetadata.xml",
                    TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidAudiences = new[] { ConfigurationManager.AppSettings["WtRealm"], ConfigurationManager.AppSettings["WtRealm"].ToLower() },
                        ValidIssuer = ConfigurationManager.AppSettings["ValidIssuer"]
                    },
                    UseTokenLifetime = false, // use cookie expiration time
                    Notifications = new WsFederationAuthenticationNotifications()
                    {
                        RedirectToIdentityProvider = (ctx) =>
                        {
                            //To avoid a redirect loop to the federation server send 403 when user is authenticated but does not have access
                            if (ctx.OwinContext.Response.StatusCode == 401 && ctx.OwinContext.Authentication.User.Identity.IsAuthenticated)
                            {
                                ctx.OwinContext.Response.StatusCode = 403;
                                ctx.HandleResponse();
                            }
                            // forward parameters from the client or previous STS'e
                            var parameterDictionary = new Dictionary<string, string>
                            {
                                {"serviceid", ""},
                                {"appid", ""},
                                {"userid", ""},
                            };
                            var parameters = new List<string> { "action", "data", "serviceid", "appid", "userid" };
                            foreach (var parameter in parameters)
                            {
                                var value = ctx.Request.Query[parameter];
                                if (value == null) continue;
                                ctx.ProtocolMessage.SetParameter(parameter, value);
                                parameterDictionary[parameter] = value;
                            }
                            var hmacParameters = HmacHelper.CreateHmacRequestParametersFromConfig(parameterDictionary, Consts.ProfileHmacSettingsPrefix);
                            foreach (var parameter in hmacParameters)
                            {
                                ctx.ProtocolMessage.SetParameter(parameter.Key, parameter.Value);
                            }
                            return Task.FromResult(0);
                        },
                        SecurityTokenValidated = (ctx) =>
                        {
                            var result = ctx.AuthenticationTicket;
                            if (result != null)
                            {
                                ctx.OwinContext.Authentication.SignOut("ExternalCookie");
                                var claims = result.Identity.Claims.ToList();
                                claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "External Account"));
                                var ci = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                                ctx.OwinContext.Authentication.SignIn(ci);
                            }
                            // var redirectUri = new Uri(ctx.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);
                            // var queryString = HttpUtility.ParseQueryString(redirectUri.Query);
                            // ctx.AuthenticationTicket.Properties.RedirectUri = queryString["wreply"];
                            return Task.FromResult(0);
                        }
                    }
                }
            );
            app.UseStageMarker(PipelineStage.Authenticate);

            /*
            //Remap logout to a federated logout
            app.Map(LogoutUrl, map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return Task.FromResult(0);
                });
            });

            //Tell antiforgery to use the name claim
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
             */

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #23
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 #24
0
        public void WsFederationAuthenticationConfiguration(IAppBuilder app)
        {
            app.UseStaticFiles();

            app.UseAuthSignInCookie();

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
                {
                    Wtrealm = "http://Automation1",
                    MetadataAddress = "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/federationmetadata/2007-06/federationmetadata.xml",
                    BackchannelHttpHandler = new WaadMetadataDocumentHandler(),
                    StateDataFormat = new CustomStateDataFormat(),
                    Notifications = new WsFederationAuthenticationNotifications()
                    {
                        MessageReceived = notification =>
                            {
                                Assert.True(notification.ProtocolMessage.Wctx.EndsWith("&mystate=customValue"), "wctx is not ending with &mystate=customValue");
                                notification.ProtocolMessage.Wctx = notification.ProtocolMessage.Wctx.Replace("&mystate=customValue", string.Empty);
                                notification.OwinContext.Set<bool>("MessageReceived", true);
                                return Task.FromResult(0);
                            },
                        RedirectToIdentityProvider = notification =>
                            {
                                if (notification.ProtocolMessage.IsSignInMessage)
                                {
                                    //Sign in message
                                    notification.ProtocolMessage.Wreply = notification.Request.Uri.AbsoluteUri + "signin-wsfed";
                                    notification.ProtocolMessage.Wctx += "&mystate=customValue";
                                }

                                return Task.FromResult(0);
                            },
                        SecurityTokenReceived = notification =>
                            {
                                notification.OwinContext.Set<bool>("SecurityTokenReceived", true);
                                return Task.FromResult(0);
                            },
                        SecurityTokenValidated = notification =>
                            {
                                var context = notification.AuthenticationTicket;

                                Assert.True(notification.OwinContext.Get<bool>("MessageReceived"), "MessageReceived notification not invoked");
                                Assert.True(notification.OwinContext.Get<bool>("SecurityTokenReceived"), "SecurityTokenReceived notification not invoked");

                                if (context.Identity != null)
                                {
                                    context.Identity.AddClaim(new Claim("ReturnEndpoint", "true"));
                                    context.Identity.AddClaim(new Claim("Authenticated", "true"));
                                    context.Identity.AddClaim(new Claim(context.Identity.RoleClaimType, "Guest", ClaimValueTypes.String));
                                }

                                return Task.FromResult(0);
                            },
                        AuthenticationFailed = notification =>
                            {
                                //Change the request url to something different and skip Wsfed. This new url will handle the request and let us know if this notification was invoked.
                                notification.OwinContext.Request.Path = new PathString("/AuthenticationFailed");
                                notification.SkipToNextMiddleware();
                                return Task.FromResult(0);
                            }
                    }
                });

            app.Map("/Logout", subApp =>
                {
                    subApp.Run(async context =>
                        {
                            if (context.Authentication.User.Identity.IsAuthenticated)
                            {
                                var authProperties = new AuthenticationProperties() { RedirectUri = context.Request.Uri.AbsoluteUri };
                                context.Authentication.SignOut(authProperties, WsFederationAuthenticationDefaults.AuthenticationType);
                                await context.Response.WriteAsync("Signing out...");
                            }
                            else
                            {
                                await context.Response.WriteAsync("SignedOut");
                            }
                        });
                });

            app.Map("/AuthenticationFailed", subApp =>
            {
                subApp.Run(async context =>
                {
                    await context.Response.WriteAsync("AuthenticationFailed");
                });
            });

            app.Map("/signout-wsfed", subApp =>
            {
                subApp.Run(async context =>
                {
                    await context.Response.WriteAsync("signout-wsfed");
                });
            });

            #region Utilities to set the metadata xml.
            app.Map("/metadata", subApp =>
            {
                subApp.Run(async context =>
                {
                    if (context.Request.Method == "POST")
                    {
                        var formParameters = await context.Request.ReadFormAsync();
                        metadataXml = formParameters.GetValues("metadata")[0];
                        await context.Response.WriteAsync("Received metadata");
                    }
                    else
                    {
                        context.Response.ContentType = "text/xml";
                        await context.Response.WriteAsync(metadataXml);
                    }
                });
            });
            #endregion

            app.UseExternalApplication(WsFederationAuthenticationDefaults.AuthenticationType);
        }
Example #25
0
        public void Configuration(IAppBuilder app)
        {
            // Registers the Kentico.Membership identity implementation
            app.CreatePerOwinContext(() => UserManager.Initialize(app, new UserManager(new UserStore(SiteContext.CurrentSiteName))));
            app.CreatePerOwinContext <SignInManager>(SignInManager.Create);

            // Configures the authentication cookie
            UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                // Fill in the name of your sign-in action and controller
                LoginPath = new PathString(urlHelper.Action("SignIn", "Account")),
                Provider  = new CookieAuthenticationProvider
                {
                    // Sets the return URL for the sign-in page redirect (fill in the name of your sign-in action and controller)
                    OnApplyRedirect = context => context.Response.Redirect(urlHelper.Action("SignIn", "Account")
                                                                           + new Uri(context.RedirectUri).Query)
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Registers a WS-Federation authentication service
            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
            {
                // Set any properties required by your authentication service
                MetadataAddress = "placeholder",     // Fill in the address of your service's WS-Federation metadata
                Wtrealm         = "",
                // When using external services, Passive authentication mode may help avoid redirect loops for 401 responses
                AuthenticationMode = AuthenticationMode.Passive
            });

            // Registers an OpenID Connect authentication service
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // Set any properties required by your authentication service
                ClientId           = "placeholder",
                ClientSecret       = "placeholder",
                Authority          = "placeholder",
                AuthenticationMode = AuthenticationMode.Passive
            });

            // Registers the Facebook authentication service
            app.UseFacebookAuthentication(
                new FacebookAuthenticationOptions
            {
                // Fill in the application ID and secret of your Facebook authentication application
                AppId     = "placeholder",
                AppSecret = "placeholder"
            });

            // Registers the Google authentication service
            app.UseGoogleAuthentication(
                new GoogleOAuth2AuthenticationOptions
            {
                // Fill in the client ID and secret of your Google authentication application
                ClientId     = "placeholder",
                ClientSecret = "placeholder"
            });
        }
Example #26
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 #27
0
        public void Configuration(IAppBuilder app)
        {
            //Enable cookie authentication, used to store the claims between requests
            app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType,
                //CookieManager = new SystemWebCookieManager()
            });

            //Enable federated authentication
            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
            {
                //Trusted URL to federation server meta data
                MetadataAddress = adfsMetadata,
                //Value of Wtreal must *exactly* match what is configured in the federation server
                Wtrealm = realm,
                //CallbackPath = new PathString("/SSO/LoginCallBack.aspx"),
                Notifications = new WsFederationAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (ctx) =>
                    {
                        //To avoid a redirect loop to the federation server send 403 when user is authenticated but does not have access
                        if (ctx.OwinContext.Response.StatusCode == 401 && ctx.OwinContext.Authentication.User.Identity.IsAuthenticated)
                        {
                            ctx.OwinContext.Response.StatusCode = 403;
                            ctx.HandleResponse();
                        }
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = (ctx) =>
                    {
                        //Ignore scheme/host name in redirect Uri to make sure a redirect to HTTPS does not redirect back to HTTP
                        var redirectUri = new Uri(ctx.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);

                        var userName = ctx.AuthenticationTicket.Identity.Claims.FirstOrDefault(p => p.Type == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress").Value;
                        var roles    = ctx.AuthenticationTicket.Identity.Claims.Where(p => p.Type == "https://adfs.bisnode.com/customclaims/groups").Select(p => p.Value);

                        if (redirectUri.IsAbsoluteUri)
                        {
                            ctx.AuthenticationTicket.Properties.RedirectUri = redirectUri.PathAndQuery;//"https://bisnodeintranet.local/SSO/LoginCallBack.aspx?userName="******"&roles=" + string.Join(",", roles) + "&ReturnUrl=" + redirectUri.PathAndQuery;// redirectUri.PathAndQuery;
                        }

                        AuthenticateUser(userName, roles);
                        return(Task.FromResult(0));
                    }
                }
            });

            //Add stage marker to make sure WsFederation runs on Authenticate (before URL Authorization and virtual roles)
            app.UseStageMarker(PipelineStage.Authenticate);

            //Remap logout to a federated logout
            app.Map(LogoutUrl, map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return(Task.FromResult(0));
                });
            });

            //Tell antiforgery to use the name claim
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
        }
Example #28
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("]}");
            });
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Wtrealm = realm,
                    MetadataAddress = adfsMetadata,
                    //custom code below to respond to notifications
                    Notifications = new WsFederationAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                       {
                           return Task.FromResult(0);
                       },
                        MessageReceived = context =>
                        {
                            return Task.FromResult(0);
                        },
                        RedirectToIdentityProvider = context =>
                        {
                            return Task.FromResult(0);
                        },
                        SecurityTokenReceived = context =>
                        {
                            return Task.FromResult(0);
                        },
                        SecurityTokenValidated = context =>
                        {

                            // Is this the point I can connect this authenticated user to the Identity database (roles) ?
                            /*
                            context.AuthenticationTicket.Identity.AddClaim(
                                        new Claim(ClaimTypes.Role, "ModelEditorRole")
                                        );
                            context.AuthenticationTicket.Identity.AddClaim(
                                        new Claim(ClaimTypes.Role, "SomeOtherRole")
                                        );
                                        */

                            string accountName = "";
                            string accountEmail = "";

                            foreach (var claim in context.AuthenticationTicket.Identity.Claims)
                            {
                                // instead of using "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"
                                // use enum
                                if (claim.Type == ClaimTypes.Upn)
                                {
                                     accountName = claim.Value;

                                    //do something? Connect to ASP.NET Identity database?
                                    // Can we "log in" an account in asp.net identity matching the user identity
                                    // e.g. [email protected]?
                                    // or do we add the account into the identity database, and only use to query roles
                                    // from the identity database ?
                                    // mainly, we want the current principal to pass an
                                    // [Authorize roles("roleX")] test
                                    // how about context.AuthenticationTicket.Identity.AddClaim() ?

                                }
                                else if (claim.Type == ClaimTypes.Email)
                                {
                                    accountEmail = claim.Value;
                                }
                                else if (claim.Type == ClaimTypes.Role)
                                {   // these would be roles coming from Active Directory, not the Identity database
                                    string roleName = claim.Value;
                                }

                            }

                            var db = new ApplicationDbContext();

                            //Add the user if necessary
                            var user = (from u in db.Users
                                        where u.UserName.ToLower() == accountName.ToLower()
                                        select u).FirstOrDefault();

                            //get the users roles and add to the claims
                            if (user == null)
                            {
                                var um = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(db));

                                var adminUser = new ApplicationUser()
                                {
                                    UserName = accountName,
                                    Email = accountEmail
                                };

                                var ir = um.Create(adminUser, "placeholder#123X"); // not sure how I feel about this... does it need a password?

                            }

                            var userRoles = (from u in db.Users
                                             from ur in u.Roles
                                             join r in db.Roles on ur.RoleId equals r.Id
                                             where u.UserName.ToLower() == accountName.ToLower()
                                             select new
                                             {
                                                 RoleName = r.Name

                                             }).ToList();

                            foreach (var role in userRoles)
                            {
                                context.AuthenticationTicket.Identity.AddClaim(
                                        new Claim(ClaimTypes.Role, role.RoleName));
                            }

                            return Task.FromResult(0);
                        }

                    }

                });
        }
        public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                Caption = "Google",
                SignInAsAuthenticationType = signInAsType,
                
                ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze"
            };
            app.UseGoogleAuthentication(google);

            var fb = new FacebookAuthenticationOptions
            {
                AuthenticationType = "Facebook",
                Caption = "Facebook",
                SignInAsAuthenticationType = signInAsType,
                
                AppId = "676607329068058",
                AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63"
            };
            app.UseFacebookAuthentication(fb);

            var twitter = new TwitterAuthenticationOptions
            {
                AuthenticationType = "Twitter",
                Caption = "Twitter",
                SignInAsAuthenticationType = signInAsType,
                
                ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq",
                ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM"
            };
            app.UseTwitterAuthentication(twitter);

            var adfs = new WsFederationAuthenticationOptions
            {
                AuthenticationType = "adfs",
                Caption = "ADFS",
                SignInAsAuthenticationType = signInAsType,

                MetadataAddress = "https://adfs.leastprivilege.vm/federationmetadata/2007-06/federationmetadata.xml",
                Wtrealm = "urn:idsrv3"
            };
            app.UseWsFederationAuthentication(adfs);

            var aad = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "aad",
                Caption = "Azure AD",
                SignInAsAuthenticationType = signInAsType,

                Authority = "https://login.windows.net/4ca9cb4c-5e5f-4be9-b700-c532992a3705",
                ClientId = "65bbbda8-8b85-4c9d-81e9-1502330aacba",
                RedirectUri = "https://localhost:44333/core/aadcb"
            };

            app.UseOpenIdConnectAuthentication(aad);
        }
        public static void ConfigureAuth(IAppBuilder app)
        {
            var config = Config;

            if (string.IsNullOrWhiteSpace(config.GenericAuthFailureMessage))
            {
                throw new ConfigurationErrorsException("Web configuration key \'authGenericAuthFailureMessage\' is missing or corrupted.");
            }

            LocalAuthEnabled           = config.EnableLocalAuth;
            GenericLoginFailureMessage = config.GenericAuthFailureMessage;

            if (config.EnableOpenAuth)
            {
                if (config.EnableLocalAD)
                {
                    if (string.IsNullOrWhiteSpace(config.LocalADGroup))
                    {
                        throw new ConfigurationErrorsException("Web configuration key \'authLocalADGroup\' is missing or corrupted.");
                    }
                    if (string.IsNullOrWhiteSpace(config.LocalADEmailDomain))
                    {
                        throw new ConfigurationErrorsException("Web configuration key \'authLocalADEmailDomain\' is missing or corrupted.");
                    }

                    LocalADGroup       = config.LocalADGroup;
                    LocalADEmailDomain = config.LocalADEmailDomain;

                    app.UseLocalADAuthentication(new LocalADAuthenticationOptions
                    {
                        AuthenticationType = LocalADAuthenticationType,
                        AuthenticationMode = AuthenticationMode.Passive
                    });
                }

                if (config.EnableAzureAD)
                {
                    if (string.IsNullOrWhiteSpace(config.AzureGroupId))
                    {
                        throw new ConfigurationErrorsException("Web configuration key \'authAzureGroupId\' is missing or corrupted.");
                    }

                    AzureADGroupId = config.AzureGroupId;

                    // Azure AD cookie
                    app.UseWsFederationAuthentication(
                        new WsFederationAuthenticationOptions
                    {
                        AuthenticationType = "Azure AD",
                        AuthenticationMode = AuthenticationMode.Passive,
                        MetadataAddress    = string.Format(
                            "https://login.windows.net/{0}/federationmetadata/2007-06/federationmetadata.xml",
                            config.AzureAppTenant),
                        Wtrealm = config.WebAppURL
                    });

                    // client (JavaScript) token
                    app.UseWindowsAzureActiveDirectoryBearerAuthentication(
                        new WindowsAzureActiveDirectoryBearerAuthenticationOptions
                    {
                        AuthenticationMode = AuthenticationMode.Passive,
#pragma warning disable 618
                        Audience = config.AzureAppClientID,
#pragma warning restore 618
                        Tenant = config.AzureAppTenant
                    });
                }

                if (config.EnableMS)
                {
                    app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions
                    {
                        AuthenticationMode = AuthenticationMode.Passive,
                        AuthenticationType = "Microsoft",
                        ClientId           = config.MSAppClientID,
                        ClientSecret       = config.MSAppClientSecret,
                    });
                }

                if (config.EnableGoogle)
                {
                    app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
                    {
                        AuthenticationMode = AuthenticationMode.Passive,
                        AuthenticationType = "Google",
                        ClientId           = config.GoogleAppClientID,
                        ClientSecret       = config.GoogleAppClientSecret,
                    });
                }

                //app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
                //app.UseWebApi(GlobalConfiguration.Configuration);
            }
        }
Example #32
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 #33
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app, Container container)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // 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
            {
                CookieName         = "Dragon.SecurityServer.PermissionSTS",
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                ExpireTimeSpan     = TimeSpan.FromMinutes(1),
                SlidingExpiration  = false,
                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, AppMember>(
                        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);

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
            {
                AuthenticationType        = "securityserver",
                Wreply                    = ConfigurationManager.AppSettings["SecurityTokenServiceEndpointUrl"],
                Wtrealm                   = ConfigurationManager.AppSettings["WtRealm"],
                MetadataAddress           = ConfigurationManager.AppSettings["WsFederationEndpointUrl"] + "/FederationMetadata/2007-06/FederationMetadata.xml",
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidAudiences = new[] { ConfigurationManager.AppSettings["WtRealm"], ConfigurationManager.AppSettings["WtRealm"].ToLower() },
                    ValidIssuer    = ConfigurationManager.AppSettings["ValidIssuer"]
                },
                UseTokenLifetime = false,     // use cookie expiration time
                Notifications    = new WsFederationAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (ctx) =>
                    {
                        //To avoid a redirect loop to the federation server send 403 when user is authenticated but does not have access
                        if (ctx.OwinContext.Response.StatusCode == 401 && ctx.OwinContext.Authentication.User.Identity.IsAuthenticated)
                        {
                            ctx.OwinContext.Response.StatusCode = 403;
                            ctx.HandleResponse();
                        }
                        // forward parameters from the client or previous STS'e
                        var parameterDictionary = new Dictionary <string, string>
                        {
                            { "serviceid", "" },
                            { "appid", "" },
                            { "userid", "" },
                        };
                        var parameters = new List <string> {
                            "action", "data", "serviceid", "appid", "userid"
                        };
                        foreach (var parameter in parameters)
                        {
                            var value = ctx.Request.Query[parameter];
                            if (value == null)
                            {
                                continue;
                            }
                            ctx.ProtocolMessage.SetParameter(parameter, value);
                            parameterDictionary[parameter] = value;
                        }
                        var hmacParameters = HmacHelper.CreateHmacRequestParametersFromConfig(parameterDictionary, Consts.ProfileHmacSettingsPrefix);
                        foreach (var parameter in hmacParameters)
                        {
                            ctx.ProtocolMessage.SetParameter(parameter.Key, parameter.Value);
                        }
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = (ctx) =>
                    {
                        var result = ctx.AuthenticationTicket;
                        if (result != null)
                        {
                            ctx.OwinContext.Authentication.SignOut("ExternalCookie");
                            var claims = result.Identity.Claims.ToList();
                            claims.Add(new Claim(ClaimTypes.AuthenticationMethod, "External Account"));
                            var ci = new ClaimsIdentity(claims, DefaultAuthenticationTypes.ApplicationCookie);
                            ctx.OwinContext.Authentication.SignIn(ci);
                        }
                        // var redirectUri = new Uri(ctx.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);
                        // var queryString = HttpUtility.ParseQueryString(redirectUri.Query);
                        // ctx.AuthenticationTicket.Properties.RedirectUri = queryString["wreply"];
                        return(Task.FromResult(0));
                    }
                }
            }
                );
            app.UseStageMarker(PipelineStage.Authenticate);

            /*
             * //Remap logout to a federated logout
             * app.Map(LogoutUrl, map =>
             * {
             *  map.Run(ctx =>
             *  {
             *      ctx.Authentication.SignOut();
             *      return Task.FromResult(0);
             *  });
             * });
             *
             * //Tell antiforgery to use the name claim
             * AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
             */

            // Uncomment the following lines to enable logging in with third party login providers
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #34
0
        public void Configuration(IAppBuilder app)
        {
            //// Configure the db context and user manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            //app.UseCookieAuthentication(new CookieAuthenticationOptions { });
            //app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            //app.UseOAuthImplicitAuthentication(new OAuthImplicitAuthenticationOptions
            //{
            //    AuthorizeEndpoint = new Uri("https://pasteur/issue/oauth2/authorize"),
            //    ClientId = "testewebapi",
            //    ClientSecret = "7/Cp5O/kqBfTQT5aW0kMWomlfDm6rXOViH7lI5tYehU=",
            //    Scope = "https://localhost:44301/",
            //    RedirectUri = new Uri("https://localhost:44301/"),
            //    ResponseType = "code",
            //    Issuer = "https://pasteur",
            //    AllowedAudience = "https://localhost:44301/",
            //    SymmetricSigningKey = "c8wfH2hkyI0nJE6p4KjaqCOK4iVWSbNsPwKHnNVlVhw="
            //});

            app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(
                new CookieAuthenticationOptions
                {
                    AuthenticationType =
                       WsFederationAuthenticationDefaults.AuthenticationType
                });
            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    MetadataAddress = "https://pasteur/FederationMetadata/2007-06/FederationMetadata.xml",
                    Wtrealm = "https://localhost:44301/",
                    BackchannelCertificateValidator = new EmptyCertificateValidator(),
                    SecurityTokenHandlers = new System.IdentityModel.Tokens.SecurityTokenHandlerCollection{
                        new SoapJwtSecurityTokenHandler()
                    },
                    //TokenValidationParameters = new TokenValidationParameters
                    //{
                    //    IssuerSigningToken = new BinarySecretSecurityToken(Convert.FromBase64String("c8wfH2hkyI0nJE6p4KjaqCOK4iVWSbNsPwKHnNVlVhw=")),
                    //},
                    Wreply = "https://localhost:44301/signin",
                    Notifications = new WsFederationAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            return Task.FromResult<object>(null);
                        },
                        MessageReceived = context =>
                        {
                            return Task.FromResult<object>(null);
                        },
                        RedirectToIdentityProvider = context =>
                        {
                            return Task.FromResult<object>(null);
                        },
                        SecurityTokenReceived = context =>
                        {
                            XmlDocument doc = new XmlDocument();
                            doc.LoadXml(context.SecurityToken);

                            context.SecurityToken = doc.InnerText;
                            context.OwinContext.Request.Headers.Add("Token", new string[] { DecodeUtil.Base64Decode(doc.InnerText) });
                            return Task.FromResult<object>(null);
                        },
                        SecurityTokenValidated = context =>
                        {
                            context.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim("urn:thinktecture:token", context.OwinContext.Request.Headers["Token"]));
                            return Task.FromResult<object>(null);
                        }
                    }
                });

            //app.UseOpenIdConnectAuthentication(
            //    new OpenIdConnectAuthenticationOptions
            //    {
            //        Client_Id = "TesteWebApi",
            //        Authority = "https://pasteur"
            //});
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);


            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
            {
                Wtrealm         = realm,
                MetadataAddress = adfsMetadata,
                //custom code below to respond to notifications
                Notifications = new WsFederationAuthenticationNotifications
                {
                    AuthenticationFailed = context =>
                    {
                        return(Task.FromResult(0));
                    },
                    MessageReceived = context =>
                    {
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = context =>
                    {
                        return(Task.FromResult(0));
                    },
                    SecurityTokenReceived = context =>
                    {
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = context =>
                    {
                        // Is this the point I can connect this authenticated user to the Identity database (roles) ?

                        /*
                         * context.AuthenticationTicket.Identity.AddClaim(
                         *          new Claim(ClaimTypes.Role, "ModelEditorRole")
                         *          );
                         * context.AuthenticationTicket.Identity.AddClaim(
                         *          new Claim(ClaimTypes.Role, "SomeOtherRole")
                         *          );
                         */

                        string accountName  = "";
                        string accountEmail = "";

                        foreach (var claim in context.AuthenticationTicket.Identity.Claims)
                        {
                            // instead of using "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn"
                            // use enum
                            if (claim.Type == ClaimTypes.Upn)
                            {
                                accountName = claim.Value;

                                //do something? Connect to ASP.NET Identity database?
                                // Can we "log in" an account in asp.net identity matching the user identity
                                // e.g. [email protected]?
                                // or do we add the account into the identity database, and only use to query roles
                                // from the identity database ?
                                // mainly, we want the current principal to pass an
                                // [Authorize roles("roleX")] test
                                // how about context.AuthenticationTicket.Identity.AddClaim() ?
                            }
                            else if (claim.Type == ClaimTypes.Email)
                            {
                                accountEmail = claim.Value;
                            }
                            else if (claim.Type == ClaimTypes.Role)
                            {       // these would be roles coming from Active Directory, not the Identity database
                                string roleName = claim.Value;
                            }
                        }

                        var db = new ApplicationDbContext();

                        //Add the user if necessary
                        var user = (from u in db.Users
                                    where u.UserName.ToLower() == accountName.ToLower()
                                    select u).FirstOrDefault();

                        //get the users roles and add to the claims
                        if (user == null)
                        {
                            var um = new UserManager <ApplicationUser>(new UserStore <ApplicationUser>(db));

                            var adminUser = new ApplicationUser()
                            {
                                UserName = accountName,
                                Email    = accountEmail
                            };

                            var ir = um.Create(adminUser, "placeholder#123X");     // not sure how I feel about this... does it need a password?
                        }

                        var userRoles = (from u in db.Users
                                         from ur in u.Roles
                                         join r in db.Roles on ur.RoleId equals r.Id
                                         where u.UserName.ToLower() == accountName.ToLower()
                                         select new
                        {
                            RoleName = r.Name
                        }).ToList();

                        foreach (var role in userRoles)
                        {
                            context.AuthenticationTicket.Identity.AddClaim(
                                new Claim(ClaimTypes.Role, role.RoleName));
                        }



                        return(Task.FromResult(0));
                    }
                }
            });
        }
Example #36
0
        private static void ConfigureWsFederationServer(IAppBuilder app, string signInAsType)
        {
            var windowsAuthentication = new WsFederationAuthenticationOptions
            {
                AuthenticationType = "windows",
                Caption = "Windows",
                SignInAsAuthenticationType = signInAsType,
                MetadataAddress = "https://localhost:44300/",
                Wtrealm = "urn:win"
            };

            app.UseWsFederationAuthentication(windowsAuthentication);
        }
Example #37
0
        public void Configuration(IAppBuilder app)
        {
            // Registers the Kentico.Membership identity implementation
            app.CreatePerOwinContext(() => KenticoUserManager.Initialize(app, new KenticoUserManager(new KenticoUserStore(SiteContext.CurrentSiteName))));
            app.CreatePerOwinContext <KenticoSignInManager>(KenticoSignInManager.Create);

            // Configures the authentication cookie
            UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                // Fill in the name of your sign-in action and controller
                LoginPath = new PathString(urlHelper.Action("SignIn", "Account")),
                Provider  = new CookieAuthenticationProvider
                {
                    // Sets the return URL for the sign-in page redirect (fill in the name of your sign-in action and controller)
                    OnApplyRedirect = context => context.Response.Redirect(urlHelper.Action("SignIn", "Account")
                                                                           + new Uri(context.RedirectUri).Query)
                }
            });

            // Registers the authentication cookie with the 'Essential' cookie level
            // Ensures that the cookie is preserved when changing a visitor's allowed cookie level below 'Visitor'
            CookieHelper.RegisterCookie(OWIN_COOKIE_PREFIX + DefaultAuthenticationTypes.ApplicationCookie, CookieLevel.Essential);

            // Uses a cookie to temporarily store information about users signing in via external authentication services
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Registers a WS-Federation authentication service
            app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
            {
                // Set any properties required by your authentication service
                MetadataAddress = "placeholder",     // Fill in the address of your service's WS-Federation metadata
                Wtrealm         = "",
                // When using external services, Passive authentication mode may help avoid redirect loops for 401 responses
                AuthenticationMode = AuthenticationMode.Passive
            });

            // Registers an OpenID Connect authentication service
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // Set any properties required by your authentication service
                ClientId           = "placeholder",
                ClientSecret       = "placeholder",
                Authority          = "https://placeholder",
                AuthenticationMode = AuthenticationMode.Passive
            });

            // Registers the Facebook authentication service
            app.UseFacebookAuthentication(
                new FacebookAuthenticationOptions
            {
                // Fill in the application ID and secret of your Facebook authentication application
                AppId     = "placeholder",
                AppSecret = "placeholder"
            });

            // Registers the Google authentication service
            app.UseGoogleAuthentication(
                new GoogleOAuth2AuthenticationOptions
            {
                // Fill in the client ID and secret of your Google authentication application
                ClientId     = "placeholder",
                ClientSecret = "placeholder"
            });
        }
Example #38
0
        internal void WsFederationAuthenticationConfiguration(IAppBuilder app)
        {
            app.UseStaticFiles();

            app.UseAuthSignInCookie();

            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
            {
                Wtrealm                = "http://Automation1",
                MetadataAddress        = "https://login.windows.net/4afbc689-805b-48cf-a24c-d4aa3248a248/federationmetadata/2007-06/federationmetadata.xml",
                BackchannelHttpHandler = new WaadMetadataDocumentHandler(),
                StateDataFormat        = new CustomStateDataFormat(),
                Notifications          = new WsFederationAuthenticationNotifications()
                {
                    MessageReceived = notification =>
                    {
                        Assert.True(notification.ProtocolMessage.Wctx.EndsWith("&mystate=customValue"), "wctx is not ending with &mystate=customValue");
                        notification.ProtocolMessage.Wctx = notification.ProtocolMessage.Wctx.Replace("&mystate=customValue", string.Empty);
                        notification.OwinContext.Set <bool>("MessageReceived", true);
                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = notification =>
                    {
                        if (notification.ProtocolMessage.IsSignInMessage)
                        {
                            //Sign in message
                            notification.ProtocolMessage.Wreply = notification.Request.Uri.AbsoluteUri + "signin-wsfed";
                            notification.ProtocolMessage.Wctx  += "&mystate=customValue";
                        }

                        return(Task.FromResult(0));
                    },
                    SecurityTokenReceived = notification =>
                    {
                        notification.OwinContext.Set <bool>("SecurityTokenReceived", true);
                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = notification =>
                    {
                        var context = notification.AuthenticationTicket;

                        Assert.True(notification.OwinContext.Get <bool>("MessageReceived"), "MessageReceived notification not invoked");
                        Assert.True(notification.OwinContext.Get <bool>("SecurityTokenReceived"), "SecurityTokenReceived notification not invoked");

                        if (context.Identity != null)
                        {
                            context.Identity.AddClaim(new Claim("ReturnEndpoint", "true"));
                            context.Identity.AddClaim(new Claim("Authenticated", "true"));
                            context.Identity.AddClaim(new Claim(context.Identity.RoleClaimType, "Guest", ClaimValueTypes.String));
                        }

                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = notification =>
                    {
                        //Change the request url to something different and skip Wsfed. This new url will handle the request and let us know if this notification was invoked.
                        notification.OwinContext.Request.Path = new PathString("/AuthenticationFailed");
                        notification.SkipToNextMiddleware();
                        return(Task.FromResult(0));
                    }
                }
            });

            app.Map("/Logout", subApp =>
            {
                subApp.Run(async context =>
                {
                    if (context.Authentication.User.Identity.IsAuthenticated)
                    {
                        var authProperties = new AuthenticationProperties()
                        {
                            RedirectUri = context.Request.Uri.AbsoluteUri
                        };
                        context.Authentication.SignOut(authProperties, WsFederationAuthenticationDefaults.AuthenticationType);
                        await context.Response.WriteAsync("Signing out...");
                    }
                    else
                    {
                        await context.Response.WriteAsync("SignedOut");
                    }
                });
            });

            app.Map("/AuthenticationFailed", subApp =>
            {
                subApp.Run(async context =>
                {
                    await context.Response.WriteAsync("AuthenticationFailed");
                });
            });

            app.Map("/signout-wsfed", subApp =>
            {
                subApp.Run(async context =>
                {
                    await context.Response.WriteAsync("signout-wsfed");
                });
            });

            #region Utilities to set the metadata xml.
            app.Map("/metadata", subApp =>
            {
                subApp.Run(async context =>
                {
                    if (context.Request.Method == "POST")
                    {
                        var formParameters = await context.Request.ReadFormAsync();
                        metadataXml        = formParameters.GetValues("metadata")[0];
                        await context.Response.WriteAsync("Received metadata");
                    }
                    else
                    {
                        context.Response.ContentType = "text/xml";
                        await context.Response.WriteAsync(metadataXml);
                    }
                });
            });
            #endregion

            app.UseExternalApplication(WsFederationAuthenticationDefaults.AuthenticationType);
        }
        /// <summary>
        /// Configuration method used by Microsoft.Owin to initialize owin process.
        /// </summary>
        /// <param name="app">The application.</param>
        public void Configuration(IAppBuilder app)
        {
            //Uncomment the line below if you have are only using the configure IRegistrar for authentication
            //app.SetDefaultSignInAsAuthenticationType(_registrar.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = _registrar.AuthenticationType
            });

            //Comment out the following if you are not using ADFS authenication down to
            app.SetDefaultSignInAsAuthenticationType(WsFederationAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType
            });

            //Enable federated authentication
            app.UseWsFederationAuthentication(new WsFederationAuthenticationOptions()
            {
                //Trusted URL to federation server meta data
                MetadataAddress = "https://devdc.dev.test/federationmetadata/2007-06/federationmetadata.xml",
                //Value of Wtreal must *exactly* match what is configured in the federation server
                Wtrealm = "https://commercesample:44333/",
                Notifications = new WsFederationAuthenticationNotifications()
                {
                    RedirectToIdentityProvider = (ctx) =>
                    {
                        //To avoid a redirect loop to the federation server send 403 when user is authenticated but does not have access
                        if (ctx.OwinContext.Response.StatusCode == 401 && ctx.OwinContext.Authentication.User.Identity.IsAuthenticated)
                        {
                            ctx.OwinContext.Response.StatusCode = 403;
                            ctx.HandleResponse();
                        }
                        return Task.FromResult(0);
                    },
                    SecurityTokenValidated = (ctx) =>
                    {
                        //Ignore scheme/host name in redirect Uri to make sure a redirect to HTTPS does not redirect back to HTTP
                        var redirectUri = new Uri(ctx.AuthenticationTicket.Properties.RedirectUri, UriKind.RelativeOrAbsolute);
                        if (redirectUri.IsAbsoluteUri)
                        {
                            ctx.AuthenticationTicket.Properties.RedirectUri = redirectUri.PathAndQuery;
                        }
                        //Sync user and the roles to EPiServer in the background
                        ServiceLocator.Current.GetInstance<SynchronizingUserService>().SynchronizeAsync(ctx.AuthenticationTicket.Identity);
                        return Task.FromResult(0);
                    },

                }
            });
            //End Comment out AFDS if you are not using

            //Always keep the following to properly setup virtual roles for principals, map the logout in backend function and create anti forgery key
            app.UseStageMarker(PipelineStage.Authenticate);
            app.Map(LogoutUrl, map =>
            {
                map.Run(ctx =>
                {
                    ctx.Authentication.SignOut();
                    return Task.FromResult(0);
                });
            });
            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Name;
        }
Example #40
0
        public void Configuration(IAppBuilder app)
        {
            // For twitter:
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            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()
                CookieManager = new SameSiteCookieManager()
            });

            // 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",
                Wreply          = "https://localhost:44318/",
            });

            app.UseOpenIdConnectAuthentication(new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationOptions()
            {
                // https://github.com/IdentityServer/IdentityServer4.Demo/blob/master/src/IdentityServer4Demo/Config.cs
                ClientId     = "hybrid",
                ClientSecret = "secret", // for code flow
                Authority    = "https://demo.identityserver.io/",
                RedirectUri  = "https://localhost:44318/signin-oidc",

                /*
                 * Authority = Environment.GetEnvironmentVariable("oidc:authority"),
                 * ClientId = Environment.GetEnvironmentVariable("oidc:clientid"),
                 * ClientSecret = Environment.GetEnvironmentVariable("oidc:clientsecret"),*/
                // CookieManager = new SystemWebCookieManager(),
                CookieManager = new SameSiteCookieManager(),
                //ResponseType = "code",
                //ResponseMode = "query",
                //SaveTokens = true,
                //Scope = "openid profile offline_access",
                //RedeemCode = true,
                //Notifications = new Microsoft.Owin.Security.OpenIdConnect.OpenIdConnectAuthenticationNotifications
                //{
                //    AuthorizationCodeReceived = async n =>
                //    {
                //        var _configuration = await n.Options.ConfigurationManager.GetConfigurationAsync(n.OwinContext.Request.CallCancelled);
                //        var requestMessage = new System.Net.Http.HttpRequestMessage(System.Net.Http.HttpMethod.Post, _configuration.TokenEndpoint);
                //        requestMessage.Content = new System.Net.Http.FormUrlEncodedContent(n.TokenEndpointRequest.Parameters);
                //        var responseMessage = await n.Options.Backchannel.SendAsync(requestMessage);
                //        responseMessage.EnsureSuccessStatusCode();
                //        var responseContent = await responseMessage.Content.ReadAsStringAsync();
                //        Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectMessage message = new Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectMessage(responseContent);

                //        n.HandleCodeRedemption(message);
                //    }
                //}
            });

            /*
             * 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");
            });
        }