private static MicrosoftAccountAuthenticationOptions GetMicrosoftAuthenticationOptions() { var options = new MicrosoftAccountAuthenticationOptions { ClientId = GetClientID("Microsoft"), ClientSecret = GetClientSecret("Microsoft"), Provider = new MicrosoftAccountAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new System.Security.Claims.Claim("urn:microsoftaccount:access_token", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:microsoftaccount:{0}", claim.Key); var claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft")); } } return(Task.FromResult(0)); } } }; options.Scope.Add("wl.emails"); options.Scope.Add("wl.basic"); return(options); }
public async Task ChallengeWillTriggerApplyRedirectEvent() { var options = new MicrosoftAccountAuthenticationOptions() { ClientId = "Test Client Id", ClientSecret = "Test Client Secret", Provider = new MicrosoftAccountAuthenticationProvider { OnApplyRedirect = context => { context.Response.Redirect(context.RedirectUri + "&custom=test"); } } }; var server = CreateServer( app => app.UseMicrosoftAccountAuthentication(options), context => { context.Authentication.Challenge("Microsoft"); 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"); }
protected override void ProcessCore([NotNull] IdentityProvidersArgs args) { Assert.ArgumentNotNull(args, nameof(args)); var identityProvider = this.GetIdentityProvider(); var authenticationType = this.GetAuthenticationType(); string clientSecret = Settings.GetSetting("Sitecore.HabitatHome.Feature.Accounts.Microsoft.ClientSecret"); //todo: move this to site-specific configuration item string clientId = Settings.GetSetting("Sitecore.HabitatHome.Feature.Accounts.Microsoft.ClientId"); //todo: move this to site-specific configuration item if (string.IsNullOrEmpty(clientSecret) || string.IsNullOrEmpty(clientId)) { return; } var options = new MicrosoftAccountAuthenticationOptions { Caption = identityProvider.Caption, AuthenticationType = authenticationType, AuthenticationMode = AuthenticationMode.Passive, ClientId = clientId, ClientSecret = clientSecret, Provider = new MicrosoftAccountAuthenticationProvider() { OnAuthenticated = (context) => Task.Run(() => { context.Identity.ApplyClaimsTransformations(new TransformationContext(this.FederatedAuthenticationConfiguration, identityProvider)); }) } }; MicrosoftAccountAuthenticationExtensions.UseMicrosoftAccountAuthentication(args.App, options); }
public LocustThirdPartyOptions() { MicrosoftAccount = new MicrosoftAccountAuthenticationOptions(); Twitter = new TwitterAuthenticationOptions(); Facebook = new FacebookAuthenticationOptions(); Google = new GoogleOAuth2AuthenticationOptions(); }
// 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 void MicrosoftAuthenticationWithProviderConfiguration(IAppBuilder app) { app.UseAuthSignInCookie(); var option = new MicrosoftAccountAuthenticationOptions() { ClientId = "000000004C0F442C", ClientSecret = "EkXbW-Vr6Rqzi6pugl1jWIBsDotKLmqR", Provider = new MicrosoftAccountAuthenticationProvider() { OnAuthenticated = async context => { await Task.Run(() => { Assert.Equal <string>("ValidAccessToken", context.AccessToken); Assert.Equal <string>("ValidRefreshToken", context.RefreshToken); Assert.Equal <string>("Owinauthtester", context.FirstName); Assert.Equal <string>("fccf9a24999f4f4f", context.Id); Assert.Equal <string>("Owinauthtester", context.LastName); Assert.Equal <string>("Owinauthtester Owinauthtester", context.Name); Assert.NotNull(context.User); Assert.Equal <string>(context.Id, context.User.SelectToken("id").ToString()); context.Identity.AddClaim(new Claim("Authenticated", "true")); }); }, OnReturnEndpoint = async context => { await Task.Run(() => { if (context.Identity != null && context.SignInAsAuthenticationType == "Application") { context.Identity.AddClaim(new Claim("ReturnEndpoint", "true")); context.Identity.AddClaim(new Claim(context.Identity.RoleClaimType, "Guest", ClaimValueTypes.String)); } else if (context.Identity == null) { context.Identity = new ClaimsIdentity("Microsoft", "Name_Failed", "Role_Failed"); context.SignInAsAuthenticationType = "Application"; } }); }, OnApplyRedirect = context => { context.Response.Redirect(context.RedirectUri + "&custom_redirect_uri=custom"); } }, BackchannelHttpHandler = new MicrosoftChannelHttpHandler(), BackchannelCertificateValidator = new CustomCertificateValidator(), StateDataFormat = new CustomStateDataFormat(), }; option.Scope.Add("wl.basic"); option.Scope.Add("wl.signin"); app.UseMicrosoftAccountAuthentication(option); app.UseExternalApplication("Microsoft"); }
protected override void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app) { var options = new MicrosoftAccountAuthenticationOptions(); options.Scope.Add("wl.emails"); options.Scope.Add("wl.signin"); Config.ApplyToOwinSecurityOptions(options); app.UseMicrosoftAccountAuthentication(options); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/Account/Login") }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Uncomment the following lines to enable logging in with third party login providers var msAuthOptions = new MicrosoftAccountAuthenticationOptions(); msAuthOptions.Scope.Add("wl.basic"); msAuthOptions.Scope.Add("wl.emails"); msAuthOptions.ClientId = ConfigurationManager.AppSettings["msClientId"]; msAuthOptions.ClientSecret = ConfigurationManager.AppSettings["msClientSecret"]; app.UseMicrosoftAccountAuthentication(msAuthOptions); // app.UseTwitterAuthentication( // consumerKey: ConfigurationManager.AppSettings["consumerKey"], // consumerSecret: ConfigurationManager.AppSettings["consumerSecret"] // ); var fbAuthOptions = new FacebookAuthenticationOptions { AppId = ConfigurationManager.AppSettings["fbAppId"], AppSecret = ConfigurationManager.AppSettings["fbAppSecret"] }; fbAuthOptions.Scope.Add("email"); fbAuthOptions.Scope.Add("public_profile"); fbAuthOptions.Scope.Add("user_friends"); fbAuthOptions.Provider = new FacebookAuthenticationProvider { OnAuthenticated = context => { context.Identity.AddClaim(new Claim("FacebookAccessToken", context.AccessToken)); return(Task.FromResult(true)); } }; app.UseFacebookAuthentication(fbAuthOptions); app.UseGoogleAuthentication( clientId: ConfigurationManager.AppSettings["googleClientId"], clientSecret: ConfigurationManager.AppSettings["googleClientSecret"] ); app.UseLinkedInAuthentication(new LinkedInAuthenticationOptions { ClientId = ConfigurationManager.AppSettings["linkedinClientId"], ClientSecret = ConfigurationManager.AppSettings["linkedinClientSecret"] }); }
public MultiTenantMicrosoftOptionsResolver( MicrosoftAccountAuthenticationOptions originalOptions, ISiteResolver siteResolver, ISiteRepository siteRepository, MultiTenantOptions multiTenantOptions) { this.originalOptions = originalOptions; this.siteResolver = siteResolver; this.multiTenantOptions = multiTenantOptions; siteRepo = siteRepository; }
private static void EnableMicrosoftAuth(IAppBuilder app) { var microSoftAuthOpt = new MicrosoftAccountAuthenticationOptions(); microSoftAuthOpt.ClientId = Credentials.Microsoft_Id; microSoftAuthOpt.ClientSecret = Credentials.Microsoft_Secret; microSoftAuthOpt.Scope.Add("wl.emails"); microSoftAuthOpt.Provider = new MicrosoftOAuthProvider(); app.UseMicrosoftAccountAuthentication(microSoftAuthOpt); }
/// <summary> /// Enables authenticating users using their Microsoft account. /// </summary> /// <remarks> /// To use this feature you need to have a developer account registered and an app created at Microsoft. You can do all /// this at https://account.live.com/developers/applications. /// 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 EnableMicrosoftAccountLogin(IAppBuilder app) { // Note that the id and secret code below are fictitious and will not work when calling Microsoft. MicrosoftAccountAuthenticationOptions microsoftOptions = new MicrosoftAccountAuthenticationOptions { ClientId = "0000000049673D31", ClientSecret = "hkQB8uwZ55HrkIcpeU9J6tXXebrMUpOS" }; microsoftOptions.Scope.Add("email"); app.UseMicrosoftAccountAuthentication(microsoftOptions); }
/// <summary> /// Enables authenticating users using their Microsoft account. /// </summary> /// <param name="app">The application to associate with the login provider.</param> /// <remarks> /// To use this feature, define MICROSOFT_ACCOUNT_LOGIN_FEATURE symbol. /// A Microsoft developer account and an app needs to be created at https://account.live.com/developers/applications. /// Update ClientId and ClientSecret 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 EnableMicrosoftAccountLogin(IAppBuilder app) { // Note that the id and secret code below are fictitious and will not work when calling Microsoft. var microsoftOptions = new MicrosoftAccountAuthenticationOptions { ClientId = "<ChangeThis>", ClientSecret = "<ChangeThis>" }; microsoftOptions.Scope.Add("email"); app.UseMicrosoftAccountAuthentication(microsoftOptions); }
public void Configuration(IAppBuilder app) { // --- Cookie authentication --- var cookieOptions = new CookieAuthenticationOptions { LoginPath = new PathString("/login.aspx"), ExpireTimeSpan = new TimeSpan(1, 0, 0), CookieName = "myauth.cookie", // I don't know why but it must have a dot in the name: // .myid or myid.abc or something else with a "." }; app.UseCookieAuthentication(cookieOptions); app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType); // --- Google authentication --- app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions { ClientId = ConfigurationManager.AppSettings["GoogleClientID"], ClientSecret = ConfigurationManager.AppSettings["GoogleClientSecret"], Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = context => { context.Identity.AddClaim(new Claim(MyClaims.MyProviderID, "Google")); return(Task.FromResult <object>(null)); } } }); // --- Microsoft authentication --- var microsoftOptions = new MicrosoftAccountAuthenticationOptions { ClientId = ConfigurationManager.AppSettings["MicrosoftClientID"], ClientSecret = ConfigurationManager.AppSettings["MicrosoftClientSecret"], Provider = new MicrosoftAccountAuthenticationProvider() { OnAuthenticated = context => { context.Identity.AddClaim(new Claim(MyClaims.MyProviderID, "Microsoft")); return(Task.FromResult <object>(null)); } } }; app.UseMicrosoftAccountAuthentication(microsoftOptions); // --- add roles --- app.Use(SimpleAddUserInfoAndRoles.Exec) // <--- add my roles & information .UseStageMarker(PipelineStage.PostAuthenticate); // <--- very important. Roles must be added after authentication. }
private static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType) { var google = new GoogleOAuth2AuthenticationOptions { AuthenticationType = "Google", SignInAsAuthenticationType = signInAsType, ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com", ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze" }; app.UseGoogleAuthentication(google); var fb = new FacebookAuthenticationOptions { AuthenticationType = "Facebook", SignInAsAuthenticationType = signInAsType, AppId = "676607329068058", AppSecret = "9d6ab75f921942e61fb43a9b1fc25c63" }; app.UseFacebookAuthentication(fb); var twitter = new TwitterAuthenticationOptions { AuthenticationType = "Twitter", SignInAsAuthenticationType = signInAsType, ConsumerKey = "N8r8w7PIepwtZZwtH066kMlmq", ConsumerSecret = "df15L2x6kNI50E4PYcHS0ImBQlcGIt6huET8gQN41VFpUCwNjM" }; app.UseTwitterAuthentication(twitter); var ms = new MicrosoftAccountAuthenticationOptions { AuthenticationType = "Microsoft", SignInAsAuthenticationType = signInAsType, ClientId = "N8r8w7PIe", ClientSecret = "df15L2x6kNI50E" }; app.UseMicrosoftAccountAuthentication(ms); var github = new GitHubAuthenticationOptions() { AuthenticationType = "Github", SignInAsAuthenticationType = signInAsType, ClientId = "N8r8w7PIe", ClientSecret = "df15L2x6kNI50E" }; app.UseGitHubAuthentication(github); }
private void AddMicrosoftAuth(IAppBuilder app) { var microsoft = new MicrosoftAccountAuthenticationOptions { Caption = "Live", ClientId = WebConfigurationManager.AppSettings["MicrosoftClientId"], ClientSecret = WebConfigurationManager.AppSettings["MicrosoftClientSecret"], }; microsoft.Scope.Add("wl.basic"); microsoft.Scope.Add("wl.emails"); app.UseMicrosoftAccountAuthentication(microsoft); }
/// <summary> /// Configure microsoft account sign-in /// </summary> /// <param name="app"></param> /// <param name="clientId"></param> /// <param name="clientSecret"></param> /// <param name="caption"></param> /// <param name="style"></param> /// <param name="icon"></param> /// <remarks> /// /// Nuget installation: /// Microsoft.Owin.Security.MicrosoftAccount /// /// Microsoft account documentation for ASP.Net Identity can be found: /// /// http://www.asp.net/web-api/overview/security/external-authentication-services#MICROSOFT /// http://blogs.msdn.com/b/webdev/archive/2012/09/19/configuring-your-asp-net-application-for-microsoft-oauth-account.aspx /// /// Microsoft apps can be created here: /// /// http://go.microsoft.com/fwlink/?LinkID=144070 /// /// </remarks> public static void ConfigureBackOfficeMicrosoftAuth(this IAppBuilder app, string clientId, string clientSecret, string caption = "Microsoft", string style = "btn-microsoft", string icon = "fa-windows") { var msOptions = new MicrosoftAccountAuthenticationOptions { ClientId = clientId, ClientSecret = clientSecret, SignInAsAuthenticationType = Constants.Security.BackOfficeExternalAuthenticationType, CallbackPath = new PathString("/umbraco-microsoft-signin") }; msOptions.ForUmbracoBackOffice(style, icon); msOptions.Caption = caption; app.UseMicrosoftAccountAuthentication(msOptions); }
public void Configuration(IAppBuilder app) { app.SetDefaultSignInAsAuthenticationType("External"); //app.UseCors(CorsOptions.AllowAll); app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = "External", // DefaultAuthenticationTypes.ExternalCookie AuthenticationMode = AuthenticationMode.Passive, CookieName = ".AspNet.External", ExpireTimeSpan = TimeSpan.FromMinutes(5), }); if (!string.IsNullOrEmpty(googleClientID) && !string.IsNullOrEmpty(googleClientID)) { app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() { ClientId = googleClientID, ClientSecret = googleClientSecret, }); } if (!string.IsNullOrEmpty(facebookClientID) && !string.IsNullOrEmpty(facebookClientSecret)) { FacebookAuthenticationOptions facebookAuthOptions = new FacebookAuthenticationOptions { AppId = facebookClientID, AppSecret = facebookClientSecret, UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email", Scope = { "email" } }; app.UseFacebookAuthentication(facebookAuthOptions); } if ((!string.IsNullOrEmpty(microsoftClientID) && !string.IsNullOrEmpty(microsoftClientSecret))) { MicrosoftAccountAuthenticationOptions microsoftAccountAuthenticationOptions = new MicrosoftAccountAuthenticationOptions { ClientId = microsoftClientID, ClientSecret = microsoftClientSecret, Provider = new MicrosoftAccountAuthenticationProvider() { OnAuthenticated = (context) => { var email = context.User["userPrincipalName"]; if (email != null) { context.Identity.AddClaim(new Claim(ClaimTypes.Email, email.ToString())); } return(Task.FromResult(0)); } } }; app.UseMicrosoftAccountAuthentication(microsoftAccountAuthenticationOptions); } }
// 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); // Enable Microsoft Account login. var msaOptions = new MicrosoftAccountAuthenticationOptions { ClientId = ConfigurationManager.AppSettings["MsaClientId"], ClientSecret = ConfigurationManager.AppSettings["MsaClientSecret"] }; msaOptions.Scope.Add("wl.basic"); // Always required. msaOptions.Scope.Add("wl.emails"); // Need this to get user email. app.UseMicrosoftAccountAuthentication(msaOptions); }
private static void AddMicrosoftAccount(IAppBuilder app) { var keys = ConfigurationHelper.MicrosoftOAuthKeys; if (keys == null) { return; } var microsoftAccountAuthenticationOptions = new MicrosoftAccountAuthenticationOptions { ClientId = keys.Item1, ClientSecret = keys.Item2, }; microsoftAccountAuthenticationOptions.Scope.Add("wl.basic"); microsoftAccountAuthenticationOptions.Scope.Add("wl.emails"); app.UseMicrosoftAccountAuthentication(microsoftAccountAuthenticationOptions); }
private static void AddMicrosoftAccount(IAppBuilder app) { var keys = ConfigurationHelper.MicrosoftOAuthKeys; if (keys == null) { return; } var microsoftAccountAuthenticationOptions = new MicrosoftAccountAuthenticationOptions { ClientId = keys.Item1, ClientSecret = keys.Item2, Provider = new MSProvider() }; microsoftAccountAuthenticationOptions.Scope.Add("https://graph.microsoft.com/user.read"); app.UseMicrosoftAccountAuthentication(microsoftAccountAuthenticationOptions); }
public virtual void ConfiguerExternalIdentityProvider(IAppBuilder owinApp, string signInType) { if (AppEnvironment.HasConfig("MicrosoftClientId") && AppEnvironment.HasConfig("MicrosoftSecret")) { string microsoftClientId = AppEnvironment.GetConfig <string>("MicrosoftClientId"); string microsoftSecret = AppEnvironment.GetConfig <string>("MicrosoftSecret"); Task MicrosoftOnAuthenticated(MicrosoftAccountAuthenticatedContext context) { context.Identity.AddClaim(new System.Security.Claims.Claim("access_token", context.AccessToken)); foreach (KeyValuePair <string, JToken> claim in context.User) { string claimType = $"{claim.Key}"; string claimValue = claim.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft")); } } return(Task.CompletedTask); } MicrosoftAccountAuthenticationOptions microsoftAccountAuthenticationOptions = new MicrosoftAccountAuthenticationOptions { AuthenticationType = "Microsoft", SignInAsAuthenticationType = signInType, ClientId = microsoftClientId, ClientSecret = microsoftSecret, Provider = new MicrosoftAccountAuthenticationProvider { OnAuthenticated = MicrosoftOnAuthenticated } }; owinApp.UseMicrosoftAccountAuthentication(microsoftAccountAuthenticationOptions); } }
public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType) { var msOptions = new MicrosoftAccountAuthenticationOptions { AuthenticationType = "Microsoft", SignInAsAuthenticationType = signInAsType, ClientId = "myClientId", ClientSecret = "mySecret" }; app.UseMicrosoftAccountAuthentication(msOptions); var qqOptions = new QQConnectAuthenticationOptions { AuthenticationType = "QQ", SignInAsAuthenticationType = signInAsType, AppId = "myClientId", AppSecret = "mySecret" }; app.UseQQConnectAuthentication(qqOptions); }
// 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 }
//const string ignoreClaimPrefix = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims"; // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public void ConfigureAuth(IAppBuilder app) { // Configure the db context, user manager and signin manager to use a single instance per request DataProtectionProvider = app.GetDataProtectionProvider(); app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance <IDocumentSession>()); app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance <ApplicationUserManager>()); //app.CreatePerOwinContext(() => ServiceLocator.Current.GetInstance<ApplicationSignInManager>()); //// Enable the application to use a cookie to store information for the signed in user app.UseCookieAuthentication(new CookieAuthenticationOptions { AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, LoginPath = new PathString("/loggain/"), CookieName = ConfigurationManager.AppSettings["RavenDb.DefaultDatabase"] ?? "Easyfy.Auth", Provider = new CookieAuthenticationProvider { // Enables the application to validate the security stamp when the user logs in. // This is a security feature which is used when you change a password or add an external login to your account. OnValidateIdentity = SecurityStampValidator.OnValidateIdentity <ApplicationUserManager, User>( validateInterval: TimeSpan.FromMinutes(30), regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager)) } }); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Enables the application to temporarily store user information when they are verifying the second factor in the two-factor authentication process. app.UseTwoFactorSignInCookie(DefaultAuthenticationTypes.TwoFactorCookie, TimeSpan.FromMinutes(5)); // Enables the application to remember the second login verification factor such as phone or email. // Once you check this option, your second step of verification during the login process will be remembered on the device where you logged in from. // This is similar to the RememberMe option when you log in. app.UseTwoFactorRememberBrowserCookie(DefaultAuthenticationTypes.TwoFactorRememberBrowserCookie); // Uncomment the following lines to enable logging in with third party login providers if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Windows.ClientId"))) { var mo = new MicrosoftAccountAuthenticationOptions { Caption = "Live", ClientId = ConfigurationManager.AppSettings.Get("Windows.ClientId"), ClientSecret = ConfigurationManager.AppSettings.Get("Windows.ClientSecret"), Provider = new Microsoft.Owin.Security.MicrosoftAccount.MicrosoftAccountAuthenticationProvider() { OnAuthenticated = async context => { context.Identity.AddClaim(new System.Security.Claims.Claim("urn:microsoftaccount:access_token", context.AccessToken)); foreach (var claim in context.User) { var claimType = string.Format("urn:microsoftaccount:{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")); } } } } }; mo.Scope.Add("wl.basic"); mo.Scope.Add("wl.emails"); app.UseMicrosoftAccountAuthentication(mo); } if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Google.ClientId"))) { var googleOption = new GoogleOAuth2AuthenticationOptions() { ClientId = ConfigurationManager.AppSettings.Get("Google.ClientId"), ClientSecret = ConfigurationManager.AppSettings.Get("Google.ClientSecret"), Provider = new GoogleOAuth2AuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new Claim("urn:google:name", context.Identity.FindFirstValue(ClaimTypes.Name))); //context.Identity.AddClaim(new Claim("picture", context.User.GetValue("picture").ToString())); context.Identity.AddClaim(new Claim("urn:google:email", context.Identity.FindFirstValue(ClaimTypes.Email))); return(Task.FromResult(0)); } } }; googleOption.Scope.Add("email"); app.UseGoogleAuthentication(googleOption); } if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Twitter.ConsumerKey"))) { app.UseTwitterAuthentication( consumerKey: ConfigurationManager.AppSettings["Twitter.ConsumerKey"], consumerSecret: ConfigurationManager.AppSettings["Twitter.ConsumerSecret"]); } if (!String.IsNullOrWhiteSpace(ConfigurationManager.AppSettings.Get("Facebook.AppId"))) { var facebookOptions = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationOptions() { AppId = ConfigurationManager.AppSettings.Get("Facebook.AppId"), AppSecret = ConfigurationManager.AppSettings.Get("Facebook.AppSecret"), Provider = new Microsoft.Owin.Security.Facebook.FacebookAuthenticationProvider() { OnAuthenticated = (context) => { context.Identity.AddClaim(new System.Security.Claims.Claim("urn:facebook:access_token", context.AccessToken, XmlSchemaString, "Facebook")); foreach (var x in context.User) { var claimType = string.Format("urn:facebook:{0}", x.Key); string claimValue = x.Value.ToString(); if (!context.Identity.HasClaim(claimType, claimValue)) { context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, XmlSchemaString, "Facebook")); } } return(Task.FromResult(0)); } } }; facebookOptions.Scope.Add("email"); app.UseFacebookAuthentication(facebookOptions); } }
public static IAppBuilder UseMicrosoftAccountAuthentication(this IAppBuilder app, MicrosoftAccountAuthenticationOptions options) { app.Use(typeof(MicrosoftAccountAuthenticationMiddleware), app, options); return(app); }
// For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864 public static void ConfigureAuth(IAppBuilder app) { // Configure the db context and user manager to use a single instance per request // TODO Is this correct to make DbContext accessible from Web application? app.CreatePerOwinContext(WealthEconomyContext.Create); app.CreatePerOwinContext <AppUserManager>(CreateUserManager); // Use a cookie to temporarily store information about a user logging in with a third party login provider app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie); // Configure the application for OAuth based flow PublicClientId = "self"; var OAuthServerOptions = new OAuthAuthorizationServerOptions { TokenEndpointPath = new PathString("/api/Token"), Provider = new ApplicationOAuthProvider(PublicClientId), //AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"), // TODO ? AccessTokenExpireTimeSpan = TimeSpan.FromHours(3), AllowInsecureHttp = AppSettings.EnvironmentType != EnvironmentType.Live }; // Enable the application to use bearer tokens to authenticate users app.UseOAuthBearerTokens(OAuthServerOptions); // Configure Facebook login var facebookAppId = AppSettings.FacebookAppId; var facebookAppSecret = AppSettings.FacebookAppSecret; if (!string.IsNullOrWhiteSpace(facebookAppId) && !string.IsNullOrWhiteSpace(facebookAppSecret)) { var facebookAuthOptions = new FacebookAuthenticationOptions() { AppId = AppSettings.FacebookAppId, AppSecret = AppSettings.FacebookAppSecret, UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=email", BackchannelHttpHandler = new FacebookBackChannelHandler(), CallbackPath = new PathString("/api/Account/ExternalLoginFacebook") // Middleware is going to handle this, no need to implement }; facebookAuthOptions.Scope.Add("email"); app.UseFacebookAuthentication(facebookAuthOptions); } // Configure Google login var googleClientId = AppSettings.GoogleClientId; var googleClientSecret = AppSettings.GoogleClientSecret; if (!string.IsNullOrWhiteSpace(googleClientId) && !string.IsNullOrWhiteSpace(googleClientSecret)) { var googleAuthOptions = new GoogleOAuth2AuthenticationOptions() { ClientId = googleClientId, ClientSecret = googleClientSecret, CallbackPath = new PathString("/api/Account/ExternalLoginGoogle") // Middleware is going to handle this, no need to implement }; app.UseGoogleAuthentication(googleAuthOptions); } // Configure Microsoft Accounts login var microsoftClientId = AppSettings.MicrosoftClientId; var microsoftClientSecret = AppSettings.MicrosoftClientSecret; if (!string.IsNullOrWhiteSpace(microsoftClientId) && !string.IsNullOrWhiteSpace(microsoftClientSecret)) { var microsoftAccountAuthOptions = new MicrosoftAccountAuthenticationOptions() { ClientId = AppSettings.MicrosoftClientId, ClientSecret = AppSettings.MicrosoftClientSecret, CallbackPath = new PathString("/api/Account/ExternalLoginMicrosoft") // Middleware is going to handle this, no need to implement }; microsoftAccountAuthOptions.Scope.Add("openid"); microsoftAccountAuthOptions.Scope.Add("email"); app.UseMicrosoftAccountAuthentication(microsoftAccountAuthOptions); } }
public async Task AuthenticatedEventCanGetRefreshToken() { var options = new MicrosoftAccountAuthenticationOptions() { ClientId = "Test Client Id", ClientSecret = "Test Client Secret", BackchannelHttpHandler = new TestHttpMessageHandler { Sender = async req => { if (req.RequestUri.AbsoluteUri == "https://login.microsoftonline.com/common/oauth2/v2.0/token") { return(await ReturnJsonResponse(new { access_token = "Test Access Token", expire_in = 3600, token_type = "Bearer", refresh_token = "Test Refresh Token" })); } else if (req.RequestUri.GetLeftPart(UriPartial.Path) == "https://graph.microsoft.com/v1.0/me") { return(await ReturnJsonResponse(new { id = "Test User ID", displayName = "Test Name", givenName = "Test Given Name", surname = "Test Family Name", mail = "Test email" })); } return(null); } }, Provider = new MicrosoftAccountAuthenticationProvider { OnAuthenticated = context => { var refreshToken = context.RefreshToken; context.Identity.AddClaim(new Claim("RefreshToken", refreshToken)); return(Task.FromResult <object>(null)); } } }; var server = CreateServer( app => app.UseMicrosoftAccountAuthentication(options), context => { var req = context.Request; var res = context.Response; Describe(res, new AuthenticateResult(req.User.Identity, new AuthenticationProperties(), new AuthenticationDescription())); return(true); }); var properties = new AuthenticationProperties(); var correlationKey = ".AspNet.Correlation.Microsoft"; var correlationValue = "TestCorrelationId"; properties.Dictionary.Add(correlationKey, correlationValue); properties.RedirectUri = "/me"; var state = options.StateDataFormat.Protect(properties); var transaction = await SendAsync(server, "https://example.com/signin-microsoft?code=TestCode&state=" + Uri.EscapeDataString(state), correlationKey + "=" + correlationValue); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.Redirect); transaction.Response.Headers.Location.ToString().ShouldBe("/me"); transaction.SetCookie.Count.ShouldBe(2); transaction.SetCookie[0].ShouldContain(correlationKey); transaction.SetCookie[1].ShouldContain(".AspNet.External"); var authCookie = transaction.AuthenticationCookieValue; transaction = await SendAsync(server, "https://example.com/me", authCookie); transaction.Response.StatusCode.ShouldBe(HttpStatusCode.OK); transaction.FindClaimValue("RefreshToken").ShouldBe("Test Refresh Token"); }
/// <summary> /// Authenticate users using Microsoft Account /// </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 UseMicrosoftAccountAuthentication(this IAppBuilder app, MicrosoftAccountAuthenticationOptions options) { if (app == null) { throw new ArgumentNullException("app"); } if (options == null) { throw new ArgumentNullException("options"); } app.Use(typeof(MicrosoftAccountAuthenticationMiddleware), app, options); return(app); }
// 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 msOptions = new MicrosoftAccountAuthenticationOptions { ClientId = "000000004C11330A", ClientSecret = "FSjqWU-TDg4WvOTzYpnbW7hwEGsGrBZV", Caption = "Test", SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie, Provider = new MicrosoftAccountAuthenticationProvider { OnAuthenticated = (context) => { HttpContext.Current.GetOwinContext() .Response.Cookies.Append("OwinCookie", "SomeValue"); HttpContext.Current.Response.Cookies["ASPCookie"].Value = "SomeValue"; HttpContext.Current.GetOwinContext().Authentication.User.AddIdentity(context.Identity); return(null); } } }; msOptions.Scope.Add("wl.basic,office.onenote_create,wl.offline_access"); app.UseMicrosoftAccountAuthentication(msOptions); //app.UseMicrosoftAccountAuthentication("000000004C11330A", "FSjqWU-TDg4WvOTzYpnbW7hwEGsGrBZV"); //app.UseTwitterAuthentication( // consumerKey: "", // consumerSecret: ""); //app.UseFacebookAuthentication( // appId: "", // appSecret: ""); //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions() //{ // ClientId = "", // ClientSecret = "" //}); }
//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 }