Ejemplo n.º 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);
        }
Ejemplo n.º 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);

           

        }
        public ExternalIdentityProviderService WithTwitterAuthentication(string clientId, string clientSecret)
        {
            if (string.IsNullOrWhiteSpace(clientId))
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            if (string.IsNullOrEmpty(clientSecret))
            {
                throw new ArgumentNullException(nameof(clientId));
            }

            configurators.Add((appBuilder, signInAsType) =>
            {
                var twitter = new TwitterAuthenticationOptions
                {
                    AuthenticationType = "Twitter",
                    SignInAsAuthenticationType = signInAsType,
                    ConsumerKey = clientId,
                    ConsumerSecret = clientSecret
                };
                appBuilder.UseTwitterAuthentication(twitter);
            });

            return this;
        }
Ejemplo n.º 5
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);
            }
        }
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Allow all CORS requests
            app.UseCors(CorsOptions.AllowAll);

            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(RestContext.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
            var microsoftAuthentication = new MicrosoftAccountAuthenticationOptions();
            microsoftAuthentication.ClientId = "000000004C16836C";
            microsoftAuthentication.ClientSecret = "R2GPxr8k-dIftBnAEhLRXLjuTsiIxNpl";
            app.UseMicrosoftAccountAuthentication(microsoftAuthentication);

            var twitterAuthentication = new TwitterAuthenticationOptions();
            twitterAuthentication.ConsumerKey = "wOS8t5pPraOLwTH79OlgyttW6";
            twitterAuthentication.ConsumerSecret = "gj9iMcmsixA8UvcsTRqxxoCkzkrpDKc4vuzKGpFjTRiNv3aldl";
            app.UseTwitterAuthentication(twitterAuthentication);

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions();
            facebookAuthenticationOptions.AppId = "1645027742443677";
            facebookAuthenticationOptions.AppSecret = "baf2eea96164855d5e0d436c6e4c9365";
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions();
            googleAuthenticationOptions.ClientId = "867920998848-h8vsdddu2o8dkv72243d8phu599dejgt.apps.googleusercontent.com";
            googleAuthenticationOptions.ClientSecret = "k25jN1BX4bBtWxlNbaBMeIIk";
            googleAuthenticationOptions.CallbackPath = new PathString("/signin-google");
            googleAuthenticationOptions.Provider = new GoogleOAuth2AuthenticationProvider();
            googleAuthenticationOptions.Scope.Add("email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);
        }
        /// <summary>
        /// Current Configuration Update all necessary settings for Twitter.
        /// Articles: http://www.oauthforaspnet.com/providers/twitter/ and 
        /// http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
        /// 
        /// Twitter credentials should be stored in: <see cref="Security/AppSettingsSecrets.config"/>.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        private IAppBuilder ConfigureTwitter(IAppBuilder app)
        {
            string TwitterCallbackPath = ClientConfigurations.AppSettings.Setting<string>("TwitterCallbackURL");

            var options = new TwitterAuthenticationOptions
            {
                ConsumerKey = ClientConfigurations.AppSettings.Setting<string>("TwitterConsumerKey"),
                ConsumerSecret = ClientConfigurations.AppSettings.Setting<string>("TwitterConsumerKey"),
                CallbackPath = new PathString(TwitterCallbackPath)
            };

            return app;
        }
        /// <summary>
        /// Authenticate users using Twitter
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="options">Middleware configuration options</param>
        /// <returns>The updated <see cref="IAppBuilder"/></returns>
        public static IAppBuilder UseTwitterAuthentication(this IAppBuilder app, TwitterAuthenticationOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            app.Use(typeof(TwitterAuthenticationMiddleware), app, options);
            return app;
        }
Ejemplo n.º 9
0
 public async Task ChallengeWillTriggerApplyRedirectEvent()
 {
     var options = new TwitterAuthenticationOptions()
     {
         ConsumerKey = "Test Consumer Key",
         ConsumerSecret = "Test Consumer Secret",
         Provider = new TwitterAuthenticationProvider
         {
             OnApplyRedirect = context =>
             {
                 context.Response.Redirect(context.RedirectUri + "&custom=test");
             }
         },
         BackchannelHttpHandler = new TestHttpMessageHandler
         {
             Sender = req =>
                 {
                     if (req.RequestUri.AbsoluteUri == "https://api.twitter.com/oauth/request_token")
                     {
                         return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)
                         {
                             Content =
                                 new StringContent("oauth_callback_confirmed=true&oauth_token=test_oauth_token&oauth_token_secret=test_oauth_token_secret",
                                     Encoding.UTF8,
                                     "application/x-www-form-urlencoded")
                         });
                     }
                     return Task.FromResult<HttpResponseMessage>(null);
                 }
         },
         BackchannelCertificateValidator = null
     };
     var server = CreateServer(
         app => app.UseTwitterAuthentication(options),
         context =>
         {
             context.Authentication.Challenge("Twitter");
             return true;
         });
     var transaction = await SendAsync(server, "http://example.com/challenge");
     transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
     var query = transaction.Response.Headers.Location.Query;
     query.ShouldContain("custom=test");
 }
Ejemplo n.º 10
0
        private static void ConfigureTwitterAuth(IAppBuilder app)
        {
            var settings = new TwitterAuthenticationOptions
            {
                ConsumerKey = ConfigurableValues.Authentication.TwitterConsumerKey,
                ConsumerSecret = ConfigurableValues.Authentication.TwitterConsumerSecret,

                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(settings);
        }
Ejemplo n.º 11
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: "");

            TwitterAuthenticationOptions twitterAuthenticationOptions = new TwitterAuthenticationOptions
            {
                ConsumerKey = WebConfigurationManager.AppSettings["TwitterAPIKey"],
                ConsumerSecret = WebConfigurationManager.AppSettings["TwitterAPISecret"],
                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.UseTwitterAuthentication(twitterAuthenticationOptions);

            app.UseFacebookAuthentication(
               appId: WebConfigurationManager.AppSettings["FacebookAppId"],
               appSecret: WebConfigurationManager.AppSettings["FacebookAppSecret"]);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = WebConfigurationManager.AppSettings["GoogleClientId"],
                ClientSecret = WebConfigurationManager.AppSettings["GoogleSecret"]
            });
        }
Ejemplo n.º 12
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);

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

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

            /* app.UseFacebookAuthentication(new FacebookAuthenticationOptions()
             * {
             *   AppId = "379050216797422",
             *   AppSecret = "e0fb119bdbb7dd6d5096b525d9da115d"
             * });
             */

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "88628182739-oashagp3v9t313qe9ckik782o94vqprc.apps.googleusercontent.com",
                ClientSecret = "6ft3kvXLqoa2wvhyHFVxG_16"
            });
            var twitterOptions = new Microsoft.Owin.Security.Twitter.TwitterAuthenticationOptions()
            {
                ConsumerKey    = "xNKsNyv31ybiN5IsMrmr0r80L",
                ConsumerSecret = "WKZ527rn7A5bD9uzpjfVwd8mJ25RClWnBzowmHkgWf6ea5g68l",

                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
                    "‎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.UseTwitterAuthentication(twitterOptions);
            twitterOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;

            var facebookOptions = new FacebookAuthenticationOptions()

            {
                AppId                   = "379050216797422",
                AppSecret               = "e0fb119bdbb7dd6d5096b525d9da115d",
                AuthorizationEndpoint   = "https://www.facebook.com/v8.0/dialog/oauth",
                BackchannelHttpHandler  = new FacebookBackChannelHandler(),
                TokenEndpoint           = "https://graph.facebook.com/v8.0/oauth/access_token",
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,pages_show_list,pages_manage_post",
                //  UserPage = ""https://graph.facebook.com/v2.4/me/accounts",


                Provider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        await Task.Run(() => 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"));
                            }
                        }
                    }
                }
            };

            facebookOptions.Scope.Add("email");
            //facebookOptions.Scope.Add("pages_manage_posts");
            //facebookOptions.Scope.Add("pages_show_list");
            //facebookOptions.Scope.Add("pages_messaging");
            //facebookOptions.Scope.Add("pages_read_user_content");
            //facebookOptions.Scope.Add("user_posts");
            //facebookOptions.Scope.Add("pages_manage_engagement");


            facebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(facebookOptions);
        }
Ejemplo n.º 13
0
        public void ConfigureOAuth(IAppBuilder app)
        {
            app.CreatePerOwinContext(DBContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create); 

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

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

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

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

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

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

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



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

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


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

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

            app.UseGitHubAuthentication(githubAuthOptions);

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

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

            app.UseTwitterAuthentication(twitterAuthOptions);


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

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

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

            app.UseStackExchangeAuthentication(stackexchangeAuthOptions);


            //Configure Facebook External Login
            //facebookAuthOptions = new FacebookAuthenticationOptions()
            //{
            //    AppId = "xxx",
            //    AppSecret = "xxx",
            //    Provider = new FacebookAuthProvider()
            //};
            //app.UseFacebookAuthentication(facebookAuthOptions);
        }
Ejemplo n.º 14
0
 private static TwitterAuthenticationOptions GetTwitterAuthenticationOptions()
 {
     var options = new TwitterAuthenticationOptions
     {
         ConsumerKey = GetClientID("Twitter"),
         ConsumerSecret = GetClientSecret("Twitter"),
         Provider = new TwitterAuthenticationProvider
         {
             OnAuthenticated = (context) =>
             {
                 var twitterUser = Auth.ExecuteOperationWithCredentials(
                     Auth.CreateCredentials(GetClientID("Twitter"), GetClientSecret("Twitter"),
                         context.AccessToken, context.AccessTokenSecret),
                     () => User.GetAuthenticatedUser(parameters: new Tweetinvi.Core.Parameters.GetAuthenticatedUserParameters()
                     {
                         IncludeEmail = true
                     }));
                 if (!string.IsNullOrWhiteSpace(twitterUser?.Email))
                 {
                     context.Identity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Email, twitterUser.Email));
                 }
                 return Task.FromResult(0);
             }
         },
         // avoid invalid certificate errors, see http://stackoverflow.com/questions/36330675/get-users-email-from-twitter-api-for-external-login-authentication-asp-net-mvc
         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
             "‎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
         }),
     };
     return options;
 }
Ejemplo n.º 15
0
 /// <summary>
 /// Enables authenticating users using their Twitter account.
 /// </summary>
 /// <remarks>
 /// To use this feature you need to have a developer account registered and an app created at Twitter. You can do all
 /// this at https://dev.twitter.com/apps.
 /// Once the app is created, copy the client id and client secret that is provided and put them as credentials in this
 /// method.
 /// Security Note: Never store sensitive data in your source code. The account and credentials are added to the code above to keep the sample simple.
 /// </remarks>
 /// <param name="app">The application to associate with the login provider.</param>
 private static void EnableTwitterAccountLogin(IAppBuilder app)
 {
     // Note that the id and secret code below are fictitious and will not work when calling Twitter.
     TwitterAuthenticationOptions twitterOptions = new TwitterAuthenticationOptions
     {
         ConsumerKey = "<ChangeThis>",
         ConsumerSecret = "<ChangeThis>"
     };
     app.UseTwitterAuthentication(twitterOptions);
 }
Ejemplo n.º 16
0
        private static void SetupTwitterAuth(IAppBuilder app)
        {
            TwitterAuthenticationOptions twitterOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey = TwitterConsumerKey,
                ConsumerSecret = TwitterConsumerSecret
            };

            app.UseTwitterAuthentication(twitterOptions);
        }
Ejemplo n.º 17
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            var googleProvider = DependencyResolver.Current.GetService<IGoogleOAuth2AuthenticationProvider>();
            var facebookProvider = DependencyResolver.Current.GetService<FacebookAuthenticationProvider>();
            var twitterProvider = DependencyResolver.Current.GetService<TwitterAuthenticationProvider>();

            // 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<UserManager<ApplicationUser>, 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);

            //get the configuration settings for external providers
            var configSection = ConfigurationSettings.Current;

            var twitter = configSection.ProvidersCollection[ExternalProvider.Twitter];
            var facebook = configSection.ProvidersCollection[ExternalProvider.Facebook];
            var google = configSection.ProvidersCollection[ExternalProvider.Google];

            lock (thisObject)
            {
                OAuthBearerOptions = new OAuthBearerAuthenticationOptions
                {
                    AccessTokenProvider = OAuthOptions.AccessTokenProvider
                };

                //Configure Facebook External Login
                FacebookAuthOptions = new FacebookAuthenticationOptions
                {
                    AppId = facebook.ConsumerKey,
                    AppSecret = facebook.ConsumerSecret,
                    Provider = facebookProvider
                };

                TwitterAuthOptions = new TwitterAuthenticationOptions
                {
                    ConsumerKey = twitter.ConsumerKey,
                    ConsumerSecret = twitter.ConsumerSecret,
                    Provider = twitterProvider
                };

                GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions
                {
                    ClientId = google.ConsumerKey,
                    ClientSecret = google.ConsumerSecret,
                    Provider = googleProvider
                };
            }

            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

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

            app.UseTwitterAuthentication(TwitterAuthOptions);
            app.UseFacebookAuthentication(FacebookAuthOptions);
            app.UseGoogleAuthentication(GoogleAuthOptions);
        }
        /// <summary>
        /// Current Configuration Update all necessary settings for Twitter.
        /// Articles: 
        /// http://www.oauthforaspnet.com/providers/twitter/
        /// http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on
        /// http://www.jerriepelser.com/blog/get-the-twitter-profile-image-using-the-asp-net-identity
        /// 
        /// Twitter credentials should be stored in: <see cref="Security/AppSettingsSecrets.config"/>.
        /// </summary>
        /// <param name="app"></param>
        /// <returns></returns>
        private TwitterAuthenticationOptions GetTwitterConfigurations()
        {
            string TwitterCallbackPath = ClientConfigurations.AppSettings.Setting<string>("TwitterCallbackURL");

            // Get Idea from http://www.jerriepelser.com/blog/get-the-twitter-profile-image-using-the-asp-net-identity
            var options = new TwitterAuthenticationOptions
            {
                ConsumerKey = TwitterSettings.ConsumerKey,
                ConsumerSecret = TwitterSettings.ConsumerSecret,
                BackchannelCertificateValidator = null,
                Provider = new TwitterAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        // These are then added as claims to the ClaimsIdentity which is available as Identity property of the context variable.
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:tokens:twitter:accesstoken", context.AccessToken));
                        context.Identity.AddClaim(new System.Security.Claims.Claim("urn:tokens:twitter:accesstokensecret", context.AccessTokenSecret));
                    }
                }
            };

            return options;
        }
 public static IAppBuilder UseTwitterAuthentication(this IAppBuilder app, TwitterAuthenticationOptions options)
 {
     app.Use(typeof(TwitterAuthenticationMiddleware), app, options);
     return app;
 }
 public override void ConfigureAuth(IAppBuilder app)
 {
     TwitterAuthenticationOptions opt=new TwitterAuthenticationOptions()
        {
        ConsumerKey = ConfigurationLoader.GetConfiguration("Twitter-ConsumerKey"),
        ConsumerSecret =  ConfigurationLoader.GetConfiguration("Twitter-ConsumerSecret")
        };
     app.UseTwitterAuthentication(opt);
 }
        public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                Caption = "Google",
                SignInAsAuthenticationType = signInAsType,
                
                ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze"
            };
            app.UseGoogleAuthentication(google);

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

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

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

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

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

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

            app.UseOpenIdConnectAuthentication(aad);
        }
Ejemplo n.º 22
0
        private static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze"
            };
            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);

            var ms = new MicrosoftAccountAuthenticationOptions
            {
                AuthenticationType = "Microsoft",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "N8r8w7PIe",
                ClientSecret = "df15L2x6kNI50E"
            };
            app.UseMicrosoftAccountAuthentication(ms);

            var github = new GitHubAuthenticationOptions()
            {
                AuthenticationType = "Github",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "N8r8w7PIe",
                ClientSecret = "df15L2x6kNI50E"
            };
            app.UseGitHubAuthentication(github);
        }
Ejemplo n.º 23
0
        public static void ConfigureAdditionalIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "405547628913-afp6rob22l602dembl7eqnseb9vmrbqs.apps.googleusercontent.com",
                ClientSecret = "ENxb5ZPcOl_BHSWfUTUQecxw",
            };
            app.UseGoogleAuthentication(google);

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

            var twitter = new TwitterAuthenticationOptions
            {
                AuthenticationType = "Twitter",
                SignInAsAuthenticationType = signInAsType,
                ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq",
                ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM"
            };
            app.UseTwitterAuthentication(twitter);
        }
Ejemplo n.º 24
0
        public void ConfigureAuth(IAppBuilder app)
        {
            DataProtectionProvider = app.GetDataProtectionProvider();

            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(DataContext.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, User>(
                                                                   TimeSpan.FromMinutes(30),
                                                                   (manager, user) =>
                                                               user.GenerateUserIdentityAsync(manager)),
                                                           //OnException = context => { }
                                                       }
                                        });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            var settings = Properties.Settings.Default;
            if (!string.IsNullOrEmpty(settings.TwitterConsumerKey) &&
                !string.IsNullOrEmpty(settings.TwitterConsumerSecret))
            {
                var twitterOptions = new TwitterAuthenticationOptions
                {
                    ConsumerKey = settings.TwitterConsumerKey,
                    ConsumerSecret = settings.TwitterConsumerSecret,
                    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(twitterOptions);
            }

            if (!string.IsNullOrEmpty(settings.FacebookAppId) &&
                !string.IsNullOrEmpty(settings.FacebookAppSecret))
            {
                var facebookOptions = new FacebookAuthenticationOptions
                {
                    AppId = settings.FacebookAppId,
                    AppSecret = settings.FacebookAppSecret
                };
                facebookOptions.Scope.Add("email");

                app.UseFacebookAuthentication(facebookOptions);
            }

            if (!string.IsNullOrEmpty(settings.GoogleClientId) &&
                !string.IsNullOrEmpty(settings.GoogleClientSecret))
            {
                var googleOptions = new GoogleOAuth2AuthenticationOptions
                {
                    ClientId = settings.GoogleClientId,
                    ClientSecret = settings.GoogleClientSecret,
                    Provider = new GoogleOAuth2AuthenticationProvider()
                    {
                        OnAuthenticated = context =>
                        {
                            context.Identity.AddClaim(new Claim("urn:google:name",
                                context.Identity.FindFirstValue(ClaimTypes.Name)));
                            context.Identity.AddClaim(new Claim("urn:google:email",
                                context.Identity.FindFirstValue(ClaimTypes.Email)));

                            // This following line is need to retrieve the profile image
                            context.Identity.AddClaim(new Claim("urn:google:accesstoken", context.AccessToken,
                                ClaimValueTypes.String, "Google"));

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

                app.UseGoogleAuthentication(googleOptions);
            }
        }
Ejemplo n.º 25
0
 /// <summary>
 /// Enables authenticating users using their Twitter account.
 /// </summary>
 /// <remarks>
 /// To use this feature you need to have a developer account registered and an app created at Twitter. You can do all
 /// this at https://dev.twitter.com/apps.
 /// Once the app is created, copy the client id and client secret that is provided and put them as credentials in this
 /// method.
 /// Security Note: Never store sensitive data in your source code. The account and credentials are added to the code above to keep the sample simple.
 /// </remarks>
 /// <param name="app">The application to associate with the login provider.</param>
 private static void EnableTwitterAccountLogin(IAppBuilder app)
 {
     // Note that the id and secret code below are fictitious and will not work when calling Twitter.
     TwitterAuthenticationOptions twitterOptions = new TwitterAuthenticationOptions
     {
         ConsumerKey = "CqbBBscRO1jFbdr4CGRTiQFj",
         ConsumerSecret = "dh82r3SHGbL4ADgj6EJavdNGxFyx4YRX7QPyngBjKhV2bCdRrY"
     };
     app.UseTwitterAuthentication(twitterOptions);
 }
Ejemplo n.º 26
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
            #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"]
            };
            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


        }
Ejemplo n.º 27
0
        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 = "667365230941-7583a180030gerdjfmkd4ai1r21sk60c.apps.googleusercontent.com",
                ClientSecret = "Z5CVgL04ML5tdfAKnL2pyJ3X",
                Provider = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            //Configure Facebook External Login
            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId = "1602131330041169",
                AppSecret = "5b6a4cda8fc3bfa9451e3d4192375706",
                Provider = new FacebookAuthProvider()
            };
            app.UseFacebookAuthentication(facebookAuthOptions);

            //Configure twitter External Login
            twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey = "FTeZwkne0gahQb86DitDuK6cK",
                ConsumerSecret = "AD7G5Dnlsx1TMqnzSC3j2W8jQ2uk24PcVFDSMDz1vk3iQqXY3q",
                Provider = new TwitterAuthenticationProvider()

            };
            app.UseFacebookAuthentication(facebookAuthOptions);
        }