Exemplo n.º 1
0
        public static string GetAuthChallengeURL(HttpRequestBase request, FacebookAuthenticationOptions options)
        {
            string redirect_uri = CalculateRedirectURI(request, options);
            var client_id = Uri.EscapeDataString(options.AppId);
            var scope = Uri.EscapeDataString(options.Scope);

            // todo encrypt state and include a redirect URL?
            var state = Uri.EscapeDataString("");

            var url = $"{AuthorizationEndpoint}?response_type=code&client_id={client_id}&redirect_uri={redirect_uri}&scope={scope}&state={state}";

            return url;
        }
Exemplo n.º 2
0
        public static FacebookAccessToken ExchangeCodeForAccessToken(HttpRequestBase request, FacebookAuthenticationOptions options, string code)
        {
            string redirect_uri = CalculateRedirectURI(request, options);
            var client_id = Uri.EscapeDataString(options.AppId);
            var client_secret = Uri.EscapeDataString(options.AppSecret);

            var getAccessTokenURL = $"{TokenEndpoint}?grant_type=authorization_code&client_id={client_id}&client_secret={client_secret}&redirect_uri={redirect_uri}&code={code}";
            var getAccessTokenResponse = ExecuteHttpGET(getAccessTokenURL);
            var parsedAccessTokenResponse = HttpUtility.ParseQueryString(getAccessTokenResponse);
            var accessToken = parsedAccessTokenResponse["access_token"];
            var expires = int.Parse(parsedAccessTokenResponse["expires"]);

            var appsecret_proof = GenerateAppSecretProof(accessToken, client_secret);
            var getUserInfoURL = $"{UserInformationEndpoint}?access_token={Uri.EscapeDataString(accessToken)}&appsecret_proof={Uri.EscapeDataString(appsecret_proof)}";
            var getUserInfoResponse = ExecuteHttpGET(getUserInfoURL);
            var userInfo = JObject.Parse(getUserInfoResponse);
            return new FacebookAccessToken(accessToken, expires, userInfo);
        }
Exemplo n.º 3
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 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フォーマットに変更する。
                if (ASPNETIdentityConfig.EnableCustomTokenFormat)
                {
                    oAuthAuthorizationServerOptions.AccessTokenFormat = new AccessTokenFormatJwt();
                }
                #endregion

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

                #endregion
            }

            #endregion

            #endregion
        }
Exemplo n.º 4
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
        }
Exemplo n.º 5
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
        }
Exemplo n.º 6
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
            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: "",
            //    clientSecret: "");

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


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

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "1147567228663793",
                AppSecret = "2408fceb49e72ff0e2e4a9810e72a9ce",
                Provider  = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return(Task.FromResult(true));
                    }
                }
            };

            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("user_friends");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);


            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
        // 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: "",
            //   consumerSecret: "");

            var options = new FacebookAuthenticationOptions
            {
                AppId     = "293544134428341",
                AppSecret = "b0c7bd10734fb3d9c990a52b21d63bf3"
            };

            options.Scope.Add("public_profile");
            options.Scope.Add("email");

            //add this for facebook to actually return the email and name
            options.Fields.Add("email");
            options.Fields.Add("name");

            app.UseFacebookAuthentication(options);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "804689771686-gfan9lc71jstjt45ir3lut3arv71gf7q.apps.googleusercontent.com",
                ClientSecret = "HjhMftT8H-ocWJ9De2iRHplY"
            });
        }
Exemplo n.º 8
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and role manager to use a single instance per request
            app.CreatePerOwinContext(IdentityContext.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);
        }
Exemplo n.º 9
0
        // Para obtener más información sobre cómo configurar la autenticación, visite https://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, AppUser>(
                        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: "",
            //    clientSecret: "");

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

            #region Facebook
            var fbAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "",
                AppSecret = "",
            };
            fbAuthOptions.Scope.Add("email");
            fbAuthOptions.Scope.Add("public_profile");
            fbAuthOptions.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                        }
                    }
                }
            };
            fbAuthOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(fbAuthOptions);
            #endregion

            #region Google
            var googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "",
                ClientSecret = ""
            };
            googleAuthOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseGoogleAuthentication(googleAuthOptions);
            #endregion
        }
        // 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: "",
            //   consumerSecret: "");
            FacebookAuthenticationOptions facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = (ctx) =>
                    {
                        ctx.Identity.AddClaim(new Claim("fb_access_token", ctx.AccessToken, ClaimValueTypes.String, "Facebook"));
                        return(Task.FromResult(0));
                    }
                }
            };

            facebookAuthenticationOptions.Scope.Add("pages_show_list");

            InstagramAuthenticationOptions instagramAuthenticationOptions = new
                                                                            InstagramAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["InstagramClientId"],
                ClientSecret = ConfigurationManager.AppSettings["InstagramClientSecret"]
            };

            app.UseFacebookAuthentication(facebookAuthenticationOptions);
            app.UseInstagramInAuthentication(instagramAuthenticationOptions);
            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 11
0
        private void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType         = "Google",
                Caption                    = "Sign-in with Google",
                SignInAsAuthenticationType = signInAsType,

                ClientId     = ConfigurationManager.AppSettings["GoogleClientId"],
                ClientSecret = ConfigurationManager.AppSettings["GoogleClientSecret"]
            });

            var fb = new FacebookAuthenticationOptions
            {
                AuthenticationType         = "Facebook",
                Caption                    = "Sign-in with Facebook",
                SignInAsAuthenticationType = signInAsType,

                AppId     = ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"],
                Provider  = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = (context) =>
                    {
                        context.Identity.AddClaim(
                            new System.Security.Claims.Claim(
                                "urn:facebook:access_token",
                                context.AccessToken, ClaimValueTypes.String, "Facebook"));

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

            fb.Scope.Add("email");
            app.UseFacebookAuthentication(fb);

            //var y = new YahooAuthenticationOptions()
            //{
            //    AuthenticationType = "Yahoo",
            //    Caption = "Sign-in with Yahoo",
            //    SignInAsAuthenticationType = signInAsType,
            //    Provider = new YahooAuthenticationProvider()
            //    {
            //        OnAuthenticated = (context) =>
            //        {
            //            context.Identity.AddClaim(
            //                new Claim("AccessToken", context.AccessToken)
            //                    );
            //            return Task.FromResult(0);
            //        }
            //    },
            //    ConsumerKey = ConfigurationManager.AppSettings["YahooConsumerKey"],
            //    ConsumerSecret = ConfigurationManager.AppSettings["YahooConsumerSecret"]
            //};
            //app.UseYahooAuthentication(y);

            //var pp = new PayPalAuthenticationOptions()
            //{
            //    AuthenticationType = "PayPal",
            //    Caption = "Sign-in with PayPal",
            //    SignInAsAuthenticationType = signInAsType,
            //    Provider = new PayPalAuthenticationProvider()
            //    {

            //    },
            //    ClientId = ConfigurationManager.AppSettings["PayPalClientId"],
            //    ClientSecret = ConfigurationManager.AppSettings["PayPalClientSecret"]
            //};
            //app.UsePayPalAuthentication(pp);
        }
Exemplo n.º 12
0
        private void ConfigureFacebook(IAppBuilder app)
        {
            /* -------------------------------------------------------------------------------
             * Normal configuration
             * ------------------------------------------------------------------------------- */

            //app.UseFacebookAuthentication("Your App ID", "Your App Secret");

            /* -------------------------------------------------------------------------------
             * Request extra permissions
             * ------------------------------------------------------------------------------- */

            //var options = new FacebookAuthenticationOptions
            //{
            //    AppId = "1208835509271215",
            //    AppSecret = "1abfaaf382ca042b8a91ffd74e5ff18a",
            //};
            //options.Scope.Add("user_friends");
            //app.UseFacebookAuthentication(options);

            /* -------------------------------------------------------------------------------
             * Specify an alternate callback path. In this case you need to make sure that
             * the redirect URI you specify when registering the application in Facebook
             * matches this exactly
             * ------------------------------------------------------------------------------- */

            //var options = new FacebookAuthenticationOptions
            //{
            //    AppId = "Your App ID",
            //    AppSecret = "Your App Secret",
            //    CallbackPath = new PathString("/oauth-redirect/facebook")
            //};
            //app.UseFacebookAuthentication(options);

            /* -------------------------------------------------------------------------------
             * Retrieve the access token and other user information
             * ------------------------------------------------------------------------------- */
            /*
             * ========== STEPS FOR GOOGLE OAUTH ==========
             *  1 - Create Facebook App and Get the App ID and App Secret
             *  2 - Set the OAuth Redirect URLs
             *      For localhost enable SSL. provide URLs as https://localhost:44300/signin-facebook
             */
            var options = new FacebookAuthenticationOptions
            {
                //AppId = "1208835509271215",
                //AppSecret = "1abfaaf382ca042b8a91ffd74e5ff18a",
                AppId        = ConfigurationManager.AppSettings["FACEBOOK_APP_ID"],
                AppSecret    = ConfigurationManager.AppSettings["FACEBOOK_APP_SECRET"],
                CallbackPath = new PathString("/en/signin-facebook"),
                //CallbackPath = new PathString("/en/Account/ExternalLoginCallback"),
            };

            options.Scope.Add("email");
            options.Scope.Add("public_profile");
            options.Fields.Add("email");
            options.Fields.Add("name");
            options.Fields.Add("picture.width(500).height(500)");
            options.Fields.Add("first_name");
            options.Fields.Add("middle_name");
            options.Fields.Add("last_name");
            //options.UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name";
            options.Provider = new FacebookAuthenticationProvider
            {
                OnAuthenticated = context =>
                {
                    // Retrieve the OAuth access token to store for subsequent API calls
                    //string accessToken = context.AccessToken;

                    // Retrieve the username
                    //string facebookUserName = context.UserName;

                    // You can even retrieve the full JSON-serialized user
                    //OAuthReponseUserFacebook User = context.User.ToObject<OAuthReponseUserFacebook>();

                    //Adding User Data Claims
                    context.Identity.AddClaim(new Claim(_ClaimTypes.ExternalProviderAccessToken, context.AccessToken));
                    context.Identity.AddClaim(new Claim(ClaimTypes.UserData, context.User.ToString()));

                    return(Task.FromResult(true));
                },
            };

            app.UseFacebookAuthentication(options);
        }
Exemplo n.º 13
0
        private static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var desc = new AuthenticationDescription();

            desc.Caption            = "Google";
            desc.AuthenticationType = "Google";
            desc.Properties["Img"]  = "<img>";

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType         = "Google",
                Caption                    = "Sign-in with Google",
                SignInAsAuthenticationType = signInAsType,
                Description                = desc,
                ClientId                   = "28751939105-qp1ud0pms2pffpu9ssji6rhhpms45bhu.apps.googleusercontent.com",
                ClientSecret               = "ul3fdy8YOi3nWmsdQ9rap6Vn"
            });

            TwitterAuthenticationOptions twitterAuthenticationOptions = new TwitterAuthenticationOptions();



            twitterAuthenticationOptions.ConsumerKey                = "9w4EYvCfs9wjfqZDeCDll4ZBg";
            twitterAuthenticationOptions.ConsumerSecret             = "jcQ35Eo8ZjQMLVOddqwB0OyzUuTPN3h8XZrjm4kFZGOCOAWFas";
            twitterAuthenticationOptions.Caption                    = "Sign-in with Twitter";
            twitterAuthenticationOptions.SignInAsAuthenticationType = signInAsType;

            twitterAuthenticationOptions.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(twitterAuthenticationOptions);


            MicrosoftAccountAuthenticationOptions microsoftAccountAuthenticationOptions = new MicrosoftAccountAuthenticationOptions();

            microsoftAccountAuthenticationOptions.ClientId     = "000000004018E347";
            microsoftAccountAuthenticationOptions.ClientSecret = "MOqHuPKgbLngN6EHrR6IR0w7779tFLyb";
            microsoftAccountAuthenticationOptions.Caption      = "Sign-in with Microsoft";
            microsoftAccountAuthenticationOptions.SignInAsAuthenticationType = signInAsType;

            app.UseMicrosoftAccountAuthentication(microsoftAccountAuthenticationOptions);

            var fa = new FacebookAuthenticationOptions()
            {
                Caption = "Sign-in with Facebook",
                SignInAsAuthenticationType = signInAsType,
                AppId     = "1585563455100467",
                AppSecret = "ff9ab6a79875e037db94701e79c57f0d"
            };

            fa.Scope.Add("email");
            fa.Scope.Add("public_profile");

            app.UseFacebookAuthentication(fa);

            //if (IdentityServer3AppSettings.AdditionalIdentityProvidersEnabled)
            //{
            //    // if google authentication is enabled.
            //    if (GoogleAuthenticationAppSettings.Enabled)
            //    {

            //    }


            //    LinkedInAuthenticationOptions linkedInAuthenticationOptions = new LinkedInAuthenticationOptions();


            //    linkedInAuthenticationOptions.ClientId = "77vc0fkijvxj8l";
            //    linkedInAuthenticationOptions.ClientSecret = "44ALEkiMBMc2rsSK";
            //    linkedInAuthenticationOptions.Caption = "Sign-in with LinkedIn";
            //    linkedInAuthenticationOptions.SignInAsAuthenticationType = signInAsType;

            //    app.UseLinkedInAuthentication(linkedInAuthenticationOptions);


            //}
        }
Exemplo n.º 14
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()
            };

            app.UseOAuthAuthorizationServer(OAuthServerOptions);
            app.UseOAuthBearerAuthentication(OAuthBearerOptions);

            googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "857698632407-2oh1dlmgvkcr3s1t7ogk2r1kvvr2t34v.apps.googleusercontent.com",
                ClientSecret = "EwDEtu5aecpoPO74wQTQNDDy",
                Provider     = new GoogleAuthProvider()
            };
            app.UseGoogleAuthentication(googleAuthOptions);

            facebookAuthOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "1050543328368934",
                AppSecret = "78145c119c1d6c64dd64bf129cc3a0c2",
                Provider  = new FacebookAuthProvider()
            };

            facebookAuthOptions.Scope.Add("email");

            app.UseFacebookAuthentication(facebookAuthOptions);

            linkedInAuthOptions = new LinkedInAuthenticationOptions()
            {
                ClientId     = "78h6qf8zyp15lg",
                ClientSecret = "I86DaIuxrfqsv3tW",
                Provider     = new LinkedInAuthProvider()
            };
            app.UseLinkedInAuthentication(linkedInAuthOptions);

            twitterAuthOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = "6hiW6eeKKWNx00xBiICcbtVlP",
                ConsumerSecret = "kI5gRkew9tf0l1itwReiFj5L7dnFwWjTRSldh5IsmnAQrNc0Yn",
                Provider       = new TwitterAuthProvider(),
                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.UseTwitterAuthentication(twitterAuthOptions);
        }
Exemplo n.º 15
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: "",
            //   consumerSecret: "");


            var faceBookOptions = new FacebookAuthenticationOptions()
            {
                AppId                      = WebConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret                  = WebConfigurationManager.AppSettings["FacebookAppSecret"],
                AuthenticationType         = LoginProviders.Facebook,
                SignInAsAuthenticationType = "ExternalCookie",
                Provider                   = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new 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 Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                            }
                        }
                    }
                }
            };

            faceBookOptions.Scope.Add("email");
            app.UseFacebookAuthentication(faceBookOptions);


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


            var googleAuthOptions = new GoogleOAuth2AuthenticationOptions();

            googleAuthOptions.ClientId     = WebConfigurationManager.AppSettings["GoogleClientId"]; //Enter your ClientId
            googleAuthOptions.ClientSecret = WebConfigurationManager.AppSettings["GoogleSecret"];   //Enter your ClientSecret
            googleAuthOptions.Provider     = new GoogleOAuth2AuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new 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 Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                        }
                    }
                }
            };

            app.UseGoogleAuthentication(googleAuthOptions);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = WebConfigurationManager.AppSettings["GoogleClientId"],
            //    ClientSecret = WebConfigurationManager.AppSettings["GoogleSecret"]
            //});
        }
Exemplo n.º 16
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, 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: "",
            //   consumerSecret: "");

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

            FacebookAuthenticationOptions facebookOptions = new FacebookAuthenticationOptions();

            facebookOptions.AppId     = "418317095278533";
            facebookOptions.AppSecret = "442c484d94364c6286709669cb99fe9d";
            //facebookOptions.CallbackPath = new PathString("/Account/ExternalLoginCallback");

            app.UseFacebookAuthentication(facebookOptions);


            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 17
0
 private static string CalculateRedirectURI(HttpRequestBase request, FacebookAuthenticationOptions options)
 {
     var requestPrefix = request.Url.GetLeftPart(UriPartial.Authority);
     var redirect_uri = requestPrefix + request.ApplicationPath.Substring(1) + options.CallbackPath;
     return Uri.EscapeDataString(redirect_uri);
 }
Exemplo n.º 18
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"),
                LoginPath = new PathString("/"),
                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: "",
            //   consumerSecret: "");

            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "483590832023997",
                AppSecret = "fa07013d244a7bf8875338feca9b4649",
                Scope     = { "email" },
                Provider  = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return(Task.FromResult(true));
                    }
                }
            };

            app.UseFacebookAuthentication(facebookAuthenticationOptions);

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "450339138853-civo77qf0v01prgg6otlmfm8j9ipcoa9.apps.googleusercontent.com",
            //    ClientSecret = "fMkOnyUq0W1OO1bZsKJVt20G"
            //});
        }
Exemplo n.º 19
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(
            //    clientIG: "",
            //    clientSecret: "");

            app.UseTwitterAuthentication(new TwitterAuthenticationOptions
            {
                ConsumerKey    = "CTkIEDpt3z2fEixn4lvM5dIyu",
                ConsumerSecret = "HkCfchy87ZqIaa2rAraQeGbwXNts04AHBqg4A3M4CHt9KazTWI",
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(
                    new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4
                    "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5
                    "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  // DigiCert High Assurance EV Root CA
                }),
                Provider = new TwitterAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        // Retrieve the OAuth access token to store for subsequent API calls
                        AccessCode       = context.AccessToken;
                        AccessCodeSecret = context.AccessTokenSecret;
                    }
                }
            });

            var options = new FacebookAuthenticationOptions
            {
                AppId     = "112069712469758",
                AppSecret = "74b14723e5be3639f851a2751f791ea4",
                SignInAsAuthenticationType = Microsoft.Owin.Security.AppBuilderSecurityExtensions.GetDefaultSignInAsAuthenticationType(app),
                Provider = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = async context =>
                    {
                        // Retrieve the OAuth access token to store for subsequent API calls
                        AccessCode = context.AccessToken;
                    }
                }
            };

            //options.Scope.Add("public_profile");
            //options.Scope.Add("email");
            options.Scope.Add("user_likes");
            app.UseFacebookAuthentication(options);

            //app.UseGoogleAuthentication();
        }
Exemplo n.º 20
0
        private void ConfigureFacebook(IAppBuilder app)
        {
            const string appId     = "345283286312425";
            const string appSecret = "447e03a0096467eb0b60483c415168d4";
            var          options   = new FacebookAuthenticationOptions
            {
                AppId     = appId,
                AppSecret = appSecret
            };

            options.Scope.Add("email");
            options.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    var userDetail = context.User;

                    string id = (dynamic)context.Id;

                    string email       = (dynamic)context.Email;
                    var    userStore   = MembershipTools.NewUserStore();
                    var    userManager = new UserManager <User>(userStore);
                    var    currentUser = userManager.FindByEmail(email);
                    if (currentUser != null)
                    {
                        var serializedUser = context.User;
                        try
                        {
                            currentUser.EmailConfirmed = true;
                            currentUser.Name           = ((dynamic)context.User).first_name.Value;
                            currentUser.Surname        = ((dynamic)context.User).last_name.Value;
                            //currentUser.RegisterDate = DateTime.Now;
                            var avatar = @"https://graph.facebook.com/" + id + "/picture?type=large";

                            var loginInfo = HttpContext.Current.GetOwinContext().Authentication.GetExternalLoginInfo();
                            if (loginInfo != null)
                            {
                                var result = userManager.AddLogin(currentUser.Id, loginInfo.Login);
                                Console.WriteLine("test");
                            }
                            await userStore.UpdateAsync(currentUser);

                            await userStore.Context.SaveChangesAsync();
                        }
                        catch (Exception ex)
                        {
                            string x = ex.StackTrace.ToString();
                        }
                    }
                    else
                    {
                        var user = new User()
                        {
                            Email    = email,
                            Name     = ((dynamic)context.User).first_name.Value,
                            Surname  = ((dynamic)context.User).last_name.Value,
                            UserName = email.Substring(0, email.IndexOf('@'))
                        };
                        userManager.Create(user, StringHelpers.GetCode().Substring(0, 6));
                        var loginInfo = HttpContext.Current.GetOwinContext().Authentication.GetExternalLoginInfo();
                        var result    = userManager.AddLogin(user.Id, loginInfo.Login);
                    }
                }
            };
            app.UseFacebookAuthentication(options);
        }
Exemplo n.º 21
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.UseFacebookAuthentication(
            //  appId: WebConfigurationManager.AppSettings["FacebookApiKey"],
            //  appSecret: WebConfigurationManager.AppSettings["FacebookApiSecret"]);

            var facebookOptions = new FacebookAuthenticationOptions()
            {
                AppId     = WebConfigurationManager.AppSettings["FacebookApiKey"],
                AppSecret = WebConfigurationManager.AppSettings["FacebookApiSecret"],
            };

            facebookOptions.Scope.Add("email");
            app.UseFacebookAuthentication(facebookOptions);

            var twitterAuthOptions = new TwitterAuthenticationOptions
            {
                ConsumerKey    = WebConfigurationManager.AppSettings["TwitterApiKey"],
                ConsumerSecret = WebConfigurationManager.AppSettings["TwitterApiSecret"],
                BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[]
                {
                    "A5EF0B11CEC04103A34A659048B21CE0572D7D47",
                    "0D445C165344C1827E1D20AB25F40163D8BE79A5",
                    "7FD365A7C2DDECBBF03009F34339FA02AF333133",
                    "39A55D933676616E73A761DFA16A7E59CDE66FAD",
                    "5168FF90AF0207753CCCD9656462A212B859723B",
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"
                })
            };

            app.UseTwitterAuthentication(twitterAuthOptions);

            app.UseVkontakteAuthentication(
                WebConfigurationManager.AppSettings["VkApiKey"],
                WebConfigurationManager.AppSettings["VkApiSecret"],
                "email");

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 22
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);

            //** TODO: use application setting to restore client key and secret *//


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


            var twitterAuthenticationOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey    = ConfigurationManager.AppSettings["TwitterConsumerKey"],
                ConsumerSecret = ConfigurationManager.AppSettings["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
                    "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server C‎A
                    "B13EC36903F8BF4701D498261A0802EF63642BC3"  //DigiCert High Assurance EV Root CA
                })
            };

            app.UseTwitterAuthentication(twitterAuthenticationOptions);



            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId                      = ConfigurationManager.AppSettings["FacebookAppId"],
                AppSecret                  = ConfigurationManager.AppSettings["FacebookAppSecret"],
                AuthenticationType         = "Facebook",
                SignInAsAuthenticationType = "ExternalCookie",
            };

            facebookAuthenticationOptions.Scope.Add("email");

            facebookAuthenticationOptions.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    foreach (var claim in context.User)
                    {
                        var    claimType  = string.Format("urn:facebook:{0}", claim.Key);
                        string claimValue = claim.Value.ToString();
                        if (!context.Identity.HasClaim(claimType, claimValue))
                        {
                            context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook"));
                        }
                    }
                }
            };
            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["GoogleClientId"],
                ClientSecret = ConfigurationManager.AppSettings["GoogleClientSecret"],
            });

            app.UseLinkedInAuthentication(new LinkedInAuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["LinkedInClientId"],
                ClientSecret = ConfigurationManager.AppSettings["LinkedInClientSecret"],
            });
        }
Exemplo n.º 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 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
            var provider = new CookieAuthenticationProvider {
                OnException = context => { }
            };

            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                Provider = provider
            });
            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         = 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(
            //    consumerKey: "",
            //    consumerSecret: "");
            var facebookProvider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = (context) =>
                {
                    // Add the email id to the claim
                    context.Identity.AddClaim(new Claim(ClaimTypes.Email, context.Email));
                    return(Task.FromResult(0));
                }
            };
            var options = new FacebookAuthenticationOptions()
            {
                AppId     = "827541077270473",
                AppSecret = "aa63a79f14dff2a568db23b90bbfd6d7",
                Provider  = facebookProvider
            };

            options.Scope.Add("email");
            app.UseFacebookAuthentication(options);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
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: "",
            //   consumerSecret: "");

            //app.UseFacebookAuthentication(
            //   appId: "",
            //   appSecret: "");
            var facebookOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "273754210133890",
                AppSecret = "6d0227c52152c04e06b91de863e4feff",
                BackchannelHttpHandler  = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,email"
            };

            facebookOptions.Scope.Add("email");
            app.UseFacebookAuthentication(facebookOptions);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = "991505607615-1fl7nvep4tgh589uat1dtv84vsvbcrjp.apps.googleusercontent.com",
                ClientSecret = "w8VZZtekNDiY0n9OZVVZlOST"
            });
        }
Exemplo n.º 26
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            const string FacebookClaimBaseName = "urn:facebook:{0}";
            const string GoogleClaimBaseName   = "urn:google:{0}";
            const string TwitterClaimBaseName  = "urn:twitter:{0}";
            const string TwitterTokensBaseName = "urn:tokens:twitter:";

            ////string TwitterAccessToken = TwitterTokensBaseName + "accesstoken";
            ////string TwitterAccessTokenSecret = TwitterTokensBaseName + "accesstokensecret";

            ////string FacebookClaimLink = String.Format(FacebookClaimBaseName, "link");
            ////string FacebookClaimId = String.Format(FacebookClaimBaseName, "id");
            ////string FacebookClaimEmail = String.Format(FacebookClaimBaseName, "email");
            ////string FacebookClaimFirstName = String.Format(FacebookClaimBaseName, "first_name");
            ////string FacebookClaimLastName = String.Format(FacebookClaimBaseName, "last_name");
            ////string FacebookClaimGender = String.Format(FacebookClaimBaseName, "gender");
            ////string FacebookClaimLocale = String.Format(FacebookClaimBaseName, "locale");
            ////string FacebookClaimTimeZone = String.Format(FacebookClaimBaseName, "timezone");
            ////string FacebookClaimUpdatedTime = String.Format(FacebookClaimBaseName, "updated_time");
            ////string FacebookClaimVerified = String.Format(FacebookClaimBaseName, "verified");
            ////string FacebookClaimBirthday = String.Format(FacebookClaimBaseName, "user_birthday");

            ////string GoogleClaimProfile = String.Format(GoogleClaimBaseName, "profile");
            ////string GoogleClaimSub = String.Format(GoogleClaimBaseName, "sub");
            ////string GoogleClaimName = String.Format(GoogleClaimBaseName, "name");
            ////string GoogleClaimGivenName = String.Format(GoogleClaimBaseName, "given_name");
            ////string GoogleClaimFamilyName = String.Format(GoogleClaimBaseName, "family_name");
            ////string GoogleClaimPicture = String.Format(GoogleClaimBaseName, "picture");
            ////string GoogleClaimEmail = String.Format(GoogleClaimBaseName, "email");
            ////string GoogleClaimEmailVerified = String.Format(GoogleClaimBaseName, "email_verified");
            ////string GoogleClaimGender = String.Format(GoogleClaimBaseName, "gender");
            ////string GoogleClaimLocale = String.Format(GoogleClaimBaseName, "locale");

            ////string TwitterClaimUserId = String.Format(TwitterClaimBaseName, "userid");
            ////string TwitterClaimScreenName = String.Format(TwitterClaimBaseName, "screenname");



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

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


            //app.MapSignalR();

            // Uncomment the following lines to enable logging in with third party login providers
            //http://localhost:24332/Account/ExternalLoginCallback
            ///
            //app.UseMicrosoftAccountAuthentication(
            //    clientId: "00000000481D1F5F",
            //    clientSecret: "2wcUbjL3Lrh8c786qFbXtbu");

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



            const string xmlSchemaString = "http://www.w3.org/2001/XMLSchema#string";

            string facebookAppId     = "217851345348916";
            string facebookAppSecret = "3a4369eecd8d978baa476a1fb9e964c5";

            var facebookOptions = new FacebookAuthenticationOptions();

            facebookOptions.AppId     = facebookAppId;
            facebookOptions.AppSecret = facebookAppSecret;
            facebookOptions.Scope.Add("email");
            //facebookOptions.Scope.Add("user_birthday");
            facebookOptions.BackchannelHttpHandler  = new FacebookBackChannelHandler();
            facebookOptions.UserInformationEndpoint = "https://graph.facebook.com/v2.7/me?fields=id,name,email,first_name,last_name";
            facebookOptions.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async facebookContext =>
                {
                    // Save every additional claim we can find in the user
                    foreach (JProperty property in facebookContext.User.Children())
                    {
                        var    claimType  = string.Format(FacebookClaimBaseName, property.Name);
                        string claimValue = (string)property.Value;
                        if (!facebookContext.Identity.HasClaim(claimType, claimValue))
                        {
                            facebookContext.Identity.AddClaim(new Claim(claimType, claimValue, xmlSchemaString, "External"));
                        }
                    }
                }
            };
            facebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;
            app.UseFacebookAuthentication(facebookOptions);


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


            string googleClientId     = "359134327838-37rl59j06tjpc29ltbsrmpem66sk809a.apps.googleusercontent.com";
            string googleClientSecret = "9TM5TEiUS6e2Egjqh5deumdp";

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions
            {
                ClientId     = googleClientId,
                ClientSecret = googleClientSecret,
                Provider     = new GoogleOAuth2AuthenticationProvider()
                {
                    //OnAuthenticated = async googleContext =>
                    // {
                    //  //   string profileClaimName = string.Format("urn:google:{0}", "profile");
                    //     foreach (JProperty property in googleContext.User.Children())
                    //     {
                    //         var claimType = string.Format(GoogleClaimBaseName, property.Name);
                    //         string claimValue = (string)property.Value;
                    //         if (!googleContext.Identity.HasClaim(claimType, claimValue))
                    //             googleContext.Identity.AddClaim(new Claim(claimType, claimValue,
                    //                   xmlSchemaString, "External"));
                    //     }
                    // }
                }
            };

            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login");
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/userinfo.email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);



            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "359134327838-37rl59j06tjpc29ltbsrmpem66sk809a.apps.googleusercontent.com",
            //    ClientSecret = "9TM5TEiUS6e2Egjqh5deumdp"
            //});
        }
Exemplo n.º 27
0
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and role manager to use a single instance per request
            //app.CreatePerOwinContext(ApplicationUserStore.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"),
                CookieName         = "VirtoCommerce.Storefront",
                //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>(
                //                TimeSpan.FromMinutes(
                //                    30),
                //                (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: "",
            //   consumerSecret: "");

            var facebookOptions = new FacebookAuthenticationOptions();

            facebookOptions.AppId     = ConfigurationManager.AppSettings["OAuth2.Facebook.AppId"];
            facebookOptions.AppSecret = ConfigurationManager.AppSettings["OAuth2.Facebook.Secret"];
            app.UseFacebookAuthentication(facebookOptions);

            var googleOptions = new GoogleOAuth2AuthenticationOptions();

            googleOptions.ClientId     = ConfigurationManager.AppSettings["OAuth2.Google.ClientId"];
            googleOptions.ClientSecret = ConfigurationManager.AppSettings["OAuth2.Google.Secret"];
            app.UseGoogleAuthentication(googleOptions);

            app.UseSiteContext();
        }
        public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType         = "Google",
                Caption                    = "Google",
                SignInAsAuthenticationType = signInAsType,

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

            app.UseGoogleAuthentication(google);

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

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

            app.UseFacebookAuthentication(fb);

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

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

            app.UseTwitterAuthentication(twitter);

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

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

            app.UseOpenIdConnectAuthentication(aad);

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

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

            app.UseWsFederationAuthentication(adfs);

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

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

            app.UseWsFederationAuthentication(was);
        }
Exemplo n.º 29
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: "Q3KhfOBjpQT1YaTwkddgmiyzN",
             * consumerSecret: "VEji8E7RjOXL0GQqA6G2g13k6nrnNYIO4jEzFSLsZKMN8qXZc5");*/


            /*app.UseFacebookAuthentication(
             * appId: "979590172101709",
             * appSecret: "b97ba9469288fed6cf8fbeb89f17efd0");*/
            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId     = "979590172101709",
                AppSecret = "b97ba9469288fed6cf8fbeb89f17efd0",
                Provider  = new FacebookAuthenticationProvider
                {
                    OnAuthenticated = context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                        return(Task.FromResult(true));
                    }
                }
            };

            // Additional facebook permissions.
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            facebookAuthenticationOptions.Scope.Add("user_friends");
            facebookAuthenticationOptions.Scope.Add("user_likes");


            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 30
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);
        }
        // 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: "",
            //    clientSecret: "");

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

            var fbAuthOpts = new FacebookAuthenticationOptions();

            fbAuthOpts.Scope.Add("email");
            fbAuthOpts.Scope.Add("user_friends");
            fbAuthOpts.Scope.Add("user_likes");
            fbAuthOpts.Scope.Add("publish_actions");

            fbAuthOpts.AppId     = "...";
            fbAuthOpts.AppSecret = "...";
            fbAuthOpts.Provider  = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                }
            };

            app.UseFacebookAuthentication(fbAuthOpts);

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

            //var facebookOptions = new FacebookAuthenticationOptions()
            //{
            //    AppId = "...",
            //    AppSecret = "...",
            //    BackchannelHttpHandler = new FacebookBackChannelHandler(),
            //    UserInformationEndpoint = "https://graph.facebook.com/v2.12me?fields=id"
            //};


            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
Exemplo n.º 32
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

            // Configure the db context and user 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
            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.FromHours(1),
                RefreshTokenProvider      = new RefreshTokenProvider(),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = false
            };

            // 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.UseTwitterAuthentication(
            //    consumerKey: "",
            //    consumerSecret: "");

            var facebookAuthOptions = new FacebookAuthenticationOptions
            {
                AppId     = ConfigurationManager.AppSettings["oauth:facebook:id"],
                AppSecret = ConfigurationManager.AppSettings["oauth:facebook:secret"],
                Provider  = new FacebookAuthProvider()
            };

            facebookAuthOptions.Scope.Add("email");
            facebookAuthOptions.Scope.Add("public_profile");

            app.UseFacebookAuthentication(facebookAuthOptions);

            var googleAuthOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["oauth:google:id"],
                ClientSecret = ConfigurationManager.AppSettings["oauth:google:secret"],

                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    // Force the account choose to show
                    OnApplyRedirect = delegate(GoogleOAuth2ApplyRedirectContext context)
                    {
                        string redirect = context.RedirectUri;
                        redirect += "&prompt=select_account";
                        context.Response.Redirect(redirect);
                    },

                    // Add claims to name, email and google access token
                    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(System.Threading.Tasks.Task.FromResult(0));
                    }
                }
            };

            app.UseGoogleAuthentication(googleAuthOptions);

            app.UseOpenIDAuthentication("https://appleid.apple.com/auth/authorize", "Apple", true);
        }
Exemplo n.º 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(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: "",
            //   consumerSecret: "");

            //https://developers.facebook.com/docs/facebook-login/permissions/v2.1#
            var facebookAuthenticationOptions = new FacebookAuthenticationOptions
            {
                AppId     = ConfigurationManager.AppSettings["Facebook.AppId"],
                AppSecret = ConfigurationManager.AppSettings["Facebook.AppSecret"]
            };

            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("user_friends");
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_about_me");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            facebookAuthenticationOptions.Scope.Add("user_education_history");
            facebookAuthenticationOptions.Scope.Add("user_hometown");
            facebookAuthenticationOptions.Scope.Add("user_location");
            facebookAuthenticationOptions.Scope.Add("user_photos");
            facebookAuthenticationOptions.Scope.Add("user_website");
            facebookAuthenticationOptions.Scope.Add("user_work_history");
            facebookAuthenticationOptions.Provider = new FacebookAuthenticationProvider()
            {
                OnAuthenticated = async context =>
                {
                    //Get the access token from FB and store it in the database and
                    //use FacebookC# SDK to get more information about the user
                    context.Identity.AddClaim(
                        new System.Security.Claims.Claim("FacebookAccessToken",
                                                         context.AccessToken));
                }
            };
            facebookAuthenticationOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie;

            app.UseFacebookAuthentication(facebookAuthenticationOptions);

            app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            {
                ClientId     = ConfigurationManager.AppSettings["Google.ClientId"],
                ClientSecret = ConfigurationManager.AppSettings["Google.ClientSecret"]
            });
        }