Example #1
1
        public static void ConfigureAdditionalIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "client", //"767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "secret"  //"5fWcBT0udKY7_b6E3gEiJlze"
            };
            app.UseGoogleAuthentication(google);

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

            var twitter = new TwitterAuthenticationOptions
            {
                AuthenticationType = "Twitter",
                SignInAsAuthenticationType = signInAsType,
                ConsumerKey = "consumer",  //"N8r8w7PIepwtZZwtH066kMlmq",
                ConsumerSecret = "secret"  //"df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM"
            };
            app.UseTwitterAuthentication(twitter);
        }
        public static void ConfigureSocialIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleAuthenticationOptions
            {
                AuthenticationType = "Google",
                SignInAsAuthenticationType = signInAsType
            };
            app.UseGoogleAuthentication(google);

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

            var twitter = new TwitterAuthenticationOptions
            {
                AuthenticationType = "Twitter",
                SignInAsAuthenticationType = signInAsType,
                ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq",
                ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM"
            };
            app.UseTwitterAuthentication(twitter);
        }
Example #3
1
        public void ConfigureOAuth(IAppBuilder app)
        {
            //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.FromMinutes(30),
                Provider = new SimpleAuthorizationServerProvider(),
                RefreshTokenProvider = new SimpleRefreshTokenProvider()
            };

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

            //Configure Google External Login
            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = "xxxxxx",
                ClientSecret = "xxxxxx",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            //Configure Facebook External Login
            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId = System.Configuration.ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret = System.Configuration.ConfigurationManager.AppSettings["FacebookAppSecret"],
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);

            //Configure Twitter External Login
           twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerKey"],
                ConsumerSecret = System.Configuration.ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                Provider = new TwitterAuthProvider()
            };
           app.UseTwitterAuthentication(twitterAuthOptions);

           //Configure LinkedIn External Login
           linkedinAuthOptions = new LinkedInAuthenticationOptions()
           {

               ClientId = System.Configuration.ConfigurationManager.AppSettings["LinkedInClientId"],
               ClientSecret = System.Configuration.ConfigurationManager.AppSettings["LinkedInSecret"],
               Provider = new LinkedInAuthProvider()
           };
           app.UseLinkedInAuthentication(linkedinAuthOptions);

           

        }
        // Para obtener más información para configurar la autenticación, visite http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Permitir que la aplicación use una cookie para almacenar información para el usuario que inicia sesión
            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);

            // Quitar los comentarios de las siguientes líneas para habilitar el inicio de sesión con proveedores de inicio de sesión de terceros

            // Microsoft => https://account.live.com/developers/applications
            app.UseMicrosoftAccountAuthentication(
                clientId: "000000004C111F35",
                clientSecret: "deMeyaE3qw25PVxxH79ndrTfwyeVk9Ua");

            // Twitter => https://dev.twitter.com/
            app.UseTwitterAuthentication(
               consumerKey: "ZfAxJLtSy18Vc3ueOOA76w",
               consumerSecret: "EpEGdYKF2emLS6eouoPeiJe6tJi5C2pSOkBDnbUDKY");

            // Facebook => https://developers.facebook.com/apps/
            app.UseFacebookAuthentication(
               appId: "562262000476246",
               appSecret: "097b95d01c1f6942a3c08560c69a8848");

            app.UseGoogleAuthentication();
        }
Example #5
0
 private static void ProcessSiginOption(IAppBuilder app, SigininOptionConfig signinConfig)
 {
     switch (signinConfig.SigninOption)
     {
         case SigninOption.MicrosoftAccount:
             app.UseMicrosoftAccountAuthentication(
                 clientId: signinConfig.IdOrKey,
                 clientSecret: signinConfig.Secret);
             break;
         case SigninOption.Twitter:
             app.UseTwitterAuthentication(
                consumerKey: signinConfig.IdOrKey,
                consumerSecret: signinConfig.Secret);
             break;
         case SigninOption.Facebook:
             app.UseFacebookAuthentication(
                appId: signinConfig.IdOrKey,
                appSecret: signinConfig.Secret);
             break;
         case SigninOption.Google:
             app.UseGoogleAuthentication(
                 clientId: signinConfig.IdOrKey,
                 clientSecret: signinConfig.Secret);
             break;
         default:
             break;
     }
 }
        // 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);

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

            app.UseTwitterAuthentication(
               consumerKey: "lVAwXKGYmyt2xL8pdOyxLanMF",
               consumerSecret: "vMLRQy8vmyHK3XqAOxFyF5GdNYMakpkYJ9Bcw5c7BUVNFqcuRW");

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

            //app.UseGoogleAuthentication();
        }
        // 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/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

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

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

            app.UseTwitterAuthentication(
               new TwitterAuthenticationOptions
               {
                   ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                   ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"],
                   BackchannelCertificateValidator = new Microsoft.Owin.Security.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
                   })
               }
            );


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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #8
0
        // 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
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication( new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString( "/Account/Login" )
            } );
            app.UseExternalSignInCookie( DefaultAuthenticationTypes.ExternalCookie );

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

            app.UseTwitterAuthentication(
               consumerKey: "PqRSqRIrWw8EJty1Gat0ZA",
               consumerSecret: "gsElizO6qYGPA1RMApWdp1BpsmfvRYXXBWmd0hs8" );

            app.UseFacebookAuthentication(
               appId: "449783478408068",
               appSecret: "a058d3068f6b29bc0149e5987b9e823a" );

            app.UseGoogleAuthentication();
        }
Example #9
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(() => new DurandalAuthDbContext());
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            //Enable Cors support in the Web API. Should go before the activation of Bearer tokens
            //http://aspnetwebstack.codeplex.com/discussions/467315
            app.UseCors(CorsOptions.AllowAll);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Enable the application to use bearer tokens to authenticate users
            // Enabling 3 components:
            // 1. Authorization Server middleware. For creating the bearer tokens
            // 2. Application bearer token middleware. Will atuthenticate every request with Authorization : Bearer header
            // 3. External bearer token middleware. For external providers
            app.UseOAuthBearerTokens(OAuthOptions);

            app.UseMicrosoftAccountAuthentication(
                ConfigurationManager.AppSettings["MicrosoftKey"],
                ConfigurationManager.AppSettings["MicrosoftSecret"]);

            app.UseTwitterAuthentication(
                ConfigurationManager.AppSettings["TwitterKey"],
                ConfigurationManager.AppSettings["TwitterSecret"]);

            app.UseFacebookAuthentication(
                ConfigurationManager.AppSettings["FacebookKey"],
                ConfigurationManager.AppSettings["FacebookSecret"]);

            app.UseGoogleAuthentication();
        }
Example #10
0
        public void Configuration(IAppBuilder app)
        {
            app.UseOAuthBearerAuthentication(AccountController.OAuthBearerOptions);

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

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

            if (IsTrue("ExternalAuth.Google.IsEnabled"))
            {
                app.UseGoogleAuthentication(CreateGoogleAuthOptions());
            }
        }
Example #11
0
        // 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);

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

            app.UseTwitterAuthentication(
               consumerKey: "Pbdf6cD0RgZO6WZmg7OLg",
               consumerSecret: "ALZDj07Uc5lWETyxGqV1SEDUc6RgyPV110asSsR7PI");

            app.UseFacebookAuthentication(
               appId: "1412821768932410",
               appSecret: "108ba83ee8303a68ea5ab04226786fb3");

            app.UseGoogleAuthentication();
        }
        // For more information on configuring authentication, please visit http://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(WebsiteContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.  
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, Account>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            
            app.UseTwitterAuthentication(
               consumerKey: WebConfigurationManager.AppSettings["TwitterId"],
               consumerSecret: WebConfigurationManager.AppSettings["TwitterSecret"]);
            
            app.UseFacebookAuthentication(
               appId: WebConfigurationManager.AppSettings["FacebookId"],
               appSecret: WebConfigurationManager.AppSettings["FacebookSecret"]);
        }
        // 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
            // 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);

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

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

            app.UseTwitterAuthentication(
                consumerKey: "QBAhakLsIl794uEEAX8csF3tP",
                consumerSecret: "ML44lD3gjDWfF1VR2SRmYa8Ic0VPUEk9FwraEBs0iP3awfvKuS");

            app.UseFacebookAuthentication(
                appId: "523635924470241",
                appSecret: "ef29066fd82cb20e746b52c00c7e34a7");

            app.UseGoogleAuthentication(new Microsoft.Owin.Security.Google.GoogleOAuth2AuthenticationOptions() {   ClientId = "122905730574.apps.googleusercontent.com", ClientSecret = "AjLf5P2WiGXIQrKqeTBRifAr" });
        }
Example #14
0
        // 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);

            // 3rd party providers
            var microsoftAppId = ConfigurationManager.AppSettings["MicrosoftAppId"];
            var microsoftAppSecret = ConfigurationManager.AppSettings["MicrosoftAppSecret"];
            if (microsoftAppId != null && microsoftAppSecret != null)
                app.UseMicrosoftAccountAuthentication(microsoftAppId, microsoftAppSecret);

            var twitterAppId = ConfigurationManager.AppSettings["TwitterAppId"];
            var twitterAppSecret = ConfigurationManager.AppSettings["TwitterAppSecret"];
            if (twitterAppId != null && twitterAppSecret != null)
                app.UseTwitterAuthentication(twitterAppId, twitterAppSecret);

            var facebookAppId = ConfigurationManager.AppSettings["FacebookAppId"];
            var facebookAppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"];
            if (facebookAppId != null && facebookAppSecret != null)
                app.UseFacebookAuthentication(facebookAppId, facebookAppSecret);

            app.UseGoogleAuthentication();
        }
        // 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);

            app.UseTwitterAuthentication(
                new TwitterAuthenticationOptions()
                {
                    ConsumerKey = TwitterConsumerKey,
                    ConsumerSecret = TwitterConsumerSecret,
                    Provider = new TwitterAuthenticationProvider()
                    {
                        OnAuthenticated = async context =>
                        {
                            context.Identity.AddClaim(new Claim(TwitterAccessTokenClaimType, context.AccessToken));
                            context.Identity.AddClaim(new Claim(TwitterAccessTokenSecretClaimType, context.AccessTokenSecret));
                        }
                    }
                }
               );
        }
        // 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
            // 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, isPersistent: true);

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

            // Uncomment the following lines to enable logging in with third party login providers
            string microsoftClientId = ConfigurationManager.AppSettings["microsoft_clientid"];
            string microsoftClientSecret = ConfigurationManager.AppSettings["microsoft_clientsecret"];
            if (microsoftClientId != null && microsoftClientSecret != null)
            {
                app.UseMicrosoftAccountAuthentication(microsoftClientId, microsoftClientSecret);
            }

            string twitterConsumerKey = ConfigurationManager.AppSettings["twitter_consumerkey"];
            string twitterConsumerSecret = ConfigurationManager.AppSettings["twitter_consumersecret"];
            if (twitterConsumerKey != null && twitterConsumerSecret != null)
            {
                app.UseTwitterAuthentication(twitterConsumerKey, twitterConsumerSecret);
            }

            string fbAppId = ConfigurationManager.AppSettings["facebook_appid"];
            string fbAppSecret = ConfigurationManager.AppSettings["facebook_appsecret"];
            if (fbAppId != null && fbAppSecret != null)
            {
                app.UseFacebookAuthentication(fbAppId, fbAppSecret);
            }

            app.UseGoogleAuthentication();
        }
Example #17
0
        // 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
            // 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);

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

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

            app.UseTwitterAuthentication(
                consumerKey: OAuthConfiguration.TwitterAuthConsumerKey,
                consumerSecret: OAuthConfiguration.TwitterAuthConsumerSecret);

            app.UseFacebookAuthentication(
                appId: OAuthConfiguration.FacebookAuthAppId,
                appSecret: OAuthConfiguration.FacebookAuthAppSecret);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId = OAuthConfiguration.GoogleAuthClientId,
                ClientSecret = OAuthConfiguration.GoogleAuthClientSecret
            });
        }
Example #18
0
        // 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);

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

            app.UseTwitterAuthentication(
               consumerKey: "LHpUEuCYelGiT1zYJrHTDw",
               consumerSecret: "VZnwWxOfzFv9K9FOrfirz2fhD47wgSMo5m41zV3Has");

            app.UseFacebookAuthentication(
               appId: "207117879494713",
               appSecret: "a9496a24c4a27bb5b3ecbb9805306afc");

            app.UseGoogleAuthentication();
        }
Example #19
0
        // 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);

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

            app.UseTwitterAuthentication(
                new TwitterAuthenticationOptions
                {
                    ConsumerKey = ConfigurationManager.AppSettings["consumerKey"],
                    ConsumerSecret = ConfigurationManager.AppSettings["consumerSecret"],
                    Provider = new LinqToTwitterAuthenticationProvider()
                });

            //app.UseTwitterAuthentication(
            //   consumerKey: ConfigurationManager.AppSettings["consumerKey"],
            //   consumerSecret: ConfigurationManager.AppSettings["consumerSecret"]);

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

            //app.UseGoogleAuthentication();
        }
Example #20
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCors(new CorsOptions {PolicyProvider = new CustomOwinCorsPolicyProvider()});

            // 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);
            
            // Enable the application to use bearer tokens to authenticate users
            app.UseOAuthBearerTokens(OAuthOptions);

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

            app.UseTwitterAuthentication(
                consumerKey: ConfigurationManager.AppSettings.Get("OAuthTwitterKey"),
                consumerSecret: ConfigurationManager.AppSettings.Get("OAuthTwitterSecret"));

            app.UseFacebookAuthentication(
                appId: ConfigurationManager.AppSettings.Get("OAuthFacebookKey"),
                appSecret: ConfigurationManager.AppSettings.Get("OAuthFacebookSecret"));

            app.UseGoogleAuthentication();
        }
Example #21
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            // and also store information about a user logging in with a third party login provider.
            // This is required if your application allows users to login
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

            app.UseTwitterAuthentication(
               consumerKey: "PS2yoTd6vf2hcZbbofNUpTUo8",
               consumerSecret: "zxZR1fNgACENr8Q299ZCJcHt4I6K1S6aLxajXyNLI037XoPbUu");

            app.UseFacebookAuthentication(
               appId: "200010180162728",
               appSecret: "780b74301cc8b352137ba107649a3dc6");

            app.UseGoogleAuthentication();
        }
Example #22
0
        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("/Login/SignIn")
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure social authentication: Twitter
            var naaeTwitterKey = ConfigurationManager.AppSettings["naa4e:twitter:key"];
            var naaeTwitterSecret = ConfigurationManager.AppSettings["naa4e:twitter:sec"];
            if (!Globals.IsAnyNullOrEmpty(naaeTwitterKey, naaeTwitterSecret))
            {
                var twitterOptions = new TwitterAuthenticationOptions
                {
                    ConsumerKey = naaeTwitterKey,
                    ConsumerSecret = naaeTwitterSecret,
                    Provider = new TwitterAuthenticationProvider()
                    {
                        OnAuthenticated = (context) =>
                        {
                            context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstoken", context.AccessToken));
                            context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstokensecret", context.AccessTokenSecret));
                            return Task.FromResult(0);
                        }
                    }
                };
                app.UseTwitterAuthentication(twitterOptions);
            }

            // Configure social authentication: Facebook
            var naaeFbKey = ConfigurationManager.AppSettings["naa4e:fb:key"];
            var naaeFbSecret = ConfigurationManager.AppSettings["naa4e:fb:sec"];
            if (!Globals.IsAnyNullOrEmpty(naaeFbKey, naaeFbSecret))
            {
                var fbOptions = new FacebookAuthenticationOptions
                {
                    AppId = naaeFbKey,
                    AppSecret = naaeFbSecret,
                    Provider = new FacebookAuthenticationProvider
                    {
                        OnAuthenticated = (context) =>
                        {
                            // Gives you email, ID (to get profile pic), full name, and more
                            context.Identity.AddClaim(new Claim("urn:facebook:access_token", context.AccessToken));  
                            context.Identity.AddClaim(new Claim("urn:facebook:email", context.Email));
                            return Task.FromResult(0);
                        }
                    }
                };
                fbOptions.Scope.Add("email");
                app.UseFacebookAuthentication(fbOptions);
            }
        }
Example #23
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

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

            app.UseTwitterAuthentication(
               consumerKey: "PWmtzEvBdTMfJ2GJWBDA1WEny",
               consumerSecret: "p7z1mcC5wsT1mdsiRVkio93M3hRdeNjQPP8ifpfmfTh8Lko3Uw");

            app.UseFacebookAuthentication(
               appId: "1679103069041937",
               appSecret: "5fe2a7ca3317a1fe43ee538fc972c481");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "795097649471-u3lc8eva98ho7lpk6a95kvhs463ddltr.apps.googleusercontent.com",
            //    ClientSecret = "aszuOjxGqphSJ8DE13d6nu_u"
            //});

            app.UseLinkedInAuthentication("77cqvvlk8h3zrt", "OeXSfuGYk15VpDer");

            app.UseGitHubAuthentication(
                clientId: "a7764ab9ebbf06896f50",
                clientSecret: "db5bf16e5a1481c1d2eb4e3c4828de7d72d931dc");
        }
Example #24
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Social/Login"),
            });            
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId = this.configurationReader.FacebookAppId,
                AppSecret = this.configurationReader.FacebookAppSecret,
                Scope =
                    {
                        "email"
                    },
                BackchannelHttpHandler = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email",
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = (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"));
                            }

                        }

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey = this.configurationReader.TwitterConsumerKey,
                ConsumerSecret = this.configurationReader.TwitterConsumerSecret,
                SignInAsAuthenticationType = ConstantStrings.AuthorizationCookieName,
                BackchannelCertificateValidator = null   // can be for demo purposes
            });


            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                ClientId = this.configurationReader.GoogleClientId,
                ClientSecret = this.configurationReader.GoogleClientSecret
            });
        }
Example #25
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

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

            app.UseLinkedInAuthentication(
                clientId: "77ciafbm5z7o7p",
                clientSecret: "dRrJihfJrzGQtdb7");

            app.UseTwitterAuthentication(
               consumerKey: "98o8VvM5vqeuneLDcOtNzT9Hy",
               consumerSecret: "CTSKjYk24eW7y69SVpltz1oEWIW72Nkzq8Xr51GMfcC8lodlh8");

            app.UseFacebookAuthentication(
               appId: "1464866667162348",
               appSecret: "f2c4ceef2b63323090a8d14ecf251ac1");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
        // Para obtener más información para configurar la autenticación, visite http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure el contexto de base de datos, el administrador de usuarios y el administrador de inicios de sesión para usar una única instancia por solicitud
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Permitir que la aplicación use una cookie para almacenar información para el usuario que inicia sesión
            // y una cookie para almacenar temporalmente información sobre un usuario que inicia sesión con un proveedor de inicio de sesión de terceros
            // Configurar cookie de inicio de sesión
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    // Permite a la aplicación validar la marca de seguridad cuando el usuario inicia sesión.
                    // Es una característica de seguridad que se usa cuando se cambia una contraseña o se agrega un inicio de sesión externo a la cuenta.
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Permite que la aplicación almacene temporalmente la información del usuario cuando se verifica el segundo factor en el proceso de autenticación de dos factores.
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // Permite que la aplicación recuerde el segundo factor de verificación de inicio de sesión, como el teléfono o correo electrónico.
            // Cuando selecciona esta opción, el segundo paso de la verificación del proceso de inicio de sesión se recordará en el dispositivo desde el que ha iniciado sesión.
            // Es similar a la opción Recordarme al iniciar sesión.
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // Quitar los comentarios de las siguientes líneas para habilitar el inicio de sesión con proveedores de inicio de sesión de terceros

            //app.UseMicrosoftAccountAuthentication(
            //    clientId: Cryptography.Decrypt(ConfigurationManager.AppSettings["liveClientId"].ToString()),
            //    clientSecret: Cryptography.Decrypt(ConfigurationManager.AppSettings["liveClientId"].ToString()));

            app.UseTwitterAuthentication(
               consumerKey: Cryptography.Decrypt(ConfigurationManager.AppSettings["twitterClientId"].ToString()),
               consumerSecret: Cryptography.Decrypt(ConfigurationManager.AppSettings["twitterClientSecret"].ToString()));

            app.UseFacebookAuthentication(
               appId: Cryptography.Decrypt(ConfigurationManager.AppSettings["facebookClientId"].ToString()),
               appSecret: Cryptography.Decrypt(ConfigurationManager.AppSettings["facebookClientSecret"].ToString()));

            string googleClientId = Cryptography.Decrypt(ConfigurationManager.AppSettings["googleClientId"].ToString());
            string googleClientSecret = Cryptography.Decrypt(ConfigurationManager.AppSettings["googleClientSecret"].ToString());

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = googleClientId,
                ClientSecret = googleClientSecret
            });
        }
Example #27
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, 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);

            // Added to allow roles
            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);

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

            app.UseTwitterAuthentication(
            consumerKey: "wEUSnL8wkfzst157rX62DRv7D",
            consumerSecret: "l5TYmUMHnJgIHALjC0FLJeaGDeMO67HevNlXl5vzTXDcJ7ueLV");

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #28
0
        // 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.UseApplicationSignInCookie();

            // Enable the application to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie();

            app.UseTwitterAuthentication(consumerKey: "JsYU5yR1tZMrnKNKPzIvQg",
                                         consumerSecret: "TQ9UX1B7IsgS9AUfgeMJKrC9ZwrKdZwSQDKiaXb0");
        }
Example #29
0
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();

            // Disable keep alive, no need
            GlobalHost.Configuration.DisconnectTimeout = TimeSpan.FromMinutes(3);

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = "ShootR",
                Provider = new ShootRAuthenticationProvider()
            });

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                Provider = new TwitterAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        var service = new TwitterService(ConfigurationManager.AppSettings["twitterConsumerKey"], ConfigurationManager.AppSettings["twitterConsumerSecret"]);
                        service.AuthenticateWith(context.AccessToken, context.AccessTokenSecret);

                        var profile = service.GetUserProfile(new GetUserProfileOptions
                        {
                            IncludeEntities = true
                        });

                        context.Identity.AddClaim(new Claim("profilePicture", profile.ProfileImageUrl));
                    }
                },
                SignInAsAuthenticationType = "ShootR",
                ConsumerKey = ConfigurationManager.AppSettings["twitterConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["twitterConsumerSecret"]
            });

            app.UseGoogleAuthentication(new GoogleAuthenticationOptions
            {
                SignInAsAuthenticationType = "ShootR"
            });

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("profilePicture", "https://graph.facebook.com/" + context.Identity.FindFirst(ClaimTypes.NameIdentifier).Value + "/picture?type=large"));
                    }
                },
                SignInAsAuthenticationType = "ShootR",
                AppId = ConfigurationManager.AppSettings["facebookAppId"],
                AppSecret = ConfigurationManager.AppSettings["facebookAppSecret"]
            });
        }
Example #30
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(Baby7DbContext.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.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login"),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, Boy7User>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

            app.UseTwitterAuthentication(
               consumerKey: ConfigurationManager.AppSettings["TwitterClientId"],  //"d3nK7tbc7dnSCwrv7M9NHn0Ot",
               consumerSecret: ConfigurationManager.AppSettings["TwitterClientSecret"]  //"Ir1YCMC0DuWEsVLDEA27DQFwKT0gekkRnSJiJlM8lFUFwGprCi");
            );

            //localhost
            app.UseFacebookAuthentication(
               appId: ConfigurationManager.AppSettings["FacebookClientId"],         //"1500725923474073",
               appSecret: ConfigurationManager.AppSettings["FacebookClientSecret"]  //"577d3c15de6ca70437b60336dd01dc30");
            );

            //localhost
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = ConfigurationManager.AppSettings["GoogleClientId"].ToString(),  // "729988413782-f4fej2kmnmu29pf26j63ampb5b88ut0j.apps.googleusercontent.com",
                ClientSecret = ConfigurationManager.AppSettings["GoogleClientSecret"] //"5yR9-aeEHoqNymAZTjsDT9NQ"
            });

            //Azure
            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "729988413782-cfhk0oescuouklj0tjs645qgkauobfei.apps.googleusercontent.com",
            //    ClientSecret = "6c3FrrOxZsyldXgydwPn55ad"
            //});
        }
Example #31
0
        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);

            // 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 Authentication

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseOpenIdConnectAuthentication(
                new OpenIdConnectAuthenticationOptions
            {
                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId    = clientId,
                Authority   = authority,
                RedirectUri = redirectUri,
                // PostLogoutRedirectUri is the page that users will be redirected to after sign-out. In this case, it is using the home page
                PostLogoutRedirectUri = redirectUri,
                Scope = OpenIdConnectScope.OpenIdProfile,
                // ResponseType is set to request the id_token - which contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.IdToken,
                // ValidateIssuer set to false to allow personal and work accounts from any organization to sign in to your application
                // To only allow users from a single organizations, set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer = false     // This is a simplification
                },
                // OpenIdConnectAuthenticationNotifications configures OWIN to send notification of failed authentications to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            }
                );

            #endregion

            app.UseTwitterAuthentication(
                consumerKey: "vpjXLGkLYfkjNEYVEo1WETePc",
                consumerSecret: "612AQ8LHnYrcojjXjxbD2NiRW1FrINcVOvHfNOlYk5uxml1Nl7");

            app.UseFacebookAuthentication(
                appId: "526710651352502",
                appSecret: "17c42db827ec28e470237db585846d3e");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "45957034721-1ibvnu91b9duht36418qbtfv354pmn95.apps.googleusercontent.com",
                ClientSecret = "FHZxc_Sgbcr1YYcsTQjlyreE"
            });
        }
Example #32
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);


            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));
            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
                })
            };
            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));
                    }
                }
            };
            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
        }
Example #33
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(EFDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, UserEntity, Guid>(
                            TimeSpan.FromMinutes(30), (manager, user) => user.GenerateUserIdentityAsync(manager),
                            id => id.GetUserGuidId())
                }
            });
            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/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                AllowInsecureHttp         = false
            };

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

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

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

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "wDDuNu2auh21NLhWQu2zOdhSc",
                ConsumerSecret = "QYeJH178DVJB6hSovnbWoTueHKo87WGNAPNLMmCkfcNctlaHEw",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",
                    // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });

            app.UseFacebookAuthentication(
                "1112060955498040",
                "34ffff458c622d4e4ed497d9560d94a0");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #34
0
        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>(
                ApplicationUserManagerFactory.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
                {
                    OnValidateIdentity =
                        SecurityStampValidator
                        .OnValidateIdentity
                        <ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(20),
                            regenerateIdentity:
                            (manager, user) =>
                            user.GenerateUserIdentityAsync(manager))
                }
            });

            // Use a cookie to temporarily store information about a user logging
            // in with a third party login provider
            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);

            // Modify Web.config settings to enable logging in with third-party
            // login providers.  See http://go.microsoft.com/fwlink/?LinkId=252803
            // for details on setting up this ASP.NET application to support
            // logging in via external services.

            string microsoftClientId  = ConfigurationManager.AppSettings["AuthMicrosoftClientId"];
            string twitterConsumerKey = ConfigurationManager.AppSettings["AuthTwitterApiKey"];
            string facebookAppId      = ConfigurationManager.AppSettings["AuthFacebookAppId"];
            string googleClientId     = ConfigurationManager.AppSettings["AuthGoogleClientId"];

            // https://account.live.com/developers/applications/
            // http://www.benday.com/2014/02/25/walkthrough-asp-net-mvc-identity-with-microsoft-account-authentication/
            // Configure RedirectUrl as http://www.mysampleapp.com/signin-microsoft
            if (!String.IsNullOrWhiteSpace(microsoftClientId))
            {
                string clientSecret = ConfigurationManager.AppSettings["AuthMicrosoftClientSecret"];
                app.UseMicrosoftAccountAuthentication(clientId: microsoftClientId, clientSecret: clientSecret);
            }

            // https://dev.twitter.com/
            if (!String.IsNullOrWhiteSpace(twitterConsumerKey))
            {
                string consumerSecret = ConfigurationManager.AppSettings["AuthTwitterApiSecret"];
                app.UseTwitterAuthentication(consumerKey: twitterConsumerKey, consumerSecret: consumerSecret);
            }

            // https://developers.facebook.com/apps
            if (!String.IsNullOrWhiteSpace(facebookAppId))
            {
                string appSecret = ConfigurationManager.AppSettings["AuthFacebookAppSecret"];
                app.UseFacebookAuthentication(appId: facebookAppId, appSecret: appSecret);
            }

            // https://console.developers.google.com/
            // http://www.asp.net/mvc/tutorials/mvc-5/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
            // Configure RedirectUrl as http://www.mysampleapp.com/signin-google
            if (!String.IsNullOrWhiteSpace(googleClientId))
            {
                string clientSecret = ConfigurationManager.AppSettings["AuthGoogleClientSecret"];
                app.UseGoogleAuthentication(
                    clientId: googleClientId,
                    clientSecret: clientSecret
                    );
            }
        }
Example #35
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey = "1MT5S4825ZvRDb8k54Qx8zCaw",
                ConsumerSecret = "V81gtDk0pMHvFl9yDJp7iuqHaf1FcNHMcH096XQelEfIQg4ilU",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A 
                    "B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High Assurance EV Root CA
                })
            });

            app.UseFacebookAuthentication(
               appId: "1925159914434537",
               appSecret: "65ba9e74e13dd5387663d4755f2a44f4");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ProgrammersSpotDbContext.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
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, User>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "Af46IZxmqTttA6t78pJYNoowJ",
                ConsumerSecret = "BO2bqArZOVk5wwimsSm6EYkPAvAiR5GU93nMXhkbzwPf9QepXj",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });

            app.UseFacebookAuthentication(
                appId: "893522627456518",
                appSecret: "c025c2fa915d6de8b286b8b00aeb4b1d");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "464230475643-64vs1ojp3aatqkipvos04hpq77uukl1g.apps.googleusercontent.com",
                ClientSecret = "RYr3z-kF-WzyVHmM9Fyna8-2"
            });
        }
Example #37
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864

        ////////////////////////////////////////////////////////////////////////////////////////////////////
        /// <summary>   Configure authentication. </summary>
        ///
        /// <remarks>   Aedmonds, 8/25/2017. </remarks>
        ///
        /// <param name="app">  The application. </param>
        ////////////////////////////////////////////////////////////////////////////////////////////////////

        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.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);

            // 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"),
                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(20),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            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);

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

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

            //app.UseTwitterAuthentication(
            //    consumerKey: "50bgdOBzPUdfdUdz9gBxsj57u",
            //    consumerSecret: "5OBfxU4USS08ZXEzXRNEcZZguADad1qxjG3F0DrD8nxqIlfLWX"

            //    );
            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "50bgdOBzPUdfdUdz9gBxsj57u",
                ConsumerSecret = "5OBfxU4USS08ZXEzXRNEcZZguADad1qxjG3F0DrD8nxqIlfLWX",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });
            app.UseFacebookAuthentication(
                appId: "1721939471382143",
                appSecret: "5791fe289935183652592a03276e47b1");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "421974538452-c7cvqkprmt2apgjov03412gq4lr6f382.apps.googleusercontent.com",
                ClientSecret = "F9IhmKJMqSrfIwGC80FB0XBv"
            });
        }
        // For more information on configuring authentication, please visit http://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);


            // 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, CassandraUser, Guid>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentityCallback: (manager, user) => user.GenerateUserIdentityAsync(manager),
                        getUserIdCallback: (id) => (Guid.Parse(id.GetUserId())))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "uWkHwFNbklXgsLHYzLfRXcThw",
                ConsumerSecret = "2kyg9WdUiJuU2HeWYJEuvwzaJWoweLadTgG3i0oHI5FeNjD5Iv",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",
                    // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });

            app.UseDeveloperAuthentication(new DeveloperAuthenticationOptions()
            {
                ConsumerKey    = "uWkHwFNbklXgsLHYzLfRXcThw",
                ConsumerSecret = "2kyg9WdUiJuU2HeWYJEuvwzaJWoweLadTgG3i0oHI5FeNjD5Iv",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",
                    // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });

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

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "1096301616546-edbl612881t7rkpljp3qa3juminskulo.apps.googleusercontent.com",
                ClientSecret = "gOKwmN181CgsnQQDWqTSZjFs"
            });
        }
        // For more information on configuring authentication, please visit http://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);

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

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

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

            // Uncomment the following lines to enable logging in with third party login providers
            #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
                })
            };
            app.UseTwitterAuthentication(twitterAuthenticationOptions);

            #endregion Twitter

            #region LinkedIn

            app.UseLinkedInAuthentication(
                clientId: "77g2s7wgbminls",
                clientSecret: "20S5G0D0Lh40IRKW"
                );
            #endregion

            #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));
                    }
                }
            };
            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
        }
Example #40
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

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

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


            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "2L3FpITwi3LViAVAB0bIPhCCu",
                ConsumerSecret = "RBXJxvYezWwSLG07orrQQyJDUoCoxE84zoP16gqyCn0WRftzBp",
                BackchannelCertificateValidator =
                    new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(
                        new[] {
                    // VeriSign Class 3 Secure Server CA - G2
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47",
                    // VeriSign Class 3 Secure Server CA - G3
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5",
                    // VeriSign Class 3 Public Primary Certification Authority - G5
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",
                    // Symantec Class 3 Secure Server CA - G4
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD",
                    // Symantec Class 3 EV SSL CA - G3
                    "‎add53f6680fe66e383cbac3e60922e3b4c412bed",
                    // VeriSign Class 3 Primary CA - G5
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5",
                    // DigiCert SHA2 High Assurance Server C‎A
                    "5168FF90AF0207753CCCD9656462A212B859723B",
                    // DigiCert High Assurance EV Root CA
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"
                })
            });

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #41
0
        /// <summary>
        /// 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください
        ///
        /// Code! MVC 5 App with Facebook, Twitter, LinkedIn
        /// and Google OAuth2 Sign-on (C#) | The ASP.NET Site
        /// http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
        /// </summary>
        /// <param name="app">app</param>
        public static void Configure(IAppBuilder app)
        {
            // 1 要求につき 1 インスタンスのみを使用するように
            // DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。

            // Add to OwinContext.

            #region AuthenticationType

            // AuthenticationType:
            //   ClaimsIdentity生成時や、AuthenticationTicket取得時に指定する。

            // --------------------------------------------------
            // OAuthDefaultsクラス (Microsoft.Owin.Security)
            // https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthdefaults.aspx
            // --------------------------------------------------
            // - OAuthDefaults.AuthenticationType フィールド (Microsoft.Owin.Security.OAuth)
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthdefaults.authenticationtype.aspx
            //   OAuthBearerAuthenticationOptions と OAuthAuthorizationServerOptions の AuthenticationType プロパティの既定値。
            //   - AuthenticationOptions.AuthenticationType プロパティ (Microsoft.Owin.Security)
            //     https://msdn.microsoft.com/ja-jp/library/dn300391.aspx
            //   - AuthenticationOptions.AuthenticationType プロパティ (Microsoft.Owin.Security)
            //     https://msdn.microsoft.com/ja-jp/library/dn300391.aspx
            // --------------------------------------------------

            // --------------------------------------------------
            // DefaultAuthenticationTypes クラス (Microsoft.AspNet.Identity)
            // https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.aspx
            // --------------------------------------------------
            // - ApplicationCookie
            //   Forms認証用 Cookie認証チケット
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.applicationcookie.aspx
            // - TwoFactorRememberBrowserCookie
            //   Browser認証用 Cookie認証チケット
            //   https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.defaultauthenticationtypes.twofactorrememberbrowsercookie.aspx
            // - TwoFactorCookie
            //   TwoFactor認証用 Cookie認証チケット
            //   https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.defaultauthenticationtypes.twofactorcookie.aspx
            // - ExternalCookie
            //   外部ログイン Cookie認証チケット
            //   /userinfoやid_tokenの情報をCookieに格納してある。
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.externalcookie.aspx
            // - ExternalBearer
            //   Bearer TokenのUnprotectする際、ClaimsIdentityに指定。
            //   https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.externalbearer.aspx
            // --------------------------------------------------

            #endregion

            #region EntityFramework
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            #endregion

            #region EntityFramework以外

            #region UserStore, ApplicationUserManager, RoleManager, SignInManagerのOwinContextを生成

            // UserStoreのOwinContextを生成
            app.CreatePerOwinContext <UserStore>(() => new UserStore());

            // ApplicationUserManagerのOwinContextを生成
            // 以下を設定する
            // - ユーザ名検証
            // - パスワード検証
            // - ユーザ ロックアウト
            // - 2FAプロバイダ
            // - 暗号化プロバイダ
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);

            // ApplicationRoleManagerのOwinContextを生成
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);

            // ApplicationSignInManagerのOwinContextを生成
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            #endregion

            #region UseCookieAuthenticationのOwinContextを生成

            // 次を設定
            // - AuthenticationType
            // - LoginPath
            // - Provider
            // - SecurityStamp

            // 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.

            // アプリケーションがユーザのサイン・イン情報をCookie認証チケットに一時的に保存するようにします。
            // また、サードパーティのプロバイダでログインするユーザ情報もCookie認証チケットを使用してできるようにします。
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,  // 認証タイプを設定する。
                LoginPath          = new PathString("/Account/Login"),              // ログイン画面のパスを設定する。

                Provider = new CookieAuthenticationProvider                         // 認証プロバイダを設定する(ICookieAuthenticationProvider の既定の実装)。
                {
                    #region SecurityStamp

                    // 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.

                    // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。
                    // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。

                    // --------------------------------------------------
                    // SecurityStampValidator.OnValidateIdentity
                    // --------------------------------------------------
                    // パスワードの変更や、外部ログインを追加した際に、全てのログインセッションを
                    // 無効化できるようCookie認証チケットに、ログインに紐付くセキュリティスタンプを埋め込んでいる。
                    // http://kendik.hatenablog.com/entry/2014/08/17/212645
                    // --------------------------------------------------
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        // SecurityStampValidatorによる検証の間隔
                        validateInterval: ASPNETIdentityConfig.SecurityStampValidateIntervalFromSeconds,
                        // ClaimsIdentityを返すdelegate
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

                                         #endregion
                },

                // Cookie認証チケットの有効期限
                ExpireTimeSpan = ASPNETIdentityConfig.AuthCookieExpiresFromHours,
                // Cookie認証チケットの有効期限を半分過ぎた祭の要求で再発行(Sliding)される。
                SlidingExpiration = ASPNETIdentityConfig.AuthCookieSlidingExpiration,
            });

            #endregion

            #region UseExternalSignInCookieのOwinContextを生成

            // 外部アイデンティティのためOWINミドルウェアベースの
            // Cookie認証を使用するようにアプリケーションを設定します。
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            #endregion

            #region UseTwoFactor(2FA)のOwinContextを生成

            #region SignInCookie(2FAのCookie認証チケット)

            // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process.
            // 2FAプロセスにおいて第 2 認証要素を検証しているユーザの情報を一時的に格納するようにします。
            app.UseTwoFactorSignInCookie(
                authenticationType: DefaultAuthenticationTypes.TwoFactorCookie,
                expires: ASPNETIdentityConfig.TwoFactorCookieExpiresFromHours);

            #endregion

            #region RememberBrowserCookie(2FAのブラウザ記憶)

            // 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.

            // 電話や電子メールなど2FAのログイン検証係数を記憶するようにアプリケーションを設定します。
            // このオプションをチェックすると、ログイン時プロセスの第二検証ステップでログインデバイス上に記憶されます。
            // これは、ログイン時の「このアカウントを記憶する」オプションに似ています。

            app.UseTwoFactorRememberBrowserCookie(
                DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            #endregion

            #endregion

            #region Use(External)AuthenticationのOwinContextを生成

            // c# - Get E-mail of User Authenticated with Microsoft Account in ASP.NET Identity - Stack Overflow
            // http://stackoverflow.com/questions/22229593/get-e-mail-of-user-authenticated-with-microsoft-account-in-asp-net-identity

            #region MicrosoftAccountAuthentication

            if (ASPNETIdentityConfig.MicrosoftAccountAuthentication)
            {
                MicrosoftAccountAuthenticationOptions options = new MicrosoftAccountAuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    ClientId     = ASPNETIdentityConfig.MicrosoftAccountAuthenticationClientId,
                    ClientSecret = ASPNETIdentityConfig.MicrosoftAccountAuthenticationClientSecret
                };
                // スコープを追加する。
                options.Scope.Add("wl.basic");
                options.Scope.Add("wl.emails");

                // MicrosoftAccountAuthenticationの有効化
                app.UseMicrosoftAccountAuthentication(options);
            }

            #endregion

            #region GoogleAuthentication

            if (ASPNETIdentityConfig.GoogleAuthentication)
            {
                GoogleOAuth2AuthenticationOptions options = new GoogleOAuth2AuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    ClientId     = ASPNETIdentityConfig.GoogleAuthenticationClientId,
                    ClientSecret = ASPNETIdentityConfig.GoogleAuthenticationClientSecret
                };
                // スコープを追加する。
                options.Scope.Add("openid");
                options.Scope.Add("profile");
                options.Scope.Add("email");

                // GoogleAuthenticationの有効化
                app.UseGoogleAuthentication(options);
            }

            #endregion

            #region FacebookAuthentication

            if (ASPNETIdentityConfig.FacebookAuthentication)
            {
                FacebookAuthenticationOptions options = new FacebookAuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    AppId     = ASPNETIdentityConfig.FacebookAuthenticationClientId,
                    AppSecret = ASPNETIdentityConfig.FacebookAuthenticationClientSecret,
                    Provider  = new FacebookAuthenticationProvider
                    {
                        OnAuthenticated = context =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                            return(Task.FromResult(true));
                        }
                    }
                };
                // スコープを追加する。
                options.Scope.Add("email");

                // FacebookAuthenticationの有効化
                app.UseFacebookAuthentication(options);
            }

            #endregion

            #region TwitterAuthentication

            if (ASPNETIdentityConfig.TwitterAuthentication)
            {
                TwitterAuthenticationOptions options = new TwitterAuthenticationOptions
                {
                    BackchannelHttpHandler = new WebRequestHandler()
                    {
                        Proxy    = CreateProxy.GetInternetProxy(),
                        UseProxy = ASPNETIdentityConfig.UseInternetProxy
                    },
                    ConsumerKey    = ASPNETIdentityConfig.TwitterAuthenticationClientId,
                    ConsumerSecret = ASPNETIdentityConfig.TwitterAuthenticationClientSecret,

                    Provider = new TwitterAuthenticationProvider
                    {
                        OnAuthenticated = (context) =>
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken));
                            context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_secret", context.AccessTokenSecret));
                            return(Task.FromResult(0));
                        }
                    },

                    BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                        new string[] {
                        "A5EF0B11CEC04103A34A659048B21CE0572D7D47",      // VeriSign Class 3 Secure Server CA - G2
                        "0D445C165344C1827E1D20AB25F40163D8BE79A5",      // VeriSign Class 3 Secure Server CA - G3
                        "7FD365A7C2DDECBBF03009F34339FA02AF333133",      // VeriSign Class 3 Public Primary Certification Authority - G5
                        "39A55D933676616E73A761DFA16A7E59CDE66FAD",      // Symantec Class 3 Secure Server CA - G4
                        "5168FF90AF0207753CCCD9656462A212B859723B",      // DigiCert SHA2 High Assurance Server C‎A
                        "B13EC36903F8BF4701D498261A0802EF63642BC3"
                    }                                                    // DigiCert High Assurance EV Root CA
                        ),
                };

                // スコープを追加する。
                // ・・・

                // TwitterAuthenticationの有効化
                app.UseTwitterAuthentication(options);
            }

            #endregion

            #endregion

            #region OAuth Endpointの追加

            // asp.net identity - UseOAuthBearerTokens vs UseOAuthBearerAuthentication - Stack Overflow
            // http://stackoverflow.com/questions/28048355/useoauthbearertokens-vs-useoauthbearerauthentication
            //   Pseudocode from source using reflector:
            //   UseOAuthAuthorizationServer();  // authorization server middleware.
            //   UseOAuthBearerAuthentication(); // application bearer token middleware.
            //   UseOAuthBearerAuthentication(); // external bearer token middleware.
            //   UseOAuthBearerTokens();         // extension method creates both the token server
            //                                   //   and the middleware to validate tokens for requests in the same application.

            // c# - ASP.Net identity: Difference between UseOAuthBearerTokens and UseCookieAuthentication? - Stack Overflow
            // http://stackoverflow.com/questions/22121330/asp-net-identity-difference-between-useoauthbearertokens-and-usecookieauthentic

            if (ASPNETIdentityConfig.EquipOAuthServer)
            {
                // OAuth Bearer Tokenを使用可能に設定する。
                // UseOAuthAuthorizationServerとUseOAuthBearerTokensの違いが不明だが、
                // UseOAuthAuthorizationServerだとOAuthBearerTokenEndpointPathが動かない。

                #region UseOAuthAuthorizationServer

                /*
                 * // --------------------------------------------------
                 * // OAuthAuthorizationServerを設定する。
                 * // --------------------------------------------------
                 * // OAuthAuthorizationServerExtensions.UseOAuthAuthorizationServer メソッド (Owin)
                 * // https://msdn.microsoft.com/ja-jp/library/dn270711.aspx
                 * // --------------------------------------------------
                 * // 参考:https://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server
                 * app.UseOAuthAuthorizationServer(
                 *  new OAuthAuthorizationServerOptions
                 *  {
                 *      Provider = new ApplicationOAuthAuthorizationServerProvider(),
                 *      AllowInsecureHttp = ASPNETIdentityConfig.AllowOAuthInsecureHttpEndpoints,
                 *      ApplicationCanDisplayErrors = ASPNETIdentityConfig.OAuthAuthorizeEndpointCanDisplayErrors,
                 *      AuthorizeEndpointPath = ASPNETIdentityConfig.OAuthAuthorizeEndpointPath,
                 *      AccessTokenExpireTimeSpan = ASPNETIdentityConfig.OAuthAccessTokenExpireTimeSpanFromMinutes,
                 *
                 *      // Authorization code provider which creates and receives the authorization code.
                 *      AuthorizationCodeProvider = new AuthenticationTokenProvider
                 *      {
                 *          OnCreate = CreateAuthenticationCode,
                 *          OnReceive = ReceiveAuthenticationCode,
                 *      },
                 *
                 *      // Refresh token provider which creates and receives refresh token.
                 *      RefreshTokenProvider = new AuthenticationTokenProvider
                 *      {
                 *          OnCreate = CreateRefreshToken,
                 *          OnReceive = ReceiveRefreshToken,
                 *      }
                 *  });
                 */

                #endregion

                #region UseOAuthBearerAuthentication

                // --------------------------------------------------
                // Resource Server単品を実装する際のメソッドであるもよう。
                // --------------------------------------------------

                //app.UseOAuthBearerAuthentication(
                //    new OAuthBearerAuthenticationOptions
                //    {
                //    });

                #endregion

                #region UseOAuthBearerTokens

                // --------------------------------------------------
                // OAuth Bearer Tokenを使用可能に設定する。
                // --------------------------------------------------
                // AppBuilderExtensions.UseOAuthBearerTokens Method (IAppBuilder, OAuthAuthorizationServerOptions) (Owin)
                // https://msdn.microsoft.com/ja-jp/library/owin.appbuilderextensions.useoauthbearertokens.aspx
                // --------------------------------------------------
                AuthenticationTokenProvider atp = new AuthenticationTokenProvider();

                // 以下のOAuth 2.0のフロー定義をサポートする。
                // ・Implicitグラント種別
                // ・Resource Owner Password Credentialsグラント種別
                // ・Client Credentialsグラント種別
                OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions =
                    new OAuthAuthorizationServerOptions
                {
                    #region 全てのグラント種別の共通設定

                    // ・Provider
                    //   OAuthAuthorizationServerProviderの派生クラスである、
                    //   ApplicationOAuthBearerTokenProvider(UseOAuthBearerTokens用)を設定する。
                    //   以下の4つのメソッドをオーバーライドする。
                    //   ・OnValidateClientRedirectUriプロパティ設定 or ValidateClientRedirectUriのオーバーライド
                    //   ・OnValidateClientAuthenticationプロパティ設定 or ValidateClientAuthenticationのオーバーライド
                    //   ・OnGrantResourceOwnerCredentialsプロパティ設定 or GrantResourceOwnerCredentialsのオーバーライド
                    //   ・OnGrantClientCredentialsプロパティ設定 or GrantClientCredentialsのオーバーライド
                    Provider = new ApplicationOAuthBearerTokenProvider(),

                    //AccessTokenFormat = new AccessTokenFormatJwt(),

                    // ・AccessTokenExpireTimeSpan(OAuth Access Token の 有効期限
                    AccessTokenExpireTimeSpan = ASPNETIdentityConfig.OAuthAccessTokenExpireTimeSpanFromMinutes,     // System.TimeSpan.FromSeconds(10), // Debug時

                    // ・AllowInsecureHttp
                    //   認証して、Token要求が http URI アドレスに届くことを許可し、
                    //   受信する redirect_uri 承認要求パラメータに http URI アドレスを設定する場合は true。
                    AllowInsecureHttp = ASPNETIdentityConfig.AllowOAuthInsecureHttpEndpoints,

                    #endregion

                    #region  Implicitグラント種別を除く全てのグラント種別の共通設定

                    // ・OAuth Bearer Token の Token Endpoint
                    TokenEndpointPath = new PathString(ASPNETIdentityConfig.OAuthBearerTokenEndpoint),

                    #endregion

                    #region Authorization Code, Implicitグラント種別の共通設定

                    // ・AuthorizeEndpointPath
                    //   OAuth の Authorize Endpoint
                    AuthorizeEndpointPath = new PathString(ASPNETIdentityConfig.OAuthAuthorizeEndpoint),

                    // ・ApplicationCanDisplayErrors
                    //   AuthorizeEndpointPath上でエラー メッセージを表示できるようにする。
                    ApplicationCanDisplayErrors = ASPNETIdentityConfig.OAuthAuthorizeEndpointCanDisplayErrors,

                    #endregion

                    #region Authorization Codeグラント種別

                    #region AuthorizationCodeProvider
                    //   1 回だけ使用する認証コードを生成して、クライアント アプリケーションに返す。
                    //   OnCreate または OnCreateAsync イベントによって生成されたトークンは、
                    //   OnReceive または OnReceiveAsync イベントへの呼び出しに対して、一度だけ有効となる。
                    //   Authorization code provider which creates and receives authorization code
                    AuthorizationCodeProvider = new AuthenticationTokenProvider
                    {
                        OnCreate  = AuthorizationCodeProvider.GetInstance().Create,
                        OnReceive = AuthorizationCodeProvider.GetInstance().Receive,
                        //OnCreateAsync = AuthorizationCodeProvider.GetInstance().CreateAsync,
                        //OnReceiveAsync = AuthorizationCodeProvider.GetInstance().ReceiveAsync,
                    },
                    #endregion

                    #region  RefreshTokenProvider
                    //   必要に応じて、新しいAccessTokenの生成に使うことができるRefresh Tokenを生成する。
                    //   RefreshTokenProviderが提供されない場合、OAuthBearerTokenEndpointPathからRefresh Tokenが返されない。
                    //   Refresh token provider which creates and receives referesh token
                    RefreshTokenProvider = new AuthenticationTokenProvider
                    {
                        OnCreate  = RefreshTokenProvider.GetInstance().Create,
                        OnReceive = RefreshTokenProvider.GetInstance().Receive,
                        //OnCreateAsync = RefreshTokenProvider.GetInstance().CreateAsync,
                        //OnReceiveAsync = RefreshTokenProvider.GetInstance().ReceiveAsync,
                    },
                    #endregion

                    #endregion
                };

                #region Options可変部分

                // AccessTokenFormat(OAuth Access Token の Format をJWTフォーマットに変更する。
                oAuthAuthorizationServerOptions.AccessTokenFormat = new AccessTokenFormatJwt();

                #endregion

                // UseOAuthBearerTokensにOAuthAuthorizationServerOptionsを設定
                app.UseOAuthBearerTokens(oAuthAuthorizationServerOptions);

                #endregion
            }

            #endregion

            #endregion
        }
        // For more information on configuring authentication, please visit http://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(() => DependencyResolver.Current.GetService <ApplicationUserManager>());

            // Configure the db context, user manager and role manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
            //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            // Configure the sign in cookie
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // Enables the application to validate the security stamp when the user logs in.
                    // This is a security feature which is used when you change a password or add an external login to your account.

                    //OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    //    validateInterval: TimeSpan.FromMinutes(30),
                    //    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))

                    OnValidateIdentity = ApplicationCookieIdentityValidator.OnValidateIdentity(
                        validateInterval: TimeSpan.FromMinutes(0),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

            // Uncomment the following lines to enable logging in with third party login providers

            app.UseMicrosoftAccountAuthentication(
                clientId: "SEU ID",
                clientSecret: "SEU TOKEN");

            app.UseTwitterAuthentication(
                consumerKey: "SEU ID",
                consumerSecret: "SEU TOKEN");


            app.UseGoogleAuthentication(
                clientId: "SEU ID",
                clientSecret: "SEU TOKEN");


            var fao = new FacebookAuthenticationOptions
            {
                AppId     = "SEU ID",
                AppSecret = "SEU TOKEN"
            };

            fao.Scope.Add("email");
            fao.Scope.Add("publish_actions");
            fao.Scope.Add("basic_info");

            fao.Provider = new 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));
                }
            };

            fao.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(fao);
        }
Example #43
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

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

                    /* I changed this part */
                    OnException = (context =>
                    {
                        throw context.Exception;
                    })
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "yydJeaOLKKFDXyz7CT4HX4Fhy",
                ConsumerSecret = "IcKlGKgzWCacz7zkCoRf4sIhvdN65rMszLSapYok8xsw9TSXkS",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });

            app.UseFacebookAuthentication(
                appId: "298770690496697",
                appSecret: "7204bbddd8e6d10f2d2d0e154fb4d8e9");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "854437471211-a8ol1klkv6omgt5k7boiqa531f915cqj.apps.googleusercontent.com",
                ClientSecret = "dR64N0q7tCPINE0G6SHsQXoG"
            });
        }
        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);


            // workaround for https://katanaproject.codeplex.com/workitem/409
            var metadataAddress = "https://adfs.leastprivilege.vm/federationmetadata/2007-06/federationmetadata.xml";
            var manager         = new SyncConfigurationManager(new ConfigurationManager <WsFederationConfiguration>(metadataAddress, new WsFederationConfigurationRetriever(), new HttpDocumentRetriever {
                RequireHttps = false
            }));

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

                ConfigurationManager = manager,
                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 #45
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301883
        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);

            // 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
                {
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            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);

            var msAuthOptions = new MicrosoftAccountAuthenticationOptions
            {
                ClientId     = "000000004814B875",
                ClientSecret = "lngSfDXmZcYlDclRcKfzas6hpk3LOipE",
                CallbackPath = new PathString("/Account/ExternalLoginCallback"),
            };

            app.UseMicrosoftAccountAuthentication(msAuthOptions);

            var twAuthOptions = new TwitterAuthenticationOptions
            {
                ConsumerKey    = "WzrkEmxx51YrWtwy2gIeJ5Aiv",
                ConsumerSecret = "S9IBpCoLFV6DKXhsUiM2wiedGUvSa6dltAa2PSVTxrOAWtWfYD",
            };

            app.UseTwitterAuthentication(twAuthOptions);

            var fbAuthOptions = new FacebookAuthenticationOptions
            {
                AppId     = "808310982550906",
                AppSecret = "72b007177792a854f6f76188845046aa",
            };

            app.UseFacebookAuthentication(fbAuthOptions);

            var goAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "300609129400-v1p6srt3i10fuvi3escsuo3a2428jbpv.apps.googleusercontent.com",
                ClientSecret = "g_u48liMarAn-PwhhaMdt4NM",
            };

            app.UseGoogleAuthentication(goAuthOptions);
        }
Example #46
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);

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

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

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

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

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

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "y37jZ7NlblNBPIFGcXZAo4dSs",
                ConsumerSecret = " 5HchJIW6IwrMlHWDPYEvmr5L6GjOf2KM6lroe0Y3Zt861D1TmB ",
                BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47",  // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5",  // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",  // VeriSign Class 3 Public Primary CA - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD",  // Symantec Class 3 Secure Server CA - G4
                    "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5",  // VeriSign Class 3 Primary CA - G5
                    "01C3968ACDBD57AE7DFAFF9552311608CF23A9F9",  // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"   // DigiCert High Assurance EV Root CA
                })
            });

            app.UseFacebookAuthentication(
                appId: "1940034419552333",
                appSecret: "bd089af30133a141beab5e8a352cc3d7");

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "737945419460-6auusno29r0slc42jm6rifk12ttqiunv.apps.googleusercontent.com",
                ClientSecret = "D9GnnDchoLvvjrGfTCAMhwBW"
            });
        }
Example #47
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);

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

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

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

            // Uncomment the following lines to enable logging in with third party login providers
            app.UseMicrosoftAccountAuthentication(
                clientId: "66c19b36-fd1c-44ce-816e-bde993923361",
                clientSecret: "uywmfMRQ39;@bvBTIU571?#");

            app.UseTwitterAuthentication(
                consumerKey: "m5qOyoXb8dFwDz45t3AYh4WtT",
                consumerSecret: "hKoKOb4nfD65PBFKcHb5xj5WtaVD5G9niJ3jk25dejJJSA0UgI");

            //app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            //{
            //    ConsumerKey = "m5qOyoXb8dFwDz45t3AYh4WtT",
            //    ConsumerSecret = "hKoKOb4nfD65PBFKcHb5xj5WtaVD5G9niJ3jk25dejJJSA0UgI"

            //    ,
            //    BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[]
            //    {

            //        "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
            //        "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
            //        "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary CA - G5
            //        "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
            //        "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
            //        "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
            //        "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
            //        "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
            //    })
            //});
            app.UseFacebookAuthentication(
                appId: "150900822389499",
                appSecret: "d00a0ddf700c563a0d34bd7984a5c32a"
                );

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "118416597455-jfravf0tocu7j9horeviolbth3f5cbn5.apps.googleusercontent.com",
                ClientSecret = "GEvtiYMNWUzXj0tdEOoDhV05"
            });
        }
Example #48
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

            // Uncomment the following lines to enable logging in with third party login providers
            app.UseMicrosoftAccountAuthentication(
                clientId: "499ef1c8-fced-4b89-b77b-8e184e7ec973",
                clientSecret: "RSve3iOt3k1P2PhCnWG1j62");

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


            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "ulLrGY69THNaaUPhpjmhZt4lU",
                ConsumerSecret = "WuWAwv31sbqcJVuas0cMazysWZIEE7KLyoKu6P8FckxwczsA1Q",
                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
                    "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5",  // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B",  // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"   // DigiCert High Assurance EV Root CA
                })
            });


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

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "247036705634-luvqvaotp55pi36cpb1psees2gg68t3k.apps.googleusercontent.com",
                ClientSecret = "0VOIOShyCjEKJd98xYtPwDNm"
            });
        }
Example #49
0
        private void ConfigureTwitter(IAppBuilder app)
        {
            /* -------------------------------------------------------------------------------
             * Normal configuration
             * ------------------------------------------------------------------------------- */

            //app.UseTwitterAuthentication("Your consumer key", "Your consumer secret");

            /* -------------------------------------------------------------------------------
             * Specify an alternate callback path
             * ------------------------------------------------------------------------------- */

            //var options = new TwitterAuthenticationOptions
            //{
            //    ConsumerKey = "Your consumer key",
            //    ConsumerSecret = "Your consumer secret",
            //    CallbackPath = new PathString("/oauth-redirect/twitter")
            //};
            //app.UseTwitterAuthentication(options);

            /* -------------------------------------------------------------------------------
             * Retrieve the access token and other user information
             * ------------------------------------------------------------------------------- */

            var options = new TwitterAuthenticationOptions
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TWITTER_API_KEY"],
                ConsumerSecret = ConfigurationManager.AppSettings["TWITTER_API_SECRET"],
                //BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[] {
                //    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA – G2
                //    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA – G3
                //    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority – G5
                //    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA – G4
                //    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                //    "B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High Assurance EV Root CA
                //}),
                //CallbackPath = new PathString("/en/Account/LoginCallback"),
                CallbackPath = new PathString("/en/signin-twitter"),
            };

            options.Provider = new TwitterAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    try
                    {
                        // Retrieve the OAuth access token to store for subsequent API calls
                        //string accessToken = context.AccessToken;

                        // Retrieve the screen name (e.g. @jerriepelser)
                        //string twitterScreenName = context.ScreenName;

                        // Retrieve the user ID
                        //var twitterUserId = context.UserId;
                        var userData = new OAuthReponseUserTwitter
                        {
                            //ProfilePicture = string.Format("https://twitter.com/{0}/profile_image?size=original", twitterScreenName)
                        };
                        OAuthReponseUserTwitter response = TwitterLogin(context.AccessToken, context.AccessTokenSecret, options.ConsumerKey, options.ConsumerSecret);
                        if (response != null)
                        {
                            context.Identity.AddClaim(new Claim(ClaimTypes.Email, response.Email));
                            context.Identity.AddClaim(new Claim(ClaimTypes.UserData, JsonConvert.SerializeObject(response)));
                        }
                        context.Identity.AddClaim(new Claim(_ClaimTypes.ExternalProviderAccessToken, context.AccessToken));
                    }
                    catch (Exception e)
                    {
                        File.AppendAllText(HttpContext.Current.Server.MapPath("~/Logs.txt"), DateTime.UtcNow.ToShortDateString() + " - " + HttpContext.Current.Request.Browser.Type + "\n\n" + e.Message + "\n\n===============================\n\n");
                    }
                    return(Task.FromResult(true));
                }
            };

            app.UseTwitterAuthentication(options);
        }
Example #50
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);

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

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

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

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


            app.UseTwitterAuthentication(
                consumerKey: "FuW4EGyrZpWh1INHc2H6pl4mY",
                consumerSecret: "aC0xlXNZPEWCAPaFYa51OZJOvGU1lL4tPMvtogwjCeeSM3d2T8");

            app.UseFacebookAuthentication(
                appId: "579225015814994",
                appSecret: "68f6fe3481d50f612fefda07f2e1dfe6");


            /*
             * app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
             * {
             *  ClientId = "37282451184-7nuf9c7p86537gihj5bk3ulggfo4gode.apps.googleusercontent.com",
             *  ClientSecret = "HJlxyR0jNeM0NNolT-ME6wwC"
             * });
             */

            /*
             * ClientId = WebConfigurationManager.AppSettings["googleClientId"]
             * ClientSecret = WebConfigurationManager.AppSettings["googleClientSecret"]
             */
        }
        public static void Configuration(IAppBuilder app)
        {
            app.UseDebugMiddleware(new DebugMiddlewareOptions
            {
                OnIncomingRequest = (ctx) =>
                {
                    var watch = new Stopwatch();
                    watch.Start();
                    ctx.Environment["DebugStopwatch"] = watch;
                },
                OnOutgoingRequest = (ctx) =>
                {
                    var watch = (Stopwatch)ctx.Environment["DebugStopwatch"];
                    watch.Stop();
                    Debug.WriteLine("Request took: " + watch.ElapsedMilliseconds + " ms");
                }
            });

            app.UseCookieAuthentication(new Microsoft.Owin.Security.Cookies.CookieAuthenticationOptions
            {
                AuthenticationType = "ApplicationCookie",
                LoginPath          = new Microsoft.Owin.PathString("/Auth/Login")
            });

            app.UseFacebookAuthentication(new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions
            {
                AppId     = "[INSERT APP ID FACEBOOK TWITTER APP]",
                AppSecret = "[INSERT APP SECRET FOR FACEBOOK APP]",
                SignInAsAuthenticationType = "ApplicationCookie"
            });

            app.UseTwitterAuthentication(new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions
            {
                ConsumerKey                     = "[INSERT CONSUMER KEY FOR TWITTER APP]",
                ConsumerSecret                  = "[INSERT CONSUMER SECRET FOR TWITTER APP]",
                SignInAsAuthenticationType      = "ApplicationCookie",
                BackchannelCertificateValidator = null
            });

            app.Use(async(ctx, next) => {
                if (ctx.Authentication.User.Identity.IsAuthenticated)
                {
                    Debug.WriteLine("User: "******"User Not Authenticated");
                }
                await next();
            });

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            app.UseWebApi(config);

            app.Map("/nancy", mappedApp => { mappedApp.UseNancy(); });
            //app.UseNancy(conf => {
            //    conf.PassThroughWhenStatusCodesAre(HttpStatusCode.NotFound);
            //});

            //app.Use(async (ctx, next) => {
            //    await ctx.Response.WriteAsync("<html><head></head><body>Hello World</body></html>");
            //});
        }
Example #52
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, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

            // Uncomment the following lines to enable logging in with third party login providers
            app.UseMicrosoftAccountAuthentication(
                clientId: "76e64974-3742-4ee6-b8a4-eeb2318840c0",
                clientSecret: "FVQTyg85aYaeXnsxiYrD4Wk");

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

            app.UseTwitterAuthentication(new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions
            {
                ConsumerKey    = "jVXe92S86vfD1J3z7T5IIS2M5",
                ConsumerSecret = "3wdDMNVjr2kLAf2sTUZ3uH5KKwH9e9BmdJJg6JoNq6lNGzDnLw",
                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
                    "‎add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5",  // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B",  // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"   // DigiCert High Assurance EV Root CA
                })
            });

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

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "657741589723-1r3de5jtq0p0ntq4i9f1gv2lb5i1c56s.apps.googleusercontent.com",
                ClientSecret = "w5DmdPf-vbwev3bJ0R7G1hf6"
            });

            //app.UseGitHubAuthentication("1cb9e53572f23b90a5eb", "cba4cf6a552b8399f00452ce2a6a94fe41d2423e");
        }
Example #53
0
        //const string ignoreClaimPrefix = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims";

        // For more information on configuring authentication, please visit http://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

            DataProtectionProvider = app.GetDataProtectionProvider();

            app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance <IDocumentSession>());
            app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance <ApplicationUserManager>());
            //app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance<ApplicationSignInManager>());

            //// 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("/loggain/"),
                CookieName         = ConfigurationManager.AppSettings["RavenDb.DefaultDatabase"] ?? "Easyfy.Auth",
                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))
                }
            });

            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

            // Uncomment the following lines to enable logging in with third party login providers

            if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Microsoft.ClientId")))
            {
                app.UseMicrosoftAccountAuthentication(
                    clientId: ConfigurationManager.AppSettings.Get("Microsoft.ClientId"),
                    clientSecret: ConfigurationManager.AppSettings.Get("Microsoft.ClientSecret"));
            }

            if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Google.ClientId")))
            {
                var googleOption = new GoogleOAuth2AuthenticationOptions()
                {
                    ClientId     = ConfigurationManager.AppSettings.Get("Google.ClientId"),
                    ClientSecret = ConfigurationManager.AppSettings.Get("Google.ClientSecret"),
                };

                googleOption.Scope.Add("email");

                app.UseGoogleAuthentication(googleOption);
            }

            if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Twitter.ConsumerKey")))
            {
                app.UseTwitterAuthentication(
                    consumerKey: ConfigurationManager.AppSettings["Twitter.ConsumerKey"],
                    consumerSecret: ConfigurationManager.AppSettings["Twitter.ConsumerSecret"]);
            }

            if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Facebook.AppId")))
            {
                var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions()
                {
                    AppId     = ConfigurationManager.AppSettings.Get("Facebook.AppId"),
                    AppSecret = ConfigurationManager.AppSettings.Get("Facebook.AppSecret"),
                    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));
                        }
                    }
                };
                facebookOptions.Scope.Add("email");

                app.UseFacebookAuthentication(facebookOptions);
            }
        }
Example #54
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);

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

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

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



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

            //MICROSOFT TEST LOGIN
            app.UseMicrosoftAccountAuthentication(
                clientId: "test123",
                clientSecret: "test123");


            app.UseFacebookAuthentication(
                appId: "361821174545785",
                appSecret: "c532bf1a9a3b6068632c54e5db283ffa");



            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "QaydrLmgun3kmbJlgv9GqA7T3",
                ConsumerSecret = "zhFjZwjR9seuoKM3tzmUAMyYBwIr3d2N8oKl51p6slliAushUF",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            });


            //GOOGLE TEST LOGIN
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "1013373664774-pr70bn9869p619jtj0vhho1k1mpbmgtf.apps.googleusercontent.com",
                ClientSecret = "WRfUR87-uBAgdlHwavm7KEe_"
            });
        }
Example #55
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            var Secret = ConfigurationManager.AppSettings["SecretKey"];

            byte[] key = Convert.FromBase64String(Secret);

            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(() => DependencyResolver.Current.GetService <ApplicationUserManager>());

            // Configure the db context, user manager and role manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationDbContext.Create);
            //app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            //app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.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.UseJwtBearerAuthentication(
                new Microsoft.Owin.Security.Jwt.JwtBearerAuthenticationOptions
            {
                AuthenticationMode        = Microsoft.Owin.Security.AuthenticationMode.Active,
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
                {
                    //ValidateIssuer = true,
                    //ValidateAudience = true,
                    ValidateIssuerSigningKey = true,
                    ValidIssuer      = ConfigurationManager.AppSettings["ValidIssuer"],
                    ValidAudience    = ConfigurationManager.AppSettings["ValidAudience"],
                    ValidateLifetime = true,
                    IssuerSigningKey = new SymmetricSecurityKey(key)
                }
            });

            //CookieAuthentication.EnableCookieAuthentication(app);

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

            // Uncomment the following lines to enable logging in with third party login providers

            app.UseMicrosoftAccountAuthentication(
                clientId: "SEU ID",
                clientSecret: "SEU TOKEN");

            app.UseTwitterAuthentication(
                consumerKey: "SEU ID",
                consumerSecret: "SEU TOKEN");


            app.UseGoogleAuthentication(
                clientId: "SEU ID",
                clientSecret: "SEU TOKEN");


            var fao = new FacebookAuthenticationOptions
            {
                AppId     = "SEU ID",
                AppSecret = "SEU TOKEN"
            };

            fao.Scope.Add("email");
            fao.Scope.Add("publish_actions");
            fao.Scope.Add("basic_info");

            fao.Provider = new 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));
                }
            };

            fao.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(fao);
        }
Example #56
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, 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 <UserService>(UserService.Create);
            app.CreatePerOwinContext <ProfileService>(ProfileService.Create);
            app.CreatePerOwinContext <DashboardService>(DashboardService.Create);
            app.CreatePerOwinContext <MilestoneService>(MilestoneService.Create);
            app.CreatePerOwinContext <NotificationService>(NotificationService.Create);
            app.CreatePerOwinContext <SearchService>(SearchService.Create);
            app.CreatePerOwinContext <StoreService>(StoreService.Create);
            app.CreatePerOwinContext <TriviaService>(TriviaService.Create);
            app.CreatePerOwinContext <ViolationService>(ViolationService.Create);

            app.UseKentorOwinCookieSaver();

            // 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
                {
                    OnException = context => { },
                    // 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 = async context =>
                    {
                        await SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))(context);

                        // each time the user's identity is validated, we want to refresh the last time they were logged in
                        // this is used to display how active the user is to other people in the community
                        if (context.Identity != null)
                        {
                            var userService = context.OwinContext.Get <UserService>();
                            await userService.SetUserLastLoginByIdAsync(context.Identity.GetUserId());
                        }
                    }
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

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

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

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

            app.UseTwitterAuthentication(
                consumerKey: ConfigurationManager.AppSettings["twitterConsumerKey"],
                consumerSecret: ConfigurationManager.AppSettings["twitterConsumerSecret"]);

            app.UseFacebookAuthentication(
                appId: ConfigurationManager.AppSettings["facebookAppId"],
                appSecret: ConfigurationManager.AppSettings["facebookAppSecret"]);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["googleClientId"],
                ClientSecret = ConfigurationManager.AppSettings["googleClientSecret"]
            });
        }
Example #57
0
        // For more information on configuring authentication, please visit https://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // 1 要求につき 1 インスタンスのみを使用するように DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // アプリケーションが Cookie を使用して、サインインしたユーザーの情報を格納できるようにします
            // また、サードパーティのログイン プロバイダーを使用してログインするユーザーに関する情報を、Cookie を使用して一時的に保存できるようにします
            // サインイン Cookie の設定
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。
                    // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // 2 要素認証プロセスの中で 2 つ目の要素を確認するときにユーザー情報を一時的に保存するように設定します。
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // 2 つ目のログイン確認要素 (電話や電子メールなど) を記憶するように設定します。
            // このオプションをオンにすると、ログイン プロセスの中の確認の第 2 ステップは、ログインに使用されたデバイスに保存されます。
            // これは、ログイン時の「このアカウントを記憶する」オプションに似ています。
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // 次の行のコメントを解除して、サード パーティのログイン プロバイダーを使用したログインを有効にします
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "DJwoClEnUc9JW7iwcsBc7PyWU",
                ConsumerSecret = "MV7xyyLA50ufbgXTb9mZ7d94c81D8LIv60iRCZuxWanUA0rtfV",
                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
                    "add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                })
            });

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Example #58
0
        public void Configuration(IAppBuilder app)
        {
            var logger = app.CreateLogger("Katana.Sandbox.WebServer");

            logger.WriteInformation("Application Started");

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

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

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

            app.SetDefaultSignInAsAuthenticationType("External");

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

            app.UseFacebookAuthentication(new FacebookAuthenticationOptions
            {
                AppId                   = "454990987951096",
                AppSecret               = "ca7cbddf944f91f23c1ed776f265478e",
                AuthorizationEndpoint   = "https://www.facebook.com/v2.2/dialog/oauth",
                TokenEndpoint           = "https://graph.facebook.com/v2.2/oauth/access_token",
                UserInformationEndpoint = "https://graph.facebook.com/v2.2/me"
                                          // Scope = "email user_birthday user_website"
            });

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

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

            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();
                    // 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();
                // 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 #59
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);

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

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

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

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

            //Get config values
            string fbID          = System.Configuration.ConfigurationManager.AppSettings["fbID"];
            string fbSecret      = System.Configuration.ConfigurationManager.AppSettings["fbSecret"];
            string gcID          = System.Configuration.ConfigurationManager.AppSettings["gcID"];
            string gcSecret      = System.Configuration.ConfigurationManager.AppSettings["gcSecret"];
            string lic           = System.Configuration.ConfigurationManager.AppSettings["lic"];
            string liSecret      = System.Configuration.ConfigurationManager.AppSettings["liSecret"];
            string twKey         = System.Configuration.ConfigurationManager.AppSettings["twKey"];
            string twSecret      = System.Configuration.ConfigurationManager.AppSettings["twSecret"];
            string inKey         = System.Configuration.ConfigurationManager.AppSettings["inKey"];
            string inSecret      = System.Configuration.ConfigurationManager.AppSettings["inSecret"];
            string DeviantKey    = System.Configuration.ConfigurationManager.AppSettings["DeviantKey"];
            string DeviantSecret = System.Configuration.ConfigurationManager.AppSettings["DeviantSecret"];
            string ORCIDKey      = System.Configuration.ConfigurationManager.AppSettings["ORCIDKey"];
            string ORCIDSecret   = System.Configuration.ConfigurationManager.AppSettings["ORCIDSecret"];
            string DBKey         = System.Configuration.ConfigurationManager.AppSettings["DBKey"];
            string DBSecret      = System.Configuration.ConfigurationManager.AppSettings["DBSecret"];


            app.UseFacebookAuthentication(
                appId: fbID,
                appSecret: fbSecret);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = gcID,
                ClientSecret = gcSecret
            });

            app.UseLinkedInAuthentication(lic, liSecret);

            app.UseTwitterAuthentication(
                consumerKey: twKey,
                consumerSecret: twSecret);

            app.UseInstagramInAuthentication(inKey, inSecret);

            app.UseDropboxAuthentication(
                appKey: DBKey,
                appSecret: DBSecret);

            app.UseOrcidAuthentication(ORCIDKey, ORCIDSecret);

            app.UseDeviantArtAuthentication(DeviantKey, DeviantSecret);
        }
Example #60
0
        // 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください
        public void ConfigureAuth(IAppBuilder app)
        {
            // 1 要求につき 1 インスタンスのみを使用するように DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create);

            // アプリケーションが Cookie を使用して、サインインしたユーザーの情報を格納できるようにします
            // また、サードパーティのログイン プロバイダーを使用してログインするユーザーに関する情報を、Cookie を使用して一時的に保存できるようにします
            // サインイン Cookie の設定
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath          = new PathString("/Account/Login"),
                Provider           = new CookieAuthenticationProvider
                {
                    // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。
                    // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。
                    OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>(
                        validateInterval: TimeSpan.FromMinutes(30),
                        regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // 2 要素認証プロセスの中で 2 つ目の要素を確認するときにユーザー情報を一時的に保存するように設定します。
            app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5));

            // 2 つ目のログイン確認要素 (電話や電子メールなど) を記憶するように設定します。
            // このオプションをオンにすると、ログイン プロセスの中の確認の第 2 ステップは、ログインに使用されたデバイスに保存されます。
            // これは、ログイン時の「このアカウントを記憶する」オプションに似ています。
            app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie);

            // 次の行のコメントを解除して、サード パーティのログイン プロバイダーを使用したログインを有効にします
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "",
            //    clientSecret: "");


            app.UseTwitterAuthentication(
                new TwitterAuthenticationOptions()
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"],
                Provider       = new TwitterAuthenticationProvider
                {
#pragma warning disable CS1998 // 非同期メソッドは、'await' 演算子がないため、同期的に実行されます
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstoken", context.AccessToken));
                        context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstokensecret",
                                                            context.AccessTokenSecret));
                    }
#pragma warning restore CS1998 // 非同期メソッドは、'await' 演算子がないため、同期的に実行されます
                },
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47",
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5",
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD",
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5",
                    "5168FF90AF0207753CCCD9656462A212B859723B",
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"
                })
            });

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }