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");
 }
示例#2
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Enable the application to use a cookie to store information for the signed in user
            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                LoginPath = new PathString("/Account/Login")
            });
            // Use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            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"]
            });
        }
        // 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);
        }
        // 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(AppDbContext.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"),
                SlidingExpiration = false,
                ExpireTimeSpan = TimeSpan.FromDays(30),
                Provider = new CookieAuthenticationProvider
                {
                    OnValidateIdentity =
                        SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, User>(
                            validateInterval: TimeSpan.FromMinutes(30),
                            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
                }
            });

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Uncomment the following lines to enable logging in with third party login providers
            app.UseGoogleAuthentication("1058035413863-pmbgn6n7slu0nph17l96nu65r9oeuqui.apps.googleusercontent.com", "J5wsfYCsgClB9G5miL7Bj8A7");

            var facebookOptions = new FacebookAuthenticationOptions()
            {
                AppId = "899746186808173",
                AppSecret = "4a339373d1748469a27a021c376a6ac2",
                BackchannelHttpHandler = new FacebookBackChannelHandler(),
                UserInformationEndpoint = "https://graph.facebook.com/v2.4/me?fields=id,name,email,first_name,last_name,location"
            };

            facebookOptions.Scope.Add("email");

            app.UseFacebookAuthentication(facebookOptions);

            var microsoftOptions = new MicrosoftAccountAuthenticationOptions
            {
                Caption = "Live",
                ClientId = "000000004018626B",
                ClientSecret = "0JN-2FYhsi4z-NnskF3C97A63nSJbkW8"
            };
            microsoftOptions.Scope.Add("wl.basic");
            microsoftOptions.Scope.Add("wl.emails");

            app.UseMicrosoftAccountAuthentication(microsoftOptions);
        }
        /// <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;
        }
示例#6
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Enable the application to use a cookie to store information for the signed in user
            // and to use a cookie to temporarily store information about a user logging in with a third party login provider
            app.UseCookieAuthentication(new CookieAuthenticationOptions());
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            OAuthOptions = new OAuthAuthorizationServerOptions
            {
                TokenEndpointPath = new PathString("/Token"),
                Provider = new ApplicationOAuthProvider(PublicClientId),
                AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
                // In production mode set AllowInsecureHttp = false
                AllowInsecureHttp = true
            };

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

            // Sign in with Microsoft ID
            var msOptions = new MicrosoftAccountAuthenticationOptions
            {
                ClientId = WebConfigurationManager.AppSettings["MicrosoftIDClientID"],
                ClientSecret = WebConfigurationManager.AppSettings["MicrosoftIDClientSecret"]
            };
            msOptions.Scope.Clear();
            msOptions.Scope.Add("wl.signin");
            app.UseMicrosoftAccountAuthentication(msOptions);

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

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

            //app.UseGoogleAuthentication(new GoogleOAuth2AuthenticationOptions()
            //{
            //    ClientId = "",
            //    ClientSecret = ""
            //});
        }
 ///  <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);
 }
示例#8
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            // Configure the db context and user manager to use a single instance per request
            app.CreatePerOwinContext(EntityModel.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);

            // Configure the application for OAuth based flow
            PublicClientId = "self";
            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
            OAuthOptions = new OAuthAuthorizationServerOptions
                           {
                               TokenEndpointPath = new PathString("/API/Token"),
                               Provider = new ApplicationOAuthProvider(PublicClientId),
                               AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
                               AccessTokenExpireTimeSpan = TimeSpan.FromDays(30),
                               AllowInsecureHttp = true
                           };

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

            // Uncomment the following lines to enable logging in with third party login providers
            var microsoftOptions = new MicrosoftAccountAuthenticationOptions
                                   {
                                       ClientId = "000000004012ABA5",
                                       ClientSecret = "9KHkk7OfuYwr06NpsaBKEZxD0wfQZgE2"
                                   };
            microsoftOptions.Scope.Add("wl.emails");
            var facebookOptions = new FacebookAuthenticationOptions
            {
                AppId = "775625759162004",
                AppSecret = "d411869c0707a273d6530a6a9cc592f7"
            };
            facebookOptions.Scope.Add("email");

            var googleOptions = new GoogleOAuth2AuthenticationOptions()
                                {
                                    ClientId =
                                        "469646760415-qfrnioi99r3bmcfpsi7997m1h6qgj0b3.apps.googleusercontent.com",
                                    ClientSecret = "9YdAukql7ZKrm6RUI4hfXA7S"
                                };

            app.UseFacebookAuthentication(facebookOptions);
            app.UseMicrosoftAccountAuthentication(microsoftOptions);
            app.UseGoogleAuthentication(googleOptions);
        }
示例#9
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

            // 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 SetupMicrosoftAuth(IAppBuilder app)
 {
     MicrosoftAccountAuthenticationOptions microsoftOptions = new MicrosoftAccountAuthenticationOptions()
     {
         ClientId = MicrosoftClientId,
         ClientSecret = MicrosoftClientSecret
     };
     app.UseMicrosoftAccountAuthentication(
         clientId: MicrosoftClientId,
         clientSecret: MicrosoftClientSecret);
 }
 public static IAppBuilder UseMicrosoftAccountAuthentication(this IAppBuilder app, MicrosoftAccountAuthenticationOptions options)
 {
     app.Use(typeof(MicrosoftAccountAuthenticationMiddleware), app, options);
     return app;
 }
示例#12
0
		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);
		}
示例#13
0
 /// <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);
 }
示例#14
0
        // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
        public void ConfigureAuth(IAppBuilder app)
        {
            // Configure the db context, user manager and signin manager to use a single instance per request
            app.CreatePerOwinContext(ApplicationDbContext.Create);
            app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
            app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);

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

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

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

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

            var microsoftAuthenticationOptions = new MicrosoftAccountAuthenticationOptions()
            {
                ClientId = ConfigurationManager.AppSettings["MsI"],
                ClientSecret = ConfigurationManager.AppSettings["MsS"],
                Provider = new MicrosoftAccountAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("MicrosoftAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var claimType = string.Format("urn:microsoft:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Microsoft"));
                        }
                    }
                }
            };
            microsoftAuthenticationOptions.Scope.Add("wl.basic");
            microsoftAuthenticationOptions.Scope.Add("wl.emails");
            microsoftAuthenticationOptions.Scope.Add("wl.birthday");
            app.UseMicrosoftAccountAuthentication(microsoftAuthenticationOptions);

            #endregion Microsoft

            #region Twitter
            var twitterAuthenticationOptions = new TwitterAuthenticationOptions()
            {
                ConsumerKey = ConfigurationManager.AppSettings["TwtI"],
                ConsumerSecret = ConfigurationManager.AppSettings["TwtS"]
            };
            app.UseTwitterAuthentication(twitterAuthenticationOptions);

            #endregion Twitter

            #region Facebook
            var facebookAuthenticationOptions = new FacebookAuthenticationOptions()
            {
                AppId = ConfigurationManager.AppSettings["FaceI"],
                AppSecret = ConfigurationManager.AppSettings["FaceS"],
                Provider = new FacebookAuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("FacebookAccessToken", context.AccessToken));
                    }
                }
            };
            facebookAuthenticationOptions.Scope.Add("public_profile");
            facebookAuthenticationOptions.Scope.Add("email");
            facebookAuthenticationOptions.Scope.Add("user_birthday");
            app.UseFacebookAuthentication(facebookAuthenticationOptions);


            #endregion Facebook

            #region Google

            var googleAuthenticationOptions = new GoogleOAuth2AuthenticationOptions()
            {
                ClientId = ConfigurationManager.AppSettings["GglI"],
                ClientSecret = ConfigurationManager.AppSettings["GglS"],
                Provider = new GoogleOAuth2AuthenticationProvider()
                {
                    OnAuthenticated = async context =>
                    {
                        context.Identity.AddClaim(new System.Security.Claims.Claim("GoogleAccessToken", context.AccessToken));
                        foreach (var claim in context.User)
                        {
                            var claimType = string.Format("urn:google:{0}", claim.Key);
                            string claimValue = claim.Value.ToString();
                            if (!context.Identity.HasClaim(claimType, claimValue))
                                context.Identity.AddClaim(new System.Security.Claims.Claim(claimType, claimValue, "XmlSchemaString", "Google"));
                        }
                    }
                }
            };
            googleAuthenticationOptions.Scope.Add("https://www.googleapis.com/auth/plus.login email");
            app.UseGoogleAuthentication(googleAuthenticationOptions);

            #endregion Google


        }
        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.live.com/oauth20_token.srf")
                        {
                            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://apis.live.net/v5.0/me")
                        {
                            return await ReturnJsonResponse(new
                            {
                                id = "Test User ID",
                                name = "Test Name",
                                first_name = "Test Given Name",
                                last_name = "Test Family Name",
                                emails = new
                                {
                                    preferred = "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");
        }
示例#16
0
 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;
 }
示例#17
0
        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");
        }
示例#18
0
        private static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var google = new GoogleOAuth2AuthenticationOptions
            {
                AuthenticationType = "Google",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "767400843187-8boio83mb57ruogr9af9ut09fkg56b27.apps.googleusercontent.com",
                ClientSecret = "5fWcBT0udKY7_b6E3gEiJlze"
            };
            app.UseGoogleAuthentication(google);

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

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

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

            var github = new GitHubAuthenticationOptions()
            {
                AuthenticationType = "Github",
                SignInAsAuthenticationType = signInAsType,
                ClientId = "N8r8w7PIe",
                ClientSecret = "df15L2x6kNI50E"
            };
            app.UseGitHubAuthentication(github);
        }
示例#19
0
 /// <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 = "<ChangeThis>",
         ClientSecret = "<ChangeThis>"
     };
     microsoftOptions.Scope.Add("email");
     app.UseMicrosoftAccountAuthentication(microsoftOptions);
 }
        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);
        }
示例#21
0
        // 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<UserManagerFactory>(UserManagerFactory.Create);

            // 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.FromDays(14),
                AllowInsecureHttp = true
            };

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

            // Configure Facebook login
            var facebookAppId = Framework.AppSettings.FacebookAppId;
            var facebookAppSecret = Framework.AppSettings.FacebookAppSecret;

            if (!string.IsNullOrWhiteSpace(facebookAppId) && !string.IsNullOrWhiteSpace(facebookAppSecret))
            {
                var facebookAuthOptions = new FacebookAuthenticationOptions()
                {
                    AppId = Framework.AppSettings.FacebookAppId,
                    AppSecret = Framework.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 = Framework.AppSettings.GoogleClientId;
            var googleClientSecret = Framework.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 = Framework.AppSettings.MicrosoftClientId;
            var microsoftClientSecret = Framework.AppSettings.MicrosoftClientSecret;

            if (!string.IsNullOrWhiteSpace(microsoftClientId) && !string.IsNullOrWhiteSpace(microsoftClientSecret))
            {
                var microsoftAccountAuthOptions = new MicrosoftAccountAuthenticationOptions()
                {
                    ClientId = Framework.AppSettings.MicrosoftClientId,
                    ClientSecret = Framework.AppSettings.MicrosoftClientSecret,
                    CallbackPath = new PathString("/api/Account/ExternalLoginMicrosoft") // Middleware is going to handle this, no need to implement
                };
                microsoftAccountAuthOptions.Scope.Add("wl.emails");
                app.UseMicrosoftAccountAuthentication(microsoftAccountAuthOptions);
            }
        }