public IEnumerable <OwinMiddlewareRegistration> GetOwinMiddlewares() { var settings = _workContextAccessor.GetContext().CurrentSite.As <TwitterSettingsPart>(); if (settings == null || !settings.IsValid()) { return(Enumerable.Empty <OwinMiddlewareRegistration>()); } var twitterOptions = new TwitterAuthenticationOptions { ConsumerKey = settings.ConsumerKey, ConsumerSecret = settings.ConsumerSecret, BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[] { settings.VeriSignClass3SecureServerCA_G2, settings.VeriSignClass3SecureServerCA_G3, settings.VeriSignClass3PublicPrimaryCA_G5, settings.SymantecClass3SecureServerCA_G4, settings.DigiCertSHA2HighAssuranceServerCA, settings.DigiCertHighAssuranceEVRootCA }) }; return(new List <OwinMiddlewareRegistration> { new OwinMiddlewareRegistration { Priority = Constants.General.OpenIdOwinMiddlewarePriority, Configure = app => { app.UseTwitterAuthentication(twitterOptions); } } }); }
public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Login/SignIn") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure social authentication: Twitter var naaeTwitterKey = ConfigurationManager.AppSettings["naa4e:twitter:key"]; var naaeTwitterSecret = ConfigurationManager.AppSettings["naa4e:twitter:sec"]; if (!Globals.IsAnyNullOrEmpty(naaeTwitterKey, naaeTwitterSecret)) { var twitterOptions = new TwitterAuthenticationOptions { ConsumerKey = naaeTwitterKey, ConsumerSecret = naaeTwitterSecret, Provider = new TwitterAuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstoken", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstokensecret", context.AccessTokenSecret)); return(Task.FromResult(0)); } } }; app.UseTwitterAuthentication(twitterOptions); } // Configure social authentication: Facebook var naaeFbKey = ConfigurationManager.AppSettings["naa4e:fb:key"]; var naaeFbSecret = ConfigurationManager.AppSettings["naa4e:fb:sec"]; if (!Globals.IsAnyNullOrEmpty(naaeFbKey, naaeFbSecret)) { var fbOptions = new FacebookAuthenticationOptions { AppId = naaeFbKey, AppSecret = naaeFbSecret, Provider = new FacebookAuthenticationProvider { OnAuthenticated = (context) => { // Gives you email, ID (to get profile pic), full name, and more context.Identity.AddClaim(new Claim("urn:facebook:access_token", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:facebook:email", context.Email)); return(Task.FromResult(0)); } } }; fbOptions.Scope.Add("email"); app.UseFacebookAuthentication(fbOptions); } }
public static void ConfigureSocialIdentityProviders(IAppBuilder app, string signInAsType) { var google = new GoogleAuthenticationOptions { AuthenticationType = "Google", SignInAsAuthenticationType = signInAsType }; app.UseGoogleAuthentication(google); var fb = new FacebookAuthenticationOptions { AuthenticationType = "Facebook", SignInAsAuthenticationType = signInAsType, AppId = "676607329068058", AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63" }; app.UseFacebookAuthentication(fb); var twitter = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", SignInAsAuthenticationType = signInAsType, ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq", ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM" }; app.UseTwitterAuthentication(twitter); }
public static void ConfigureAdditionalIdentityProviders(IAppBuilder app, string signInAsType) { var google = new GoogleOAuth2AuthenticationOptions { AuthenticationType = "Google", SignInAsAuthenticationType = signInAsType, ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com", ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze" }; app.UseGoogleAuthentication(google); var fb = new FacebookAuthenticationOptions { AuthenticationType = "Facebook", SignInAsAuthenticationType = signInAsType, AppId = "676607329068058", AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63" }; app.UseFacebookAuthentication(fb); var twitter = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", SignInAsAuthenticationType = signInAsType, ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq", ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM" }; app.UseTwitterAuthentication(twitter); }
public ExternalIdentityProviderService WithTwitterAuthentication(string clientId, string clientSecret) { if (string.IsNullOrWhiteSpace(clientId)) { throw new ArgumentNullException(nameof(clientId)); } if (string.IsNullOrEmpty(clientSecret)) { throw new ArgumentNullException(nameof(clientId)); } configurators.Add((appBuilder, signInAsType) => { var twitter = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", SignInAsAuthenticationType = signInAsType, ConsumerKey = clientId, ConsumerSecret = clientSecret }; appBuilder.UseTwitterAuthentication(twitter); }); return(this); }
public LocustThirdPartyOptions() { MicrosoftAccount = new MicrosoftAccountAuthenticationOptions(); Twitter = new TwitterAuthenticationOptions(); Facebook = new FacebookAuthenticationOptions(); Google = new GoogleOAuth2AuthenticationOptions(); }
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); //Bearer authentication init OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); app.UseOAuthBearerAuthentication(OAuthBearerOptions); #region Google authentication configurations GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["authConfig:GoogleClientId"], ClientSecret = ConfigurationManager.AppSettings["authConfig:GoogleClientSecret"], Provider = new GoogleAuthProvider() }; app.UseGoogleAuthentication(GoogleAuthOptions); #endregion #region Twitter authentication configurations TwitterAuthOptions = new TwitterAuthenticationOptions() { ConsumerKey = ConfigurationManager.AppSettings["authConfig:TwitterConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["authConfig:TwitterConsumerSecret"], 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 "5168FF90AF0207753CCCD9656462A212B859723B", //DigiCert SHA2 High Assurance Server CA "B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High Assurance EV Root CA }) }; app.UseTwitterAuthentication(TwitterAuthOptions); #endregion #region Vkontakte authentication configurations VkontakteAuthOptions = new VkAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["authConfig:VkontakteClientId"], ClientSecret = ConfigurationManager.AppSettings["authConfig:VkontakteClientSecret"], Scope = new List <string>() { "email" }, Provider = new VkontakteAuthProvider() }; app.UseVkontakteAuthentication(VkontakteAuthOptions); #endregion }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Allow all CORS requests app.UseCors(CorsOptions.AllowAll); // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(RestContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), // In production mode set AllowInsecureHttp = false AllowInsecureHttp = true }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers var microsoftAuthentication = new MicrosoftAccountAuthenticationOptions(); microsoftAuthentication.ClientId = "000000004C16836C"; microsoftAuthentication.ClientSecret = "R2GPxr8k-dIftBnAEhLRXLjuTsiIxNpl"; app.UseMicrosoftAccountAuthentication(microsoftAuthentication); var twitterAuthentication = new TwitterAuthenticationOptions(); twitterAuthentication.ConsumerKey = "wOS8t5pPraOLwTH79OlgyttW6"; twitterAuthentication.ConsumerSecret = "gj9iMcmsixA8UvcsTRqxxoCkzkrpDKc4vuzKGpFjTRiNv3aldl"; app.UseTwitterAuthentication(twitterAuthentication); var facebookAuthenticationOptions = new FacebookAuthenticationOptions(); facebookAuthenticationOptions.AppId = "1645027742443677"; facebookAuthenticationOptions.AppSecret = "baf2eea96164855d5e0d436c6e4c9365"; app.UseFacebookAuthentication(facebookAuthenticationOptions); var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions(); googleAuthenticationOptions.ClientId = "867920998848-h8vsdddu2o8dkv72243d8phu599dejgt.apps.googleusercontent.com"; googleAuthenticationOptions.ClientSecret = "k25jN1BX4bBtWxlNbaBMeIIk"; googleAuthenticationOptions.CallbackPath = new PathString("/signin-google"); googleAuthenticationOptions.Provider = new GoogleOAuth2AuthenticationProvider(); googleAuthenticationOptions.Scope.Add("email"); app.UseGoogleAuthentication(googleAuthenticationOptions); }
public MultiTenantTwitterOptionsResolver( TwitterAuthenticationOptions originalOptions, ISiteResolver siteResolver, ISiteRepository siteRepository, MultiTenantOptions multiTenantOptions) { this.originalOptions = originalOptions; this.siteResolver = siteResolver; this.multiTenantOptions = multiTenantOptions; siteRepo = siteRepository; }
/// <summary> /// Enables authenticating users using their Twitter account. /// </summary> /// <param name="app">The application to associate with the login provider.</param> /// <remarks> /// To use this feature, define TWITTER_ACCOUNT_LOGIN_FEATURE symbol. /// A Twitter developer account and an app needs to be created at https://dev.twitter.com/apps. /// Update ConsumerKey and ConsumerSecret values with provided client id and client secret. /// Security note: Never store sensitive data in your source code. The account and credentials are added to the code above to keep the sample simple. /// Note: Please visit https://github.com/aspnet/AspNetKatana/issues to stay on top of issues that could affect your implementation. /// </remarks> private static void EnableTwitterAccountLogin(IAppBuilder app) { // Note that the id and secret code below are fictitious and will not work when calling Twitter. var twitterOptions = new TwitterAuthenticationOptions { ConsumerKey = "<ChangeThis>", ConsumerSecret = "<ChangeThis>" }; app.UseTwitterAuthentication(twitterOptions); }
/// <summary> /// Enables authenticating users using their Twitter account. /// </summary> /// <remarks> /// To use this feature you need to have a developer account registered and an app created at Twitter. You can do all /// this at https://dev.twitter.com/apps. /// Once the app is created, copy the client id and client secret that is provided and put them as credentials in this /// method. /// Security Note: Never store sensitive data in your source code. The account and credentials are added to the code above to keep the sample simple. /// </remarks> /// <param name="app">The application to associate with the login provider.</param> private static void EnableTwitterAccountLogin(IAppBuilder app) { // Note that the id and secret code below are fictitious and will not work when calling Twitter. TwitterAuthenticationOptions twitterOptions = new TwitterAuthenticationOptions { ConsumerKey = "CqbBBscRO1jFbdr4CGRTiQFj", ConsumerSecret = "dh82r3SHGbL4ADgj6EJavdNGxFyx4YRX7QPyngBjKhV2bCdRrY" }; app.UseTwitterAuthentication(twitterOptions); }
// 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください public void ConfigureAuth(IAppBuilder app) { // 1 要求につき 1 インスタンスのみを使用するように DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。 app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); // アプリケーションが Cookie を使用して、サインインしたユーザーの情報を格納できるようにします // また、サードパーティのログイン プロバイダーを使用してログインするユーザーに関する情報を、Cookie を使用して一時的に保存できるようにします // サインイン Cookie の設定 app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。 // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。 OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); var keys = MyTokens; var options = new TwitterAuthenticationOptions(); options.ConsumerKey = keys.ConsumerKey; options.ConsumerSecret = keys.ConsumerSecret; options.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 CA "B13EC36903F8BF4701D498261A0802EF63642BC3" //DigiCert High Assurance EV Root CA }); options.Provider = new TwitterAuthenticationProvider() { #pragma warning disable CS1998 // 非同期メソッドは、'await' 演算子がないため、同期的に実行されます OnAuthenticated = async(context) => { context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); context.Identity.AddClaim(new Claim("ExternalAccessTokenSecret", context.AccessTokenSecret)); } #pragma warning restore CS1998 // 非同期メソッドは、'await' 演算子がないため、同期的に実行されます }; app.UseTwitterAuthentication(options); }
/// <summary> /// Authenticate users using Twitter /// </summary> /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param> /// <param name="options">Middleware configuration options</param> /// <returns>The updated <see cref="IAppBuilder"/></returns> public static IAppBuilder UseTwitterAuthentication(this IAppBuilder app, TwitterAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } app.Use(typeof(TwitterAuthenticationMiddleware), app, options); return(app); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); //Twitter var twitterOptions = new TwitterAuthenticationOptions(); twitterOptions.ConsumerKey = "o8QTwfzt6CdfDGndyqvLrg"; twitterOptions.ConsumerSecret = "jqU2tq5QVUkK6JdFA22wtXZNrTumatvG9VpPAfK5M"; twitterOptions.Provider = new TwitterAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("TwitterAccessToken", context.AccessToken)); context.Identity.AddClaim(new Claim("TwitterAccessSecret", context.AccessTokenSecret)); } }; app.UseTwitterAuthentication(twitterOptions); //Facebook var facebookOptions = new FacebookAuthenticationOptions(); facebookOptions.AppId = "1440310966205344"; facebookOptions.AppSecret = "0ba27f5ec1bcf335fcdf36dc19e71f86"; facebookOptions.Provider = new FacebookAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken)); } }; //we can add scope parameters here facebookOptions.Scope.Add("email"); facebookOptions.Scope.Add("user_birthday"); facebookOptions.Scope.Add("publish_stream"); facebookOptions.Scope.Add("user_photos"); app.UseFacebookAuthentication(facebookOptions); }
public async Task ChallengeWillTriggerApplyRedirectEvent() { var options = new TwitterAuthenticationOptions() { ConsumerKey = "Test Consumer Key", ConsumerSecret = "Test Consumer Secret", Provider = new TwitterAuthenticationProvider { OnApplyRedirect = context => { context.Response.Redirect(context.RedirectUri + "&custom=test"); } }, BackchannelHttpHandler = new TestHttpMessageHandler { Sender = req => { if (req.RequestUri.AbsoluteUri == "https://api.twitter.com/oauth/request_token") { return(Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent("oauth_callback_confirmed=true&oauth_token=test_oauth_token&oauth_token_secret=test_oauth_token_secret", Encoding.UTF8, "application/x-www-form-urlencoded") })); } return(Task.FromResult <HttpResponseMessage>(null)); } }, BackchannelCertificateValidator = null }; var server = CreateServer( app => app.UseTwitterAuthentication(options), context => { context.Authentication.Challenge("Twitter"); return(true); }); var transaction = await SendAsync(server, "http://example.com/challenge"); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect); var query = transaction.Response.Headers.Location.Query; query.ShouldContain("custom=test"); }
public virtual void ConfigureExternalIdentityProvider(IAppBuilder owinApp, string signInType) { if (AppEnvironment.HasConfig("TwitterClientId") && AppEnvironment.HasConfig("TwitterSecret")) { string twitterClientId = AppEnvironment.GetConfig <string>("TwitterClientId"); string twitterSecret = AppEnvironment.GetConfig <string>("TwitterSecret"); Task TwitterOnAuthenticated(TwitterAuthenticatedContext context) { context.Identity.AddClaim(new System.Security.Claims.Claim("access_token", context.AccessToken)); context.Identity.AddClaim(new System.Security.Claims.Claim("access_token_secret", context.AccessTokenSecret)); foreach (System.Security.Claims.Claim claim in context.Identity.Claims) { string claimType = $"{claim.Type}"; string claimValue = claim.Value; if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter")); } } return(Task.CompletedTask); } TwitterAuthenticationOptions twitterAuthenticationOptions = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", SignInAsAuthenticationType = signInType, ConsumerKey = twitterClientId, ConsumerSecret = twitterSecret, Provider = new TwitterAuthenticationProvider { OnAuthenticated = TwitterOnAuthenticated } }; owinApp.UseTwitterAuthentication(twitterAuthenticationOptions); } }
private static TwitterAuthenticationOptions GetTwitterAuthenticationOptions() { var options = new TwitterAuthenticationOptions { ConsumerKey = GetClientID("Twitter"), ConsumerSecret = GetClientSecret("Twitter"), Provider = new TwitterAuthenticationProvider { OnAuthenticated = (context) => { var twitterUser = Auth.ExecuteOperationWithCredentials( Auth.CreateCredentials(GetClientID("Twitter"), GetClientSecret("Twitter"), context.AccessToken, context.AccessTokenSecret), () => User.GetAuthenticatedUser(parameters: new Tweetinvi.Core.Parameters.GetAuthenticatedUserParameters() { IncludeEmail = true })); if (!string.IsNullOrWhiteSpace(twitterUser?.Email)) { context.Identity.AddClaim(new System.Security.Claims.Claim(ClaimTypes.Email, twitterUser.Email)); } return(Task.FromResult(0)); } }, // avoid invalid certificate errors, see http://stackoverflow.com/questions/36330675/get-users-email-from-twitter-api-for-external-login-authentication-asp-net-mvc BackchannelCertificateValidator = new Microsoft.Owin.Security.CertificateSubjectKeyIdentifierValidator(new[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 "add53f6680fe66e383cbac3e60922e3b4c412bed", // Symantec Class 3 EV SSL CA - G3 "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5 "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA }), }; return(options); }
/// <summary> /// Register Twitter Authentication. /// </summary> /// <param name="app"> /// The app builder. /// </param> private static void RegisterTwitterMiddleWare(IAppBuilder app) { var options = new TwitterAuthenticationOptions { ConsumerKey = Config.TwitterConsumerKey, ConsumerSecret = Config.TwitterConsumerSecret, Provider = new TwitterAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim( new Claim("urn:twitter:id", context.UserId, "XmlSchemaString", "Twitter")); context.Identity.AddClaim( new Claim("urn:twitter:name", context.ScreenName, "XmlSchemaString", "Twitter")); return(Task.FromResult(0)); } } }; app.UseTwitterAuthentication(options); }
public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType) { var google = new GoogleOAuth2AuthenticationOptions { AuthenticationType = "Google", Caption = "Google", SignInAsAuthenticationType = signInAsType, ClientId = ConfigurationManager.AppSettings["googleclientid"], ClientSecret = ConfigurationManager.AppSettings["googleclientsecret"] }; app.UseGoogleAuthentication(google); var fb = new FacebookAuthenticationOptions { AuthenticationType = "Facebook", Caption = "Facebook", SignInAsAuthenticationType = signInAsType, AppId = ConfigurationManager.AppSettings["facebookappid"], AppSecret = ConfigurationManager.AppSettings["facebookappsecret"] }; app.UseFacebookAuthentication(fb); var twitter = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", Caption = "Twitter", SignInAsAuthenticationType = signInAsType, ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq", ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM" }; app.UseTwitterAuthentication(twitter); }
/// <summary> /// 認証設定の詳細については、http://go.microsoft.com/fwlink/?LinkId=301864 を参照してください /// /// Code! MVC 5 App with Facebook, Twitter, LinkedIn /// and Google OAuth2 Sign-on (C#) | The ASP.NET Site /// http://www.asp.net/mvc/overview/security/create-an-aspnet-mvc-5-app-with-facebook-and-google-oauth2-and-openid-sign-on /// </summary> /// <param name="app">app</param> public static void Configure(IAppBuilder app) { // 1 要求につき 1 インスタンスのみを使用するように // DB コンテキスト、ユーザー マネージャー、サインイン マネージャーを構成します。 // Add to OwinContext. #region AuthenticationType // AuthenticationType: // ClaimsIdentity生成時や、AuthenticationTicket取得時に指定する。 // -------------------------------------------------- // OAuthDefaultsクラス (Microsoft.Owin.Security) // https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthdefaults.aspx // -------------------------------------------------- // - OAuthDefaults.AuthenticationType フィールド (Microsoft.Owin.Security.OAuth) // https://msdn.microsoft.com/ja-jp/library/microsoft.owin.security.oauth.oauthdefaults.authenticationtype.aspx // OAuthBearerAuthenticationOptions と OAuthAuthorizationServerOptions の AuthenticationType プロパティの既定値。 // - AuthenticationOptions.AuthenticationType プロパティ (Microsoft.Owin.Security) // https://msdn.microsoft.com/ja-jp/library/dn300391.aspx // - AuthenticationOptions.AuthenticationType プロパティ (Microsoft.Owin.Security) // https://msdn.microsoft.com/ja-jp/library/dn300391.aspx // -------------------------------------------------- // -------------------------------------------------- // DefaultAuthenticationTypes クラス (Microsoft.AspNet.Identity) // https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.aspx // -------------------------------------------------- // - ApplicationCookie // Forms認証用 Cookie認証チケット // https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.applicationcookie.aspx // - TwoFactorRememberBrowserCookie // Browser認証用 Cookie認証チケット // https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.defaultauthenticationtypes.twofactorrememberbrowsercookie.aspx // - TwoFactorCookie // TwoFactor認証用 Cookie認証チケット // https://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.defaultauthenticationtypes.twofactorcookie.aspx // - ExternalCookie // 外部ログイン Cookie認証チケット // /userinfoやid_tokenの情報をCookieに格納してある。 // https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.externalcookie.aspx // - ExternalBearer // Bearer TokenのUnprotectする際、ClaimsIdentityに指定。 // https://msdn.microsoft.com/ja-jp/library/microsoft.aspnet.identity.defaultauthenticationtypes.externalbearer.aspx // -------------------------------------------------- #endregion #region EntityFramework //app.CreatePerOwinContext(ApplicationDbContext.Create); #endregion #region EntityFramework以外 #region UserStore, ApplicationUserManager, RoleManager, SignInManagerのOwinContextを生成 // UserStoreのOwinContextを生成 app.CreatePerOwinContext <UserStore>(() => new UserStore()); // ApplicationUserManagerのOwinContextを生成 // 以下を設定する // - ユーザ名検証 // - パスワード検証 // - ユーザ ロックアウト // - 2FAプロバイダ // - 暗号化プロバイダ app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); // ApplicationRoleManagerのOwinContextを生成 app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create); // ApplicationSignInManagerのOwinContextを生成 app.CreatePerOwinContext <ApplicationSignInManager>(ApplicationSignInManager.Create); #endregion #region UseCookieAuthenticationのOwinContextを生成 // 次を設定 // - AuthenticationType // - LoginPath // - Provider // - SecurityStamp // Enable the application to use a cookie to store information for the signed in user. // and to use a cookie to temporarily store information about a user logging in with a third party login provider configure the sign in cookie. // アプリケーションがユーザのサイン・イン情報をCookie認証チケットに一時的に保存するようにします。 // また、サードパーティのプロバイダでログインするユーザ情報もCookie認証チケットを使用してできるようにします。 app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, // 認証タイプを設定する。 LoginPath = new PathString("/Account/Login"), // ログイン画面のパスを設定する。 Provider = new CookieAuthenticationProvider // 認証プロバイダを設定する(ICookieAuthenticationProvider の既定の実装)。 { #region SecurityStamp // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. // ユーザーがログインするときにセキュリティ スタンプを検証するように設定します。 // これはセキュリティ機能の 1 つであり、パスワードを変更するときやアカウントに外部ログインを追加するときに使用されます。 // -------------------------------------------------- // SecurityStampValidator.OnValidateIdentity // -------------------------------------------------- // パスワードの変更や、外部ログインを追加した際に、全てのログインセッションを // 無効化できるようCookie認証チケットに、ログインに紐付くセキュリティスタンプを埋め込んでいる。 // http://kendik.hatenablog.com/entry/2014/08/17/212645 // -------------------------------------------------- OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( // SecurityStampValidatorによる検証の間隔 validateInterval: ASPNETIdentityConfig.SecurityStampValidateIntervalFromSeconds, // ClaimsIdentityを返すdelegate regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) #endregion }, // Cookie認証チケットの有効期限 ExpireTimeSpan = ASPNETIdentityConfig.AuthCookieExpiresFromHours, // Cookie認証チケットの有効期限を半分過ぎた祭の要求で再発行(Sliding)される。 SlidingExpiration = ASPNETIdentityConfig.AuthCookieSlidingExpiration, }); #endregion #region UseExternalSignInCookieのOwinContextを生成 // 外部アイデンティティのためOWINミドルウェアベースの // Cookie認証を使用するようにアプリケーションを設定します。 app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); #endregion #region UseTwoFactor(2FA)のOwinContextを生成 #region SignInCookie(2FAのCookie認証チケット) // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. // 2FAプロセスにおいて第 2 認証要素を検証しているユーザの情報を一時的に格納するようにします。 app.UseTwoFactorSignInCookie( authenticationType: DefaultAuthenticationTypes.TwoFactorCookie, expires: ASPNETIdentityConfig.TwoFactorCookieExpiresFromHours); #endregion #region RememberBrowserCookie(2FAのブラウザ記憶) // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. // 電話や電子メールなど2FAのログイン検証係数を記憶するようにアプリケーションを設定します。 // このオプションをチェックすると、ログイン時プロセスの第二検証ステップでログインデバイス上に記憶されます。 // これは、ログイン時の「このアカウントを記憶する」オプションに似ています。 app.UseTwoFactorRememberBrowserCookie( DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); #endregion #endregion #region Use(External)AuthenticationのOwinContextを生成 // c# - Get E-mail of User Authenticated with Microsoft Account in ASP.NET Identity - Stack Overflow // http://stackoverflow.com/questions/22229593/get-e-mail-of-user-authenticated-with-microsoft-account-in-asp-net-identity #region MicrosoftAccountAuthentication if (ASPNETIdentityConfig.MicrosoftAccountAuthentication) { MicrosoftAccountAuthenticationOptions options = new MicrosoftAccountAuthenticationOptions { BackchannelHttpHandler = new WebRequestHandler() { Proxy = CreateProxy.GetInternetProxy(), UseProxy = ASPNETIdentityConfig.UseInternetProxy }, ClientId = ASPNETIdentityConfig.MicrosoftAccountAuthenticationClientId, ClientSecret = ASPNETIdentityConfig.MicrosoftAccountAuthenticationClientSecret }; // スコープを追加する。 options.Scope.Add("wl.basic"); options.Scope.Add("wl.emails"); // MicrosoftAccountAuthenticationの有効化 app.UseMicrosoftAccountAuthentication(options); } #endregion #region GoogleAuthentication if (ASPNETIdentityConfig.GoogleAuthentication) { GoogleOAuth2AuthenticationOptions options = new GoogleOAuth2AuthenticationOptions { BackchannelHttpHandler = new WebRequestHandler() { Proxy = CreateProxy.GetInternetProxy(), UseProxy = ASPNETIdentityConfig.UseInternetProxy }, ClientId = ASPNETIdentityConfig.GoogleAuthenticationClientId, ClientSecret = ASPNETIdentityConfig.GoogleAuthenticationClientSecret }; // スコープを追加する。 options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("email"); // GoogleAuthenticationの有効化 app.UseGoogleAuthentication(options); } #endregion #region FacebookAuthentication if (ASPNETIdentityConfig.FacebookAuthentication) { FacebookAuthenticationOptions options = new FacebookAuthenticationOptions { BackchannelHttpHandler = new WebRequestHandler() { Proxy = CreateProxy.GetInternetProxy(), UseProxy = ASPNETIdentityConfig.UseInternetProxy }, AppId = ASPNETIdentityConfig.FacebookAuthenticationClientId, AppSecret = ASPNETIdentityConfig.FacebookAuthenticationClientSecret, Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); return(Task.FromResult(true)); } } }; // スコープを追加する。 options.Scope.Add("email"); // FacebookAuthenticationの有効化 app.UseFacebookAuthentication(options); } #endregion #region TwitterAuthentication if (ASPNETIdentityConfig.TwitterAuthentication) { TwitterAuthenticationOptions options = new TwitterAuthenticationOptions { BackchannelHttpHandler = new WebRequestHandler() { Proxy = CreateProxy.GetInternetProxy(), UseProxy = ASPNETIdentityConfig.UseInternetProxy }, ConsumerKey = ASPNETIdentityConfig.TwitterAuthenticationClientId, ConsumerSecret = ASPNETIdentityConfig.TwitterAuthenticationClientSecret, Provider = new TwitterAuthenticationProvider { OnAuthenticated = (context) => { context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_token", context.AccessToken)); context.Identity.AddClaim(new System.Security.Claims.Claim("urn:twitter:access_secret", context.AccessTokenSecret)); return(Task.FromResult(0)); } }, BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator( new string[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA "B13EC36903F8BF4701D498261A0802EF63642BC3" } // DigiCert High Assurance EV Root CA ), }; // スコープを追加する。 // ・・・ // TwitterAuthenticationの有効化 app.UseTwitterAuthentication(options); } #endregion #endregion #region OAuth Endpointの追加 // asp.net identity - UseOAuthBearerTokens vs UseOAuthBearerAuthentication - Stack Overflow // http://stackoverflow.com/questions/28048355/useoauthbearertokens-vs-useoauthbearerauthentication // Pseudocode from source using reflector: // UseOAuthAuthorizationServer(); // authorization server middleware. // UseOAuthBearerAuthentication(); // application bearer token middleware. // UseOAuthBearerAuthentication(); // external bearer token middleware. // UseOAuthBearerTokens(); // extension method creates both the token server // // and the middleware to validate tokens for requests in the same application. // c# - ASP.Net identity: Difference between UseOAuthBearerTokens and UseCookieAuthentication? - Stack Overflow // http://stackoverflow.com/questions/22121330/asp-net-identity-difference-between-useoauthbearertokens-and-usecookieauthentic if (ASPNETIdentityConfig.EquipOAuthServer) { // OAuth Bearer Tokenを使用可能に設定する。 // UseOAuthAuthorizationServerとUseOAuthBearerTokensの違いが不明だが、 // UseOAuthAuthorizationServerだとOAuthBearerTokenEndpointPathが動かない。 #region UseOAuthAuthorizationServer /* * // -------------------------------------------------- * // OAuthAuthorizationServerを設定する。 * // -------------------------------------------------- * // OAuthAuthorizationServerExtensions.UseOAuthAuthorizationServer メソッド (Owin) * // https://msdn.microsoft.com/ja-jp/library/dn270711.aspx * // -------------------------------------------------- * // 参考:https://www.asp.net/aspnet/overview/owin-and-katana/owin-oauth-20-authorization-server * app.UseOAuthAuthorizationServer( * new OAuthAuthorizationServerOptions * { * Provider = new ApplicationOAuthAuthorizationServerProvider(), * AllowInsecureHttp = ASPNETIdentityConfig.AllowOAuthInsecureHttpEndpoints, * ApplicationCanDisplayErrors = ASPNETIdentityConfig.OAuthAuthorizeEndpointCanDisplayErrors, * AuthorizeEndpointPath = ASPNETIdentityConfig.OAuthAuthorizeEndpointPath, * AccessTokenExpireTimeSpan = ASPNETIdentityConfig.OAuthAccessTokenExpireTimeSpanFromMinutes, * * // Authorization code provider which creates and receives the authorization code. * AuthorizationCodeProvider = new AuthenticationTokenProvider * { * OnCreate = CreateAuthenticationCode, * OnReceive = ReceiveAuthenticationCode, * }, * * // Refresh token provider which creates and receives refresh token. * RefreshTokenProvider = new AuthenticationTokenProvider * { * OnCreate = CreateRefreshToken, * OnReceive = ReceiveRefreshToken, * } * }); */ #endregion #region UseOAuthBearerAuthentication // -------------------------------------------------- // Resource Server単品を実装する際のメソッドであるもよう。 // -------------------------------------------------- //app.UseOAuthBearerAuthentication( // new OAuthBearerAuthenticationOptions // { // }); #endregion #region UseOAuthBearerTokens // -------------------------------------------------- // OAuth Bearer Tokenを使用可能に設定する。 // -------------------------------------------------- // AppBuilderExtensions.UseOAuthBearerTokens Method (IAppBuilder, OAuthAuthorizationServerOptions) (Owin) // https://msdn.microsoft.com/ja-jp/library/owin.appbuilderextensions.useoauthbearertokens.aspx // -------------------------------------------------- AuthenticationTokenProvider atp = new AuthenticationTokenProvider(); // 以下のOAuth 2.0のフロー定義をサポートする。 // ・Implicitグラント種別 // ・Resource Owner Password Credentialsグラント種別 // ・Client Credentialsグラント種別 OAuthAuthorizationServerOptions oAuthAuthorizationServerOptions = new OAuthAuthorizationServerOptions { #region 全てのグラント種別の共通設定 // ・Provider // OAuthAuthorizationServerProviderの派生クラスである、 // ApplicationOAuthBearerTokenProvider(UseOAuthBearerTokens用)を設定する。 // 以下の4つのメソッドをオーバーライドする。 // ・OnValidateClientRedirectUriプロパティ設定 or ValidateClientRedirectUriのオーバーライド // ・OnValidateClientAuthenticationプロパティ設定 or ValidateClientAuthenticationのオーバーライド // ・OnGrantResourceOwnerCredentialsプロパティ設定 or GrantResourceOwnerCredentialsのオーバーライド // ・OnGrantClientCredentialsプロパティ設定 or GrantClientCredentialsのオーバーライド Provider = new ApplicationOAuthBearerTokenProvider(), //AccessTokenFormat = new AccessTokenFormatJwt(), // ・AccessTokenExpireTimeSpan(OAuth Access Token の 有効期限 AccessTokenExpireTimeSpan = ASPNETIdentityConfig.OAuthAccessTokenExpireTimeSpanFromMinutes, // System.TimeSpan.FromSeconds(10), // Debug時 // ・AllowInsecureHttp // 認証して、Token要求が http URI アドレスに届くことを許可し、 // 受信する redirect_uri 承認要求パラメータに http URI アドレスを設定する場合は true。 AllowInsecureHttp = ASPNETIdentityConfig.AllowOAuthInsecureHttpEndpoints, #endregion #region Implicitグラント種別を除く全てのグラント種別の共通設定 // ・OAuth Bearer Token の Token Endpoint TokenEndpointPath = new PathString(ASPNETIdentityConfig.OAuthBearerTokenEndpoint), #endregion #region Authorization Code, Implicitグラント種別の共通設定 // ・AuthorizeEndpointPath // OAuth の Authorize Endpoint AuthorizeEndpointPath = new PathString(ASPNETIdentityConfig.OAuthAuthorizeEndpoint), // ・ApplicationCanDisplayErrors // AuthorizeEndpointPath上でエラー メッセージを表示できるようにする。 ApplicationCanDisplayErrors = ASPNETIdentityConfig.OAuthAuthorizeEndpointCanDisplayErrors, #endregion #region Authorization Codeグラント種別 #region AuthorizationCodeProvider // 1 回だけ使用する認証コードを生成して、クライアント アプリケーションに返す。 // OnCreate または OnCreateAsync イベントによって生成されたトークンは、 // OnReceive または OnReceiveAsync イベントへの呼び出しに対して、一度だけ有効となる。 // Authorization code provider which creates and receives authorization code AuthorizationCodeProvider = new AuthenticationTokenProvider { OnCreate = AuthorizationCodeProvider.GetInstance().Create, OnReceive = AuthorizationCodeProvider.GetInstance().Receive, //OnCreateAsync = AuthorizationCodeProvider.GetInstance().CreateAsync, //OnReceiveAsync = AuthorizationCodeProvider.GetInstance().ReceiveAsync, }, #endregion #region RefreshTokenProvider // 必要に応じて、新しいAccessTokenの生成に使うことができるRefresh Tokenを生成する。 // RefreshTokenProviderが提供されない場合、OAuthBearerTokenEndpointPathからRefresh Tokenが返されない。 // Refresh token provider which creates and receives referesh token RefreshTokenProvider = new AuthenticationTokenProvider { OnCreate = RefreshTokenProvider.GetInstance().Create, OnReceive = RefreshTokenProvider.GetInstance().Receive, //OnCreateAsync = RefreshTokenProvider.GetInstance().CreateAsync, //OnReceiveAsync = RefreshTokenProvider.GetInstance().ReceiveAsync, }, #endregion #endregion }; #region Options可変部分 // AccessTokenFormat(OAuth Access Token の Format をJWTフォーマットに変更する。 oAuthAuthorizationServerOptions.AccessTokenFormat = new AccessTokenFormatJwt(); #endregion // UseOAuthBearerTokensにOAuthAuthorizationServerOptionsを設定 app.UseOAuthBearerTokens(oAuthAuthorizationServerOptions); #endregion } #endregion #endregion }
//This method is inside App_Start/Startup.Auth.cs public void ConfigureAuth(IAppBuilder app) { app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); #region Microsoft var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["MsI"], ClientSecret = ConfigurationManager.AppSettings["MsS"], Provider = new MicrosoftAccountAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:microsoft:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft")); } } } } }; microsoftAuthenticationOptions.Scope.Add("wl.basic"); microsoftAuthenticationOptions.Scope.Add("wl.emails"); microsoftAuthenticationOptions.Scope.Add("wl.birthday"); app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions); #endregion Microsoft #region Twitter var twitterAuthenticationOptions = new TwitterAuthenticationOptions() { ConsumerKey = ConfigurationManager.AppSettings["TwtI"], ConsumerSecret = ConfigurationManager.AppSettings["TwtS"], BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator( new[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5 "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA }), Provider = new TwitterAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("TwitterAccessToken", context.AccessToken)); foreach (var claim in context.UserId) { var claimType = string.Format("urn:twitter:{0}", claim); string claimValue = claim.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter")); } } } } }; app.UseTwitterAuthentication(twitterAuthenticationOptions); #endregion Twitter #region Facebook var facebookAuthenticationOptions = new FacebookAuthenticationOptions() { AppId = ConfigurationManager.AppSettings["FaceI"], AppSecret = ConfigurationManager.AppSettings["FaceS"], Provider = new FacebookAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:facebook:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook")); } } } } }; facebookAuthenticationOptions.Scope.Add("public_profile"); facebookAuthenticationOptions.Scope.Add("email"); facebookAuthenticationOptions.Scope.Add("user_birthday"); app.UseFacebookAuthentication(facebookAuthenticationOptions); #endregion Facebook #region Google var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["GglI"], ClientSecret = ConfigurationManager.AppSettings["GglS"], Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:google:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google")); } } } } }; googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email"); app.UseGoogleAuthentication(googleAuthenticationOptions); #endregion Google #region LinkedIn var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["LinkI"], ClientSecret = ConfigurationManager.AppSettings["LinkS"], Provider = new LinkedInAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedInAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:linkedin:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn")); } } } } }; app.UseLinkedInAuthentication(linkedinAuthenticationOptions); #endregion LinkedIn #region GitHub var gitAuthanticationOptions = new GitHubAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["GitI"], ClientSecret = ConfigurationManager.AppSettings["GitS"], Provider = new GitHubAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("GitHubAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:github:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "GitHub")); } } } } }; app.UseGitHubAuthentication(gitAuthanticationOptions); #endregion GitHub }
public void ConfigureOAuth(IAppBuilder app) { app.CreatePerOwinContext(DBContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create); //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create); //use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions() { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(1), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); //Configure Google External Login googleAuthOptions = new GooglePlusAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["GooglePlusClientId"], ClientSecret = ConfigurationManager.AppSettings["GooglePlusClientSecret"], Provider = new GoogleAuthProvider(), CallbackPath = new PathString("/signin-googleplus") }; // TODO uncomment to use G+ auth app.UseGooglePlusAuthentication(googleAuthOptions); string stripeClientId = ConfigurationManager.AppSettings["StripeClientId"]; string stripeClientSecret = ConfigurationManager.AppSettings["StripeClientSecret"]; stripeAuthOptions = new StripeAuthenticationOptions() { ClientId = stripeClientId, ClientSecret = stripeClientSecret, Provider = new StripeAuthProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:stripe:refreshToken", context.RefreshToken)); } }, SignInAsAuthenticationType = Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ExternalCookie }; app.UseStripeAuthentication(stripeAuthOptions); string linkedinApiKey = ConfigurationManager.AppSettings["LinkedInApiKey"]; string linkedinSecret = ConfigurationManager.AppSettings["LinkedInSecret"]; linkedinAuthOptions = new LinkedInAuthenticationOptions() { ClientId = linkedinApiKey, ClientSecret = linkedinSecret, Provider = new LinkedInAuthProvider { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie }; app.UseLinkedInAuthentication(linkedinAuthOptions); string githubClientId = ConfigurationManager.AppSettings["GithubClientId"]; string githubClientSecret = ConfigurationManager.AppSettings["GithubClientSecret"]; githubAuthOptions = new GitHubAuthenticationOptions() { ClientId = githubClientId, ClientSecret = githubClientSecret, Provider = new GitHubAuthProvider { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie }; app.UseGitHubAuthentication(githubAuthOptions); string twitterConsumerKey = ConfigurationManager.AppSettings["TwitterConsumerKey"]; string twitterConsumerSecret = ConfigurationManager.AppSettings["TwitterConsumerSecret"]; twitterAuthOptions = new TwitterAuthenticationOptions() { ConsumerKey = githubClientId, ConsumerSecret = githubClientSecret, Provider = new TwitterAuthProvider { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie }; app.UseTwitterAuthentication(twitterAuthOptions); string stackexchangeClientId = ConfigurationManager.AppSettings["StackExchangeClientId"]; string stackexchangeClientSecret = ConfigurationManager.AppSettings["StackExchangeClientSecret"]; string stackexchangeKey = ConfigurationManager.AppSettings["StackExchangeKey"]; #if DEBUG stackexchangeClientId = ConfigurationManager.AppSettings["StackExchangeClientIdDEBUG"]; stackexchangeClientSecret = ConfigurationManager.AppSettings["StackExchangeClientSecretDEBUG"]; stackexchangeKey = ConfigurationManager.AppSettings["StackExchangeKeyDEBUG"]; #endif stackexchangeAuthOptions = new StackExchangeAuthenticationOptions() { ClientId = stackexchangeClientId, ClientSecret = stackexchangeClientSecret, Key = stackexchangeKey, Provider = new StackExchangeAuthProvider { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("ExternalAccessToken", context.AccessToken)); } }, SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie }; app.UseStackExchangeAuthentication(stackexchangeAuthOptions); //Configure Facebook External Login //facebookAuthOptions = new FacebookAuthenticationOptions() //{ // AppId = "xxx", // AppSecret = "xxx", // Provider = new FacebookAuthProvider() //}; //app.UseFacebookAuthentication(facebookAuthOptions); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { var googleProvider = DependencyResolver.Current.GetService <IGoogleOAuth2AuthenticationProvider>(); var facebookProvider = DependencyResolver.Current.GetService <FacebookAuthenticationProvider>(); var twitterProvider = DependencyResolver.Current.GetService <TwitterAuthenticationProvider>(); // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <UserManager <ApplicationUser>, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(20), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthOptions); //get the configuration settings for external providers var configSection = ConfigurationSettings.Current; var twitter = configSection.ProvidersCollection[ExternalProvider.Twitter]; var facebook = configSection.ProvidersCollection[ExternalProvider.Facebook]; var google = configSection.ProvidersCollection[ExternalProvider.Google]; lock (thisObject) { OAuthBearerOptions = new OAuthBearerAuthenticationOptions { AccessTokenProvider = OAuthOptions.AccessTokenProvider }; //Configure Facebook External Login FacebookAuthOptions = new FacebookAuthenticationOptions { AppId = facebook.ConsumerKey, AppSecret = facebook.ConsumerSecret, Provider = facebookProvider }; TwitterAuthOptions = new TwitterAuthenticationOptions { ConsumerKey = twitter.ConsumerKey, ConsumerSecret = twitter.ConsumerSecret, Provider = twitterProvider }; GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions { ClientId = google.ConsumerKey, ClientSecret = google.ConsumerSecret, Provider = googleProvider }; } app.UseOAuthBearerAuthentication(OAuthBearerOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); app.UseTwitterAuthentication(TwitterAuthOptions); app.UseFacebookAuthentication(FacebookAuthOptions); app.UseGoogleAuthentication(GoogleAuthOptions); }
// 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); var twitterAuthOptions = new TwitterAuthenticationOptions { ConsumerKey = "gTABcXJyBdVpwBfTvr0giycFg", ConsumerSecret = "I2aeefsyPVh39rJS0d1hQ1gs1pg7wB0wwUeYow7nyjkuQs4Tqj", BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator(new[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", "0D445C165344C1827E1D20AB25F40163D8BE79A5", "7FD365A7C2DDECBBF03009F34339FA02AF333133", "39A55D933676616E73A761DFA16A7E59CDE66FAD", "5168FF90AF0207753CCCD9656462A212B859723B", "B13EC36903F8BF4701D498261A0802EF63642BC3" }) }; app.UseTwitterAuthentication(twitterAuthOptions); var facebookAuthOptions = new FacebookAuthenticationOptions() { AppId = "1084468928298655", AppSecret = "95cdbcd614753a0be4fba107ba54a5e0" }; // facebookAuthOptions.Scope.Add("email"); app.UseFacebookAuthentication(facebookAuthOptions); app.UseVkontakteAuthentication("5540329", "XP2pImsqpRq3cVT9jWgD", "email"); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request app.CreatePerOwinContext(ApplicationDbContext.Create); app.CreatePerOwinContext <ApplicationUserManager>(ApplicationUserManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider app.UseCookieAuthentication(new CookieAuthenticationOptions()); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; OAuthOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/api/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), AccessTokenExpireTimeSpan = TimeSpan.FromDays(14), AllowInsecureHttp = true // NOTE : When don't need SSL }; // 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: ""); var options = new TwitterAuthenticationOptions { ConsumerKey = ConfigurationManager.AppSettings["TwiiterConsumerKey"], ConsumerSecret = ConfigurationManager.AppSettings["TwiiterConsumerSecret"], 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 CA "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA }), Provider = new TwitterAuthenticationProvider { OnAuthenticated = async context => { context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesstoken", context.AccessToken)); context.Identity.AddClaim(new Claim("urn:tokens:twitter:accesssecret", context.AccessTokenSecret)); // Retrieve the OAuth access token to store for subsequent API calls string accessToken = context.AccessToken; // Retrieve the screen name (e.g. @jerriepelser) string twitterScreenName = context.ScreenName; // Retrieve the user ID var twitterUserId = context.UserId; } } }; app.UseTwitterAuthentication(options); var fbObtions = new FacebookAuthenticationOptions(); fbObtions.AppId = ConfigurationManager.AppSettings["FacebookAppId"]; fbObtions.AppSecret = ConfigurationManager.AppSettings["FacebookAppSecret"]; fbObtions.Scope.Add("email"); fbObtions.Scope.Add("publish_actions"); fbObtions.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); var claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook")); } } } }; app.UseFacebookAuthentication(fbObtions); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
// 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(SoLoudContext.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); // Token Generation app.UseOAuthBearerTokens(OAuthOptions); //app.UseOAuthAuthorizationServer(OAuthOptions); // Uncomment the following lines to enable logging in with third party login providers //app.UseMicrosoftAccountAuthentication( // clientId: "", // clientSecret: ""); var a = new TwitterAuthenticationOptions { ConsumerKey = "R8RxlH7tsQJD56fy0WTYNbUkd", ConsumerSecret = "Srpbyv1vVtyiWZx4ireJAie5ptXAN7BoDycTWbyaMpy3rs5P87", Provider = new Microsoft.Owin.Security.Twitter.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 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 CA "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA }) }; app.UseTwitterAuthentication(a); app.UseFacebookAuthentication(new FacebookAuthenticationOptions() { AppId = "1625319744433880", AppSecret = "78d4e778fac962e865fd487e5872dab2", BackchannelHttpHandler = new FacebookBackChannelHandler(), UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name", Scope = { "email", "public_profile", "publish_actions", "user_posts" }, Provider = new FacebookAuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new System.Security.Claims.Claim(SoloudClaimTypes.FacebookAccessToken.ToString(), context.AccessToken, ClaimValueTypes.String, "Facebook")); return(Task.FromResult(0)); } } }); //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); app.CreatePerOwinContext <ApplicationRoleManager>(ApplicationRoleManager.Create); // Enable the application to use a cookie to store information for the signed in user // and to use a cookie to temporarily store information about a user logging in with a third party login provider // Configure the sign in cookie app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login"), Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, ApplicationUser>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); #region Microsoft var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["MsI"], ClientSecret = ConfigurationManager.AppSettings["MsS"], Provider = new MicrosoftAccountAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:microsoft:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft")); } } } } }; microsoftAuthenticationOptions.Scope.Add("wl.basic"); microsoftAuthenticationOptions.Scope.Add("wl.emails"); microsoftAuthenticationOptions.Scope.Add("wl.birthday"); app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions); #endregion Microsoft #region Twitter var twitterAuthenticationOptions = new TwitterAuthenticationOptions() { ConsumerKey = ConfigurationManager.AppSettings["TwtI"], ConsumerSecret = ConfigurationManager.AppSettings["TwtS"], BackchannelCertificateValidator = new CertificateSubjectKeyIdentifierValidator( new[] { "A5EF0B11CEC04103A34A659048B21CE0572D7D47", // VeriSign Class 3 Secure Server CA - G2 "0D445C165344C1827E1D20AB25F40163D8BE79A5", // VeriSign Class 3 Secure Server CA - G3 "7FD365A7C2DDECBBF03009F34339FA02AF333133", // VeriSign Class 3 Public Primary Certification Authority - G5 "39A55D933676616E73A761DFA16A7E59CDE66FAD", // Symantec Class 3 Secure Server CA - G4 "4eb6d578499b1ccf5f581ead56be3d9b6744a5e5", // VeriSign Class 3 Primary CA - G5 "5168FF90AF0207753CCCD9656462A212B859723B", // DigiCert SHA2 High Assurance Server CA "B13EC36903F8BF4701D498261A0802EF63642BC3" // DigiCert High Assurance EV Root CA }), Provider = new TwitterAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("TwitterAccessToken", context.AccessToken)); foreach (var claim in context.UserId) { var claimType = string.Format("urn:twitter:{0}", claim); string claimValue = claim.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Twitter")); } } } } }; app.UseTwitterAuthentication(twitterAuthenticationOptions); #endregion Twitter #region Facebook var facebookAuthenticationOptions = new FacebookAuthenticationOptions() { AppId = ConfigurationManager.AppSettings["FaceI"], AppSecret = ConfigurationManager.AppSettings["FaceS"], Provider = new FacebookAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:facebook:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook")); } } } } }; facebookAuthenticationOptions.Scope.Add("public_profile"); facebookAuthenticationOptions.Scope.Add("email"); facebookAuthenticationOptions.Scope.Add("user_birthday"); app.UseFacebookAuthentication(facebookAuthenticationOptions); #endregion Facebook #region Google var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["GglI"], ClientSecret = ConfigurationManager.AppSettings["GglS"], Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:google:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google")); } } } } }; googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email"); app.UseGoogleAuthentication(googleAuthenticationOptions); #endregion Google #region LinkedIn var linkedinAuthenticationOptions = new LinkedInAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["LinkI"], ClientSecret = ConfigurationManager.AppSettings["LinkS"], Provider = new LinkedInAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("LinkedInAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:linkedin:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "LinkedIn")); } } } } }; app.UseLinkedInAuthentication(linkedinAuthenticationOptions); #endregion LinkedIn #region GitHub var gitAuthanticationOptions = new GitHubAuthenticationOptions() { ClientId = ConfigurationManager.AppSettings["GitI"], ClientSecret = ConfigurationManager.AppSettings["GitS"], Provider = new GitHubAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("GitHubAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:github:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "GitHub")); } } } } }; app.UseGitHubAuthentication(gitAuthanticationOptions); #endregion GitHub }
public void UseCustomLoginProvider(IAppBuilder app) { var setting = _settingService.LoadSetting <ExternalLoginProviderSettingsModel>(); var backchannelHttpHandler = new HttpClientHandler(); if (setting.UseProxy) { backchannelHttpHandler.UseProxy = true; backchannelHttpHandler.Proxy = new WebProxy(setting.ProxyServerAddress) { BypassProxyOnLocal = false, UseDefaultCredentials = false, Credentials = new NetworkCredential(setting.ProxyServerUserName, setting.ProxyServerPassword) }; } if (setting.LoginWithGoogle) { var googleOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = setting.GoogleLoginClientId, ClientSecret = setting.GoogleLoginClientSecret, BackchannelHttpHandler = backchannelHttpHandler, Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new Claim("name", context.Identity.FindFirstValue(ClaimTypes.Name))); context.Identity.AddClaim(new Claim("email", context.Identity.FindFirstValue(ClaimTypes.Email))); //This following line is need to retrieve the profile image context.Identity.AddClaim(new Claim("accesstoken", context.AccessToken, ClaimValueTypes.String, "Google")); return(Task.FromResult(0)); } } }; app.UseGoogleAuthentication(googleOptions); } if (setting.LoginWithFacebook) { //Facebook login not work on Iranian servers because Facebook.com is filter in Iran var facebookOptions = new FacebookAuthenticationOptions() { AppId = setting.FacebookLoginAppId, AppSecret = setting.FacebookLoginAppSecret, BackchannelHttpHandler = backchannelHttpHandler, UserInformationEndpoint = "https://graph.facebook.com/me?fields=id,email,first_name,last_name", Provider = new FacebookAuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:facebook:{0}", claim.Key); string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Facebook")); } } return(System.Threading.Tasks.Task.FromResult(0)); } } }; facebookOptions.SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie; facebookOptions.Scope.Add("email"); app.UseFacebookAuthentication(facebookOptions); } if (setting.LoginWithTwitter) { var twitterOptions = new TwitterAuthenticationOptions() { ConsumerKey = setting.TwitterLoginConsumerKey, ConsumerSecret = setting.TwitterLoginConsumerSecret, BackchannelHttpHandler = backchannelHttpHandler, Provider = new TwitterAuthenticationProvider() { OnAuthenticated = (context) => { var res = TwitterLogin(context.AccessToken, context.AccessTokenSecret, setting.TwitterLoginConsumerKey, setting.TwitterLoginConsumerSecret); context.Identity.AddClaim(new Claim(ClaimTypes.Email, res.Email.Trim())); context.Identity.AddClaim(new Claim(ClaimTypes.GivenName, res.FirstName.Trim())); context.Identity.AddClaim(new Claim(ClaimTypes.Surname, res.LastName.Trim())); context.Identity.AddClaim(new Claim("avatar", res.ProfileImageUrl.Trim())); return(Task.FromResult(0)); } } }; app.UseTwitterAuthentication(twitterOptions); } }
public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType) { var google = new GoogleOAuth2AuthenticationOptions { AuthenticationType = "Google", Caption = "Google", SignInAsAuthenticationType = signInAsType, ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com", ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze" }; app.UseGoogleAuthentication(google); var fb = new FacebookAuthenticationOptions { AuthenticationType = "Facebook", Caption = "Facebook", SignInAsAuthenticationType = signInAsType, AppId = "676607329068058", AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63" }; app.UseFacebookAuthentication(fb); var twitter = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", Caption = "Twitter", SignInAsAuthenticationType = signInAsType, ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq", ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM" }; app.UseTwitterAuthentication(twitter); var aad = new OpenIdConnectAuthenticationOptions { AuthenticationType = "aad", Caption = "Azure AD", SignInAsAuthenticationType = signInAsType, Authority = "https://login.windows.net/4ca9cb4c-5e5f-4be9-b700-c532992a3705", ClientId = "65bbbda8-8b85-4c9d-81e9-1502330aacba", RedirectUri = "https://localhost:44333/core/aadcb", }; app.UseOpenIdConnectAuthentication(aad); // workaround for https://katanaproject.codeplex.com/workitem/409 var metadataAddress = "https://adfs.leastprivilege.vm/federationmetadata/2007-06/federationmetadata.xml"; var manager = new SyncConfigurationManager(new ConfigurationManager <WsFederationConfiguration>(metadataAddress)); var adfs = new WsFederationAuthenticationOptions { AuthenticationType = "adfs", Caption = "ADFS", SignInAsAuthenticationType = signInAsType, CallbackPath = new PathString("/core/adfs"), ConfigurationManager = manager, Wtrealm = "urn:idsrv3" }; app.UseWsFederationAuthentication(adfs); var was = new WsFederationAuthenticationOptions { AuthenticationType = "was", Caption = "Windows", SignInAsAuthenticationType = signInAsType, CallbackPath = new PathString("/core/was"), MetadataAddress = "https://localhost:44350", Wtrealm = "urn:idsrv3" }; app.UseWsFederationAuthentication(was); }
public void ConfigureOAuth(IAppBuilder app) { DataProtectionProvider = app.GetDataProtectionProvider(); //use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); OAuthBearerOptions = new OAuthBearerAuthenticationOptions(); var OAuthServerOptions = new OAuthAuthorizationServerOptions { AllowInsecureHttp = true, TokenEndpointPath = new PathString("/token"), AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30), Provider = new SimpleAuthorizationServerProvider(), RefreshTokenProvider = new SimpleRefreshTokenProvider() }; // Token Generation app.UseOAuthAuthorizationServer(OAuthServerOptions); app.UseOAuthBearerAuthentication(OAuthBearerOptions); // Google : Create New App // https://console.developers.google.com/projectselector/apis/library if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("GoogleClientId"))) { GoogleAuthOptions = new GoogleOAuth2AuthenticationOptions { ClientId = WebConfigurationManager.AppSettings.Get("GoogleClientId"), ClientSecret = WebConfigurationManager.AppSettings.Get("GoogleClientSecret"), Provider = new GoogleAuthProvider(), CallbackPath = new PathString("/authComplete.html"), AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active, }; GoogleAuthOptions.Scope.Add("email"); app.UseGoogleAuthentication(GoogleAuthOptions); } // Facebook : Create New App // https://developers.facebook.com/apps if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("FacebookAppId"))) { FacebookAuthOptions = new FacebookAuthenticationOptions { AppId = WebConfigurationManager.AppSettings.Get("FacebookAppId"), AppSecret = WebConfigurationManager.AppSettings.Get("FacebookAppSecret"), Scope = { "email" }, Provider = new FacebookAuthProvider(), BackchannelHttpHandler = new FacebookBackChannelHandler(), UserInformationEndpoint = "https://graph.facebook.com/v2.8/me?fields=id,name,email" }; app.UseFacebookAuthentication(FacebookAuthOptions); } // Twitter : Create a new application // https://dev.twitter.com/apps if (!string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("TwitterConsumerKey"))) { var twitterOptions = new TwitterAuthenticationOptions { ConsumerKey = WebConfigurationManager.AppSettings.Get("TwitterConsumerKey"), ConsumerSecret = WebConfigurationManager.AppSettings.Get("TwitterClientSecret"), Provider = new TwitterAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new Claim("urn:twitter:access_token", context.AccessToken, XmlSchemaString, "Twitter")); return(Task.FromResult(0)); } } }; app.UseTwitterAuthentication(twitterOptions); } }