Exemplo n.º 1
0
        // 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);
        }
Exemplo n.º 2
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);
            app.MapSignalR();

            // Check to see if we are running local and if we are set the cookie domain to nothing so authentication works correctly.
            string cookieDomain = ".jehovajireh.com";
            bool   isLocal      = HttpContext.Current.Request.IsLocal;

            if (isLocal)
            {
                cookieDomain = "";
            }

            // 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"),
                CookieDomain       = cookieDomain,
                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, User>(
                        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.UseOAuthBearerTokens(OAuthOptions);

            // Uncomment the following lines to enable logging in with third party login providers
            #region Microsoft
            var microsoftAuthenticationOptions = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["MsI"],
                ClientSecret = ConfigurationManager.AppSettings["MsS"],
                CallbackPath = new PathString("/signin-microsoft"),
                Provider     = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationProvider
                {
                    OnAuthenticated = async(context) =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken",
                                                                                   context.AccessToken));
                        var expiryDuration = context.ExpiresIn ?? new TimeSpan();
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:microsft:expires_in", DateTime.UtcNow.Add(expiryDuration).ToString(CultureInfo.InvariantCulture)));

                        // Add all other available claims
                        foreach (var claim in context.User)
                        {
                            var claimType  = string.Format("urn:microsoft:{0}", claim.Key);
                            var claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType,
                                                                                           claimValue, "XmlSchemaString", "Microsoft"));
                            }
                        }
                    }
                },
                Scope = { "wl.basic", "wl.emails", "wl.birthday", "wl.photos" }
            };

            app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions);
            #endregion

            //app.UseTwitterAuthentication(
            //   consumerKey: "",
            //   consumerSecret: "");
            #region Facebook
            var facebookAuthenticationOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
            {
                AppId              = ConfigurationManager.AppSettings["FaceI"],
                AppSecret          = ConfigurationManager.AppSettings["FaceS"],
                SendAppSecretProof = true,
                CallbackPath       = new PathString("/signin-facebook"),
                Provider           = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken",
                                                                                   context.AccessToken));
                        var expiryDuration = context.ExpiresIn ?? new TimeSpan();
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:expires_in", DateTime.UtcNow.Add(expiryDuration).ToString(CultureInfo.InvariantCulture)));

                        // Add all other available claims
                        foreach (var claim in context.User)
                        {
                            var claimType  = string.Format("urn:facebook:{0}", claim.Key);
                            var claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                            }
                        }

                        return(Task.FromResult(0));
                    }
                },
                BackchannelHttpHandler = new FacebookchannelHttpHandler()
            };

            app.UseFacebookAuthentication(facebookAuthenticationOptions);
            #endregion
            #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"));
                            }
                        }
                    }
                }
            };
            app.UseGoogleAuthentication(googleAuthenticationOptions);
            #endregion
            //Default Values
            try
            {
                createDefaultRolesandUsers();
            }
            catch (System.Exception ex)
            {
                Trace.WriteLine(ex);
            }
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            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
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Microsoft : Create application
            // https://account.live.com/developers/applications
            if (ConfigurationManager.AppSettings.Get("MicrosoftClientId").Length > 0)
            {
                var msaccountOptions = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationOptions()
                {
                    ClientId = ConfigurationManager.AppSettings.Get("MicrosoftClientId"),
                    ClientSecret = ConfigurationManager.AppSettings.Get("MicrosoftClientSecret"),
                    Provider = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationProvider()
                    {
                        OnAuthenticated = (context) =>
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim("urn:microsoftaccount:access_token", context.AccessToken, XmlSchemaString, "Microsoft"));
                                return Task.FromResult(0);
                            }
                    }
                };

                app.UseMicrosoftAccountAuthentication(msaccountOptions);
            }

            // Twitter : Create a new application
            // https://dev.twitter.com/apps
            if (ConfigurationManager.AppSettings.Get("TwitterConsumerKey").Length > 0)
            {
                var twitterOptions = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions()
                {
                    ConsumerKey = ConfigurationManager.AppSettings.Get("TwitterConsumerKey"),
                    ConsumerSecret = ConfigurationManager.AppSettings.Get("TwitterConsumerSecret"),
                    Provider = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationProvider()
                    {
                        OnAuthenticated = (context) =>
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken, XmlSchemaString, "Twitter"));
                                return Task.FromResult(0);
                            }
                    }
                };

                app.UseTwitterAuthentication(twitterOptions);
            }

            // Facebook : Create New App
            // https://dev.twitter.com/apps
            if (ConfigurationManager.AppSettings.Get("FacebookAppId").Length > 0)
            {
                var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
                {
                    AppId = ConfigurationManager.AppSettings.Get("FacebookAppId"),
                    AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
                    Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider()
                    {
                        OnAuthenticated = (context) =>
                            {
                                context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook"));
                                foreach (var x in context.User)
                                {
                                    var claimType = string.Format("urn:facebook:{0}", x.Key);
                                    string claimValue = x.Value.ToString();
                                    if (!context.Identity.HasClaim(claimType, claimValue))
                                        context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook"));

                                }
                                return Task.FromResult(0);
                            }
                    }

                };
                app.UseFacebookAuthentication(facebookOptions);
            }

            // Foursquare : Create a new app
            // https://foursquare.com/developers/apps
            if (ConfigurationManager.AppSettings.Get("FoursquareClientId").Length > 0)
            {
                var foursquareOptions = new Citrius.Owin.Security.Foursquare.FoursquareAuthenticationOptions()
                {
                    ClientId = ConfigurationManager.AppSettings.Get("FoursquareClientId"),
                    ClientSecret = ConfigurationManager.AppSettings.Get("FoursquareClientSecret"),
                    Provider = new Citrius.Owin.Security.Foursquare.FoursquareAuthenticationProvider()
                    {
                        OnAuthenticated = context =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:foursquare:access_token", context.AccessToken, XmlSchemaString, "Foursquare"));
                            //foreach (var x in context.User)
                            //{
                            //    var claimType = string.Format("urn:foursquare:{0}", x.Key);
                            //    string claimValue = x.Value.ToString();
                            //    if (!context.Identity.HasClaim(claimType, claimValue))
                            //        context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Foursquare"));
                            //}

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

                app.UseFoursquareAuthentication(foursquareOptions);

                //app.UseFoursquareAuthentication(
                //    clientId: ConfigurationManager.AppSettings.Get("FoursquareClientId"),
                //    clientSecret: ConfigurationManager.AppSettings.Get("FoursquareClientSecret"));

            }

            // Google : nothing to do here.
            app.UseGoogleAuthentication();
        }