Beispiel #1
0
        public static IApplicationBuilder UseMyGithubAuthentication(this IApplicationBuilder app)
        {
            var options = app.ApplicationServices.GetService <IOptions <MyIdentityOptions> >().Value;

            if (options.IsGithubAuthConfigured())
            {
                var githubOptions =
                    new GitHubAuthenticationOptions
                {
                    ClientId     = options.GithubClient,
                    ClientSecret = options.GithubSecret
                };

                app.UseGitHubAuthentication(githubOptions);
            }

            return(app);
        }
        public static IAppBuilder UseGitHubAuthentication(
            this IAppBuilder app,
            string clientId,
            string clientSecret)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            var option = new GitHubAuthenticationOptions(
                clientId,
                clientSecret)
            {
                SignInAsAuthenticationType = app.GetDefaultSignInAsAuthenticationType()
            };

            return(UseGitHubAuthentication(app, option));
        }
        /// <summary>
        /// Adds the <see cref="GitHubAuthenticationMiddleware"/> middleware to the specified
        /// <see cref="IApplicationBuilder"/>, which enables GitHub authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="configuration">An action delegate to configure the provided <see cref="GitHubAuthenticationOptions"/>.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseGitHubAuthentication(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action <GitHubAuthenticationOptions> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            var options = new GitHubAuthenticationOptions();

            configuration(options);

            return(app.UseMiddleware <GitHubAuthenticationMiddleware>(Options.Create(options)));
        }
        public void Configure(string name, GitHubAuthenticationOptions options)
        {
            if (!string.Equals(name, GitHubAuthenticationDefaults.AuthenticationScheme, StringComparison.Ordinal))
            {
                return;
            }

            if (!ValidSettings())
            {
                return;
            }

            options.ClientId     = _platoGitHubOptions.ClientId;
            options.ClientSecret = _platoGitHubOptions.ClientSecret;

            if (_platoGitHubOptions.CallbackPath.HasValue)
            {
                options.CallbackPath = _platoGitHubOptions.CallbackPath;
            }
        }
Beispiel #5
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Enables the application to remember the second login verification factor such as phone or email.
            // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from.
            // This is similar to the RememberMe option when you log in.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            #region Microsoft

            var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["MsI"],
                ClientSecret = ConfigurationManager.AppSettings["MsS"],
                Provider     = new MicrosoftAccountAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:microsoft:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft"));
                            }
                        }
                    }
                }
            };
            microsoftAuthenticationOptions.Scope.Add("wl.basic");
            microsoftAuthenticationOptions.Scope.Add("wl.emails");
            microsoftAuthenticationOptions.Scope.Add("wl.birthday");
            app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions);

            #endregion Microsoft

            #region Twitter
            var twitterAuthenticationOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TwtI"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwtS"],
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                    new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                }),
                Provider = new TwitterAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("TwitterAccessToken", context.AccessToken));
                        foreach (var claim in context.UserId)
                        {
                            var    claimType  = string.Format("urn:twitter:{0}", claim);
                            string claimValue = claim.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter"));
                            }
                        }
                    }
                }
            };
            app.UseTwitterAuthentication(twitterAuthenticationOptions);

            #endregion Twitter

            #region Facebook

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FaceI"],
                AppSecret = ConfigurationManager.AppSettings["FaceS"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                            }
                        }
                    }
                }
            };
            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            #endregion Facebook

            #region Google

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GglI"],
                ClientSecret = ConfigurationManager.AppSettings["GglS"],
                Provider     = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                            }
                        }
                    }
                }
            };
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);

            #endregion Google

            #region LinkedIn

            var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkI"],
                ClientSecret = ConfigurationManager.AppSettings["LinkS"],
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedInAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:linkedin:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn"));
                            }
                        }
                    }
                }
            };
            app.UseLinkedInAuthentication(linkedinAuthenticationOptions);

            #endregion LinkedIn

            #region GitHub

            var gitAuthanticationOptions = new GitHubAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GitI"],
                ClientSecret = ConfigurationManager.AppSettings["GitS"],
                Provider     = new GitHubAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GitHubAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:github:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "GitHub"));
                            }
                        }
                    }
                }
            };
            app.UseGitHubAuthentication(gitAuthanticationOptions);

            #endregion GitHub
        }
        public static AuthenticationBuilder AddGitHubAuthentication(this AuthenticationBuilder authenticationBuilder, GitHubAuthenticationOptions options)
        {
            authenticationBuilder.AddOAuth(GitHubAuthenticationOptions.DefaultAuthenticationScheme, GitHubAuthenticationOptions.DefaultDisplayName, x =>
            {
                x.CallbackPath = new Http.PathString("/signin-github");

                x.ClientId     = options.ClientId;
                x.ClientSecret = options.ClientSecret;

                x.CorrelationCookie.Name     = ".ch.";
                x.CorrelationCookie.SameSite = Http.SameSiteMode.Strict;

                x.AuthorizationEndpoint   = options.AuthorizationEndpoint;
                x.TokenEndpoint           = options.TokenEndpoint;
                x.UserInformationEndpoint = options.UserInformationEndpoint;

                x.ClaimsIssuer = GitHubAuthenticationOptions.DefaultClaimsIssuer;

                x.Events = GetOAuthEvents(options.UserInformationEndpoint);

                if (options.Scopes != null)
                {
                    foreach (var scope in options.Scopes)
                    {
                        x.Scope.Add(scope);
                    }
                }

                if (options.SignInScheme != null)
                {
                    x.SignInScheme = options.SignInScheme;
                }
            });

            return(authenticationBuilder);
        }
Beispiel #7
0
 private void SetGitHubAuthentication(GitHubAuthenticationOptions options)
 {
     options.ClientId     = "26060c9aef1a28c58919";
     options.ClientSecret = "6d8b44ae95253b4d00d1f66e082175a3b53c3480";
     options.CallbackPath = new PathString("/github/auth");
 }
 public void Configure(GitHubAuthenticationOptions options) =>
 Configure(GitHubAuthenticationDefaults.AuthenticationScheme, options);
Beispiel #9
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(DBContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            //use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie);
            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
                Provider             = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

            // Token Generation
            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            //Configure Google External Login
            googleAuthOptions = new GooglePlusAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GooglePlusClientId"],
                ClientSecret = ConfigurationManager.AppSettings["GooglePlusClientSecret"],
                Provider     = new GoogleAuthProvider(),
                CallbackPath = new PathString("/signin-googleplus")
            };
            // TODO uncomment to use G+ auth
            app.UseGooglePlusAuthentication(googleAuthOptions);

            string stripeClientId     = ConfigurationManager.AppSettings["StripeClientId"];
            string stripeClientSecret = ConfigurationManager.AppSettings["StripeClientSecret"];

            stripeAuthOptions = new StripeAuthenticationOptions()
            {
                ClientId     = stripeClientId,
                ClientSecret = stripeClientSecret,
                Provider     = new StripeAuthProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                        context.Identity.AddClaim(new Claim("urn:stripe:refreshToken", context.RefreshToken));
                    }
                },
                SignInAsAuthenticationType = Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie
            };
            app.UseStripeAuthentication(stripeAuthOptions);



            string linkedinApiKey = ConfigurationManager.AppSettings["LinkedInApiKey"];
            string linkedinSecret = ConfigurationManager.AppSettings["LinkedInSecret"];

            linkedinAuthOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = linkedinApiKey,
                ClientSecret = linkedinSecret,
                Provider     = new LinkedInAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };
            app.UseLinkedInAuthentication(linkedinAuthOptions);


            string githubClientId     = ConfigurationManager.AppSettings["GithubClientId"];
            string githubClientSecret = ConfigurationManager.AppSettings["GithubClientSecret"];

            githubAuthOptions = new GitHubAuthenticationOptions()
            {
                ClientId     = githubClientId,
                ClientSecret = githubClientSecret,
                Provider     = new GitHubAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseGitHubAuthentication(githubAuthOptions);

            string twitterConsumerKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"];
            string twitterConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"];

            twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = githubClientId,
                ConsumerSecret = githubClientSecret,
                Provider       = new TwitterAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseTwitterAuthentication(twitterAuthOptions);


            string stackexchangeClientId     = ConfigurationManager.AppSettings["StackExchangeClientId"];
            string stackexchangeClientSecret = ConfigurationManager.AppSettings["StackExchangeClientSecret"];
            string stackexchangeKey          = ConfigurationManager.AppSettings["StackExchangeKey"];

        #if DEBUG
            stackexchangeClientId     = ConfigurationManager.AppSettings["StackExchangeClientIdDEBUG"];
            stackexchangeClientSecret = ConfigurationManager.AppSettings["StackExchangeClientSecretDEBUG"];
            stackexchangeKey          = ConfigurationManager.AppSettings["StackExchangeKeyDEBUG"];
        #endif

            stackexchangeAuthOptions = new StackExchangeAuthenticationOptions()
            {
                ClientId     = stackexchangeClientId,
                ClientSecret = stackexchangeClientSecret,
                Key          = stackexchangeKey,
                Provider     = new StackExchangeAuthProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken));
                    }
                },
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie
            };

            app.UseStackExchangeAuthentication(stackexchangeAuthOptions);


            //Configure Facebook External Login
            //facebookAuthOptions = new FacebookAuthenticationOptions()
            //{
            //    AppId = "xxx",
            //    AppSecret = "xxx",
            //    Provider = new FacebookAuthProvider()
            //};
            //app.UseFacebookAuthentication(facebookAuthOptions);
        }
Beispiel #10
0
        //This method is inside App_Start/Startup.Auth.cs
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            #region Microsoft

            var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["MsI"],
                ClientSecret = ConfigurationManager.AppSettings["MsS"],
                Provider     = new MicrosoftAccountAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:microsoft:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft"));
                            }
                        }
                    }
                }
            };
            microsoftAuthenticationOptions.Scope.Add("wl.basic");
            microsoftAuthenticationOptions.Scope.Add("wl.emails");
            microsoftAuthenticationOptions.Scope.Add("wl.birthday");
            app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions);

            #endregion Microsoft

            #region Twitter
            var twitterAuthenticationOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TwtI"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwtS"],
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                    new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                }),
                Provider = new TwitterAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("TwitterAccessToken", context.AccessToken));
                        foreach (var claim in context.UserId)
                        {
                            var    claimType  = string.Format("urn:twitter:{0}", claim);
                            string claimValue = claim.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter"));
                            }
                        }
                    }
                }
            };
            app.UseTwitterAuthentication(twitterAuthenticationOptions);

            #endregion Twitter

            #region Facebook

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FaceI"],
                AppSecret = ConfigurationManager.AppSettings["FaceS"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                            }
                        }
                    }
                }
            };
            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            #endregion Facebook

            #region Google

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GglI"],
                ClientSecret = ConfigurationManager.AppSettings["GglS"],
                Provider     = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                            }
                        }
                    }
                }
            };
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);

            #endregion Google

            #region LinkedIn

            var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkI"],
                ClientSecret = ConfigurationManager.AppSettings["LinkS"],
                Provider     = new LinkedInAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedInAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:linkedin:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn"));
                            }
                        }
                    }
                }
            };
            app.UseLinkedInAuthentication(linkedinAuthenticationOptions);

            #endregion LinkedIn

            #region GitHub

            var gitAuthanticationOptions = new GitHubAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GitI"],
                ClientSecret = ConfigurationManager.AppSettings["GitS"],
                Provider     = new GitHubAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GitHubAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var    claimType  = string.Format("urn:github:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "GitHub"));
                            }
                        }
                    }
                }
            };
            app.UseGitHubAuthentication(gitAuthanticationOptions);

            #endregion GitHub
        }
        // Pour plus d’informations sur la configuration de l’authentification, rendez-vous sur http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configurer le contexte de base de données, le gestionnaire des utilisateurs et le gestionnaire des connexions pour utiliser une instance unique par demande
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            // [10000]
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);


            // Autoriser l’application à utiliser un cookie pour stocker des informations pour l’utilisateur connecté
            // et pour utiliser un cookie à des fins de stockage temporaire des informations sur la connexion utilisateur avec un fournisseur de connexion tiers
            // Configurer le cookie de connexion
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Permet à l'application de valider le timbre de sécurité quand l'utilisateur se connecte.
                    // Cette fonction de sécurité est utilisée quand vous changez un mot de passe ou ajoutez une connexion externe à votre compte.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                },
                //CookieName = ".YAFNET_Authentication"
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Permet à l'application de stocker temporairement les informations utilisateur lors de la vérification du second facteur dans le processus d'authentification à 2 facteurs.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Permet à l'application de mémoriser le second facteur de vérification de la connexion, un numéro de téléphone ou un e-mail par exemple.
            // Lorsque vous activez cette option, votre seconde étape de vérification pendant le processus de connexion est mémorisée sur le poste à partir duquel vous vous êtes connecté.
            // Ceci est similaire à l'option RememberMe quand vous vous connectez.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // - [10006] - ADD: Social network login
            // Enable logging with third party login providers
            const string XmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";
            ///
            /// MICROSOFT
            ///
            var microsoftProvider = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationProvider
            {
                OnAuthenticated = (context) =>
                {
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:microsoft:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Microsoft"));
                        }
                    }
                    return(System.Threading.Tasks.Task.FromResult(0));
                }
            };
            var mio = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationOptions
            {
                ClientId     = Utils.GetAppSetting("MicrosoftClientId"),
                ClientSecret = Utils.GetAppSetting("MicrosoftClientSecret"),
                CallbackPath = new PathString("/signin-microsoft"),
                Provider     = microsoftProvider,
            };

            mio.Scope.Add("wl.basic");
            mio.Scope.Add("wl.emails");
            mio.Scope.Add("wl.birthday");
            mio.Scope.Add("wl.photos");
            mio.Scope.Add("wl.postal_addresses");
            app.UseMicrosoftAccountAuthentication(mio);

            ///
            /// TWITTER
            ///
            app.UseTwitterAuthentication(new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions
            {
                ConsumerKey    = Utils.GetAppSetting("TwitterConsumerKey"),
                ConsumerSecret = Utils.GetAppSetting("TwitterConsumerSecret"),
            });

            ///
            /// FACEBOOK
            ///
            var facebookProvider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider
            {
                OnAuthenticated = (context) =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
                    //context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));
                        }
                    }
                    return(System.Threading.Tasks.Task.FromResult(0));
                }
            };
            var fao = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
            {
                AppId        = Utils.GetAppSetting("FaceBookAppId"),
                AppSecret    = Utils.GetAppSetting("FaceBookAppSecret"),
                Provider     = facebookProvider,
                CallbackPath = new PathString("/signin-facebook"),
            };

            fao.Scope.Add("public_profile");
            fao.Scope.Add("user_friends");
            fao.Scope.Add("email");
            //fao.Scope.Add("gender");
            fao.Scope.Add("user_birthday");
            ////fao.Scope.Add("first_name");
            ////fao.Scope.Add("last_name");
            fao.Scope.Add("user_likes");
            fao.Scope.Add("user_about_me");
            fao.Scope.Add("user_photos");
            app.UseFacebookAuthentication(fao);
            ///
            /// GOOGLE
            ///
            var googleProvider = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationProvider
            {
                OnAuthenticated = (context) =>
                {
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:google:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Google"));
                        }
                    }
                    return(System.Threading.Tasks.Task.FromResult(0));
                }
            };
            var goo = new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions
            {
                ClientId     = Utils.GetAppSetting("GoogleClientId"),
                ClientSecret = Utils.GetAppSetting("GoogleClientSecret"),
                CallbackPath = new PathString("/signin-google"),
                Provider     = googleProvider,
            };

            app.UseGoogleAuthentication(goo);

            ///
            /// GITHUB : [10026] ADD: Github for external login
            ///
            var githubProvider = new GitHubAuthenticationProvider
            {
                OnAuthenticated = (context) =>
                {
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:github:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "GitHub"));
                        }
                    }
                    return(System.Threading.Tasks.Task.FromResult(0));
                }
            };
            var git = new GitHubAuthenticationOptions
            {
                ClientId     = Utils.GetAppSetting("GitHubClientId"),
                ClientSecret = Utils.GetAppSetting("GitHubClientSecret"),
                Provider     = githubProvider,
            };

            //git.Scope.Add("avatar_url");
            //git.Scope.Add("user");
            //git.Scope.Add("email");
            //git.Scope.Add("repo");
            //git.Scope.Add("gist");
            app.UseGitHubAuthentication(git);
        }
Beispiel #12
0
 public static IApplicationBuilder UseGitHubAuthentication(
     [NotNull] this IApplicationBuilder app,
     [NotNull] GitHubAuthenticationOptions options)
 {
     return(app.UseMiddleware <GitHubAuthenticationMiddleware>(options));
 }
Beispiel #13
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
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions   = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath         = new PathString("/Token"),
                Provider                  = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath     = new PathString("/api/Authentication/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

            OAuthBearerOptions = new OAuthBearerAuthenticationOptions();

            app.UseOAuthAuthorizationServer(OAuthOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);
            app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // Enable the application to use bearer tokens to authenticate users
            //   app.UseOAuthBearerTokens(OAuthOptions);

            var options = new GitHubAuthenticationOptions
            {
                ClientId     = "920019fba9f40261f36b",
                ClientSecret = "32150e11d03f50b5d8a670b061d75f60277cf3f9",

                Provider = new GitHubAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        string accessToken = context.AccessToken;
                        string username    = context.UserName;
                        string email       = context.Email;
                    }
                }
            };

            // options.Scope.Clear();
            options.Scope.Add("user:email");
            options.Scope.Add("repo");
            options.Scope.Add("read:org");


            app.UseGitHubAuthentication(options);


            // 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 = ""
            //});
        }
Beispiel #14
0
        /// <summary>
        /// Creates a builder.
        /// </summary>
        /// <param name="authBuilder">The services.</param>
        /// <returns></returns>
        public static void AddIdentityServer4MicroServiceOAuths(this AuthenticationBuilder authBuilder)
        {
            #region MicrosoftAccount (/signin-microsoft)
            var microsoft_options = new MicrosoftAccountOptions();
            authBuilder.Services.AddSingleton(microsoft_options);
            authBuilder.AddMicrosoftAccount(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(MicrosoftAccountOptions), microsoft_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion

            #region Google (/signin-google)
            var google_options = new GoogleOptions();
            authBuilder.Services.AddSingleton(google_options);
            authBuilder.AddGoogle(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(GoogleOptions), google_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion

            #region Facebook (/signin-facebook)
            var facebook_options = new FacebookOptions();
            authBuilder.Services.AddSingleton(facebook_options);
            authBuilder.AddFacebook(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(FacebookOptions), facebook_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion

            #region GitHub (/signin-github)
            var github_options = new GitHubAuthenticationOptions();
            authBuilder.Services.AddSingleton(github_options);
            authBuilder.AddGitHub(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(GitHubAuthenticationOptions), github_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion

            #region QQ (/signin-qq)
            var qq_options = new QQAuthenticationOptions();
            authBuilder.Services.AddSingleton(qq_options);
            authBuilder.AddQQ(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(QQAuthenticationOptions), qq_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion

            #region Weibo (/signin-weibo)
            var weibo_options = new WeiboAuthenticationOptions();
            authBuilder.Services.AddSingleton(weibo_options);
            authBuilder.AddWeibo(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(WeiboAuthenticationOptions), weibo_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion

            #region Weixin (/signin-weixin)
            var weixin_options = new WeixinAuthenticationOptions();
            authBuilder.Services.AddSingleton(weixin_options);
            authBuilder.AddWeixin(x =>
            {
                x.ClientId     = unknow;
                x.ClientSecret = unknow;
                authBuilder.Services.Remove(new ServiceDescriptor(typeof(WeixinAuthenticationOptions), weixin_options));
                authBuilder.Services.AddSingleton(x);
            });
            #endregion
        }
Beispiel #15
0
        private void ConfigureOAuth(IAppBuilder app)
        {
            // Call the service to get its configuration back
            var provider = new MvcConfigurationProvider(ConfigurationManager.AppSettings);
            MvcConfiguration mvcConfiguration = provider.Load();

            var            configClient = new ConfigurationClient(mvcConfiguration.ServiceUrl);
            IConfiguration config       = configClient.GetConfiguration();

            var cookieOptions = new CookieAuthenticationOptions
            {
                LoginPath  = new PathString("/Authentication/Login"),
                CookieName = "SyringeOAuth"
            };

            app.UseCookieAuthentication(cookieOptions);

            // Only enable if there are credentials
            if (config.ContainsOAuthCredentials())
            {
                app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);
            }


            //
            // OAuth2 Integrations
            //
            if (!string.IsNullOrEmpty(config.OAuthConfiguration.GoogleAuthClientId) &&
                !string.IsNullOrEmpty(config.OAuthConfiguration.GoogleAuthClientSecret))
            {
                // Console: https://console.developers.google.com/home/dashboard
                // Found under API and credentials.
                app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
                {
                    ClientId     = config.OAuthConfiguration.GoogleAuthClientId,
                    ClientSecret = config.OAuthConfiguration.GoogleAuthClientSecret
                });
            }
            if (!string.IsNullOrEmpty(config.OAuthConfiguration.MicrosoftAuthClientId) &&
                !string.IsNullOrEmpty(config.OAuthConfiguration.MicrosoftAuthClientSecret))
            {
                // Console: https://account.live.com/developers/applications/
                // Make sure he 'redirecturl' is set to 'http://localhost:1980/Authentication/Noop' (or the domain being used), to match the CallbackPath
                app.UseMicrosoftAccountAuthentication(new MicrosoftAccountAuthenticationOptions()
                {
                    ClientId     = config.OAuthConfiguration.MicrosoftAuthClientId,
                    ClientSecret = config.OAuthConfiguration.MicrosoftAuthClientSecret,
                    CallbackPath = new PathString("/Authentication/Noop")
                });
            }
            if (!string.IsNullOrEmpty(config.OAuthConfiguration.GithubAuthClientId) &&
                !string.IsNullOrEmpty(config.OAuthConfiguration.GithubAuthClientSecret))
            {
                // Console:  https://github.com/settings/developers
                // Set the callback url in the Github console to the same as the homepage url.
                var githubConfig = new GitHubAuthenticationOptions()
                {
                    ClientId     = config.OAuthConfiguration.GithubAuthClientId,
                    ClientSecret = config.OAuthConfiguration.GithubAuthClientSecret,
                };

                if (config.OAuthConfiguration.ContainsGithubEnterpriseSettings())
                {
                    githubConfig.Endpoints = new GitHubAuthenticationOptions.GitHubAuthenticationEndpoints()
                    {
                        AuthorizationEndpoint = config.OAuthConfiguration.GithubEnterpriseAuthorizationEndpoint,
                        TokenEndpoint         = config.OAuthConfiguration.GithubEnterpriseTokenEndpoint,
                        UserInfoEndpoint      = config.OAuthConfiguration.GithubEnterpriseUserInfoEndpoint
                    };
                }

                app.UseGitHubAuthentication(githubConfig);
            }
        }
Beispiel #16
0
        public void Configuration(IAppBuilder app)
        {
            AuthSettings settings = new AuthSettings();

            #region Register Route Mappings
            PTVService.RegisterRouteMapping(app);
            #endregion Register Route Mappings

            #region Configure the Service instances, 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);
            #endregion Configure the Service instances, User manager and Signin manager to use a single instance per request

            #region Configure Owin to use Authentication Cookie(s) (default behaviour)
            CookieAuthenticationOptions cookieOptions = new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval : TimeSpan.FromMinutes(30),
                        regenerateIdentity : delegate(ApplicationUserManager manager, ApplicationUser user)
                    {
                        return(user.GenerateUserIdentityAsync(manager));
                    }
                        )
                }
            };
            if (string.IsNullOrEmpty(settings.LoginPath) == false)
            {
                cookieOptions.LoginPath = new PathString(settings.LoginPath);
            }
            if (settings.ExpireTimeSpan != null)
            {
                cookieOptions.ExpireTimeSpan = settings.ExpireTimeSpan.Value;
            }
            if (settings.SlidingExpiration != null)
            {
                cookieOptions.SlidingExpiration = settings.SlidingExpiration.Value;
            }
            if (string.IsNullOrEmpty(settings.CookieDomain) == false)
            {
                cookieOptions.CookieDomain = settings.CookieDomain;
            }
            if (settings.CookieHttpOnly != null)
            {
                cookieOptions.CookieHttpOnly = (settings.CookieHttpOnly ?? true);
            }                                                                                                          // NOTE: set to 'false' to allow javascript to send Cookie information (need to send Cookie information) through to remote CORS-enabled WCF services
            if (settings.CookieAlwaysSecure != null)
            {
                cookieOptions.CookieSecure = ((settings.CookieAlwaysSecure == null) ? CookieSecureOption.SameAsRequest : (settings.CookieAlwaysSecure == true) ? CookieSecureOption.Always : CookieSecureOption.Never);
            }
            // 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(cookieOptions);
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            if ((settings.EnableTwoFactorAuthenticationQ ?? false) == true)
            {
                // 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);
            }
            else
            {
            }
            #endregion Configure Owin to use Authentication Cookie(s) (default behaviour)

            #region Configure additional OAuth Authentication Providers
#if AUTH_GOOGLE
            if (string.IsNullOrEmpty(settings.Google_AppId) == false && string.IsNullOrEmpty(settings.Google_Secret) == false && string.IsNullOrEmpty(settings.Google_CallbackPath) == false)
            {
                GoogleOAuth2AuthenticationOptions options = new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = settings.Google_AppId,
                    ClientSecret = settings.Google_Secret,
                    Scope        = { "openid", "profile", "email" }, // , "https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/userinfo.email"
                    CallbackPath = new PathString(settings.Google_CallbackPath),
                    Provider     = new CustomGoogleOAuth2AuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomGoogleBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseGoogleAuthentication(options);
            }
#endif
#if AUTH_FACEBOOK
            if (string.IsNullOrEmpty(settings.Facebook_AppId) == false && string.IsNullOrEmpty(settings.Facebook_Secret) == false && string.IsNullOrEmpty(settings.Facebook_CallbackPath) == false)
            {
                FacebookAuthenticationOptions options = new FacebookAuthenticationOptions()
                {
                    AppId                      = settings.Facebook_AppId,
                    AppSecret                  = settings.Facebook_Secret,
                    Scope                      = { "email", "public_profile", }, //, "user_friends"
                    CallbackPath               = new PathString(settings.Facebook_CallbackPath),
                    Provider                   = new CustomFacebookAuthenticationProvider(),
                    BackchannelHttpHandler     = new CustomFacebookBackChannelHandler(),                                                                              //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    UserInformationEndpoint    = $@"https://graph.facebook.com/{settings.Facebook_ApiVersion}/me?fields=id,name,email,first_name,last_name,location", //$@"https://graph.facebook.com/me?fields=id,email,first_name,last_name", //,company
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseFacebookAuthentication(options);
            }
#endif
#if AUTH_MICROSOFT
            if (string.IsNullOrEmpty(settings.Microsoft_AppId) == false && string.IsNullOrEmpty(settings.Microsoft_Secret) == false && string.IsNullOrEmpty(settings.Microsoft_CallbackPath) == false)
            {
                MicrosoftAccountAuthenticationOptions options = new MicrosoftAccountAuthenticationOptions()
                {
                    ClientId     = settings.Microsoft_AppId,
                    ClientSecret = settings.Microsoft_Secret,
                    CallbackPath = new PathString(settings.Microsoft_CallbackPath),
                    Scope        = { "User.Read", }, // "wl.basic", "wl.emails"
                    Provider     = new CustomMicrosoftAccountAuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomMicrosoftBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseMicrosoftAccountAuthentication(options);
            }
#endif
#if AUTH_LINKEDIN
            if (string.IsNullOrEmpty(settings.LinkedIn_AppId) == false && string.IsNullOrEmpty(settings.LinkedIn_Secret) == false && string.IsNullOrEmpty(settings.LinkedIn_CallbackPath) == false)
            {
                LinkedInAuthenticationOptions options = new LinkedInAuthenticationOptions()
                {
                    ClientId     = settings.LinkedIn_AppId,
                    ClientSecret = settings.LinkedIn_Secret,
                    CallbackPath = new PathString(settings.LinkedIn_CallbackPath),
                    //Scope = { "r_basicprofile", "r_emailaddress", }, //Scope = (IList<string>)(settings.LinkedIn_Scope ?? new string[] { "r_basicprofile" }).ToList(),
                    Provider = new CustomLinkedInAuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomLinkedInBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseLinkedInAuthentication(options);
            }
#endif
#if AUTH_TWITTER
            if (string.IsNullOrEmpty(settings.Twitter_AppId) == false && string.IsNullOrEmpty(settings.Twitter_Secret) == false && string.IsNullOrEmpty(settings.Twitter_CallbackPath) == false)
            {
                TwitterAuthenticationOptions options = new TwitterAuthenticationOptions()
                {
                    ConsumerKey    = settings.Twitter_AppId,
                    ConsumerSecret = settings.Twitter_Secret,
                    CallbackPath   = new PathString(settings.Twitter_CallbackPath),
                    //Scope = { "read", "email", },
                    Provider = new CustomTwitterAuthenticationProvider(),
                    BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType      = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseTwitterAuthentication(options);
            }
#endif
#if AUTH_GITHUB
            if (string.IsNullOrEmpty(settings.GitHub_AppId) == false && string.IsNullOrEmpty(settings.GitHub_Secret) == false && string.IsNullOrEmpty(settings.GitHub_CallbackPath) == false)
            {
                GitHubAuthenticationOptions options = new GitHubAuthenticationOptions()
                {
                    ClientId     = settings.GitHub_AppId,
                    ClientSecret = settings.GitHub_Secret,
                    CallbackPath = new PathString(settings.GitHub_CallbackPath),
                    Scope        = { "user", },
                    Provider     = new CustomGitHubAuthenticationProvider(),
                    //BackchannelHttpHandler = new CustomGitHubBackChannelHandler(), //BackchannelCertificateValidator = GetTrustedCertificatesValidator(),
                    SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                };
                app.UseGitHubAuthentication(options);
            }
#endif
            #endregion Configure additional OAuth Authentication Providers
        }