/// <summary>
 /// Creates a new context object.
 /// </summary>
 /// <param name="context">The HTTP request context.</param>
 /// <param name="options">The Twitter middleware options.</param>
 /// <param name="properties">The authentication properties of the challenge.</param>
 /// <param name="redirectUri">The initial redirect URI.</param>
 public TwitterRedirectToAuthorizationEndpointContext(HttpContext context, TwitterOptions options,
     AuthenticationProperties properties, string redirectUri)
     : base(context, options)
 {
     RedirectUri = redirectUri;
     Properties = properties;
 }
        /// <summary>
        /// Adds the <see cref="TwitterMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Twitter authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">An action delegate to configure the provided <see cref="TwitterOptions"/>.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, TwitterOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<TwitterMiddleware>(Options.Create(options));
        }
Пример #3
0
 /// <summary>
 /// Initializes a <see cref="TwitterCreatingTicketContext"/>
 /// </summary>
 /// <param name="context">The HTTP environment</param>
 /// <param name="options">The options for Twitter</param>
 /// <param name="userId">Twitter user ID</param>
 /// <param name="screenName">Twitter screen name</param>
 /// <param name="accessToken">Twitter access token</param>
 /// <param name="accessTokenSecret">Twitter access token secret</param>
 public TwitterCreatingTicketContext(
     HttpContext context,
     TwitterOptions options,
     string userId,
     string screenName,
     string accessToken,
     string accessTokenSecret)
     : base(context, options)
 {
     UserId = userId;
     ScreenName = screenName;
     AccessToken = accessToken;
     AccessTokenSecret = accessTokenSecret;
 }
Пример #4
0
        // Configure is called after ConfigureServices is called.
        public async void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, SampleDataGenerator sampleData, AllReadyContext context, 
            IConfiguration configuration)
        {
            // todo: in RC update we can read from a logging.json config file
            loggerFactory.AddConsole((category, level) =>
            {
                if (category.StartsWith("Microsoft."))
                {
                    return level >= LogLevel.Information;
                }
                return true;
            });

            if (env.IsDevelopment())
            {
                // this will go to the VS output window
                loggerFactory.AddDebug((category, level) =>
                {
                    if (category.StartsWith("Microsoft."))
                    {
                        return level >= LogLevel.Information;
                    }
                    return true;
                });
            }

            // CORS support
            app.UseCors("allReady");

            // Configure the HTTP request pipeline.
            var usCultureInfo = new CultureInfo("en-US");
            app.UseRequestLocalization(new RequestLocalizationOptions
            {
                SupportedCultures = new List<CultureInfo>(new[] { usCultureInfo }),
                SupportedUICultures = new List<CultureInfo>(new[] { usCultureInfo })
            });

            // Add Application Insights to the request pipeline to track HTTP request telemetry data.
            app.UseApplicationInsightsRequestTelemetry();

            // Add the following to the request pipeline only in development environment.
            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else if (env.IsStaging())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                // Add Error handling middleware which catches all application specific errors and
                // sends the request to the following path or controller action.
                app.UseExceptionHandler("/Home/Error");
            }

            // Track data about exceptions from the application. Should be configured after all error handling middleware in the request pipeline.
            app.UseApplicationInsightsExceptionTelemetry();

            // Add static files to the request pipeline.
            app.UseStaticFiles();

            // Add cookie-based authentication to the request pipeline.
            app.UseIdentity();

            // Add token-based protection to the request inject pipeline
            app.UseTokenProtection(new TokenProtectedResourceOptions
            {
                Path = "/api/request",
                PolicyName = "api-request-injest"
            });

            // Add authentication middleware to the request pipeline. You can configure options such as Id and Secret in the ConfigureServices method.
            // For more information see http://go.microsoft.com/fwlink/?LinkID=532715
            if (Configuration["Authentication:Facebook:AppId"] != null)
            {
                var options = new FacebookOptions
                {
                    AppId = Configuration["Authentication:Facebook:AppId"],
                    AppSecret = Configuration["Authentication:Facebook:AppSecret"],
                    BackchannelHttpHandler = new FacebookBackChannelHandler(),
                    UserInformationEndpoint = "https://graph.facebook.com/v2.5/me?fields=id,name,email,first_name,last_name"
                };
                options.Scope.Add("email");

                app.UseFacebookAuthentication(options);
            }

            if (Configuration["Authentication:MicrosoftAccount:ClientId"] != null)
            {
                var options = new MicrosoftAccountOptions
                {
                    ClientId = Configuration["Authentication:MicrosoftAccount:ClientId"],
                    ClientSecret = Configuration["Authentication:MicrosoftAccount:ClientSecret"]
                };

                app.UseMicrosoftAccountAuthentication(options);
            }
            //TODO: mgmccarthy: working on getting email from Twitter
            //http://www.bigbrainintelligence.com/Post/get-users-email-address-from-twitter-oauth-ap
            if (Configuration["Authentication:Twitter:ConsumerKey"] != null)
            {
                var options = new TwitterOptions
                {
                    ConsumerKey = Configuration["Authentication:Twitter:ConsumerKey"],
                    ConsumerSecret = Configuration["Authentication:Twitter:ConsumerSecret"]
                };

                app.UseTwitterAuthentication(options);
            }

            if (Configuration["Authentication:Google:ClientId"] != null)
            {
                var options = new GoogleOptions
                {
                    ClientId = Configuration["Authentication:Google:ClientId"],
                    ClientSecret = Configuration["Authentication:Google:ClientSecret"]
                };

                app.UseGoogleAuthentication(options);
            }

            // Add MVC to the request pipeline.
            app.UseMvc(routes =>
            {
                routes.MapRoute(name: "areaRoute", template: "{area:exists}/{controller}/{action=Index}/{id?}");
                routes.MapRoute(name: "default", template: "{controller=Home}/{action=Index}/{id?}");
            });

            // Add sample data and test admin accounts if specified in Config.Json.
            // for production applications, this should either be set to false or deleted.
            if (env.IsDevelopment() || env.IsEnvironment("Staging"))
            {
                context.Database.Migrate();
            }

            if (Configuration["SampleData:InsertSampleData"] == "true")
            {
                sampleData.InsertTestData();
            }

            if (Configuration["SampleData:InsertTestUsers"] == "true")
            {
                await sampleData.CreateAdminUser();
            }
        }
Пример #5
0
        public static IApplicationBuilder UseSocialAuth(
            this IApplicationBuilder app,
            SiteSettings site,
            CookieAuthenticationOptions externalCookieOptions,
            bool shouldUseFolder)
        {
            // TODO: will this require a restart if the options are updated in the ui?
            // no just need to clear the tenant cache after updating the settings
            if (!string.IsNullOrWhiteSpace(site.GoogleClientId))
            {
                var googleOptions = new GoogleOptions();
                googleOptions.AuthenticationScheme = "Google";
                googleOptions.SignInScheme         = externalCookieOptions.AuthenticationScheme;
                googleOptions.ClientId             = site.GoogleClientId;
                googleOptions.ClientSecret         = site.GoogleClientSecret;
                if (shouldUseFolder)
                {
                    googleOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-google";
                }

                app.UseGoogleAuthentication(googleOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.FacebookAppId))
            {
                var facebookOptions = new FacebookOptions();
                facebookOptions.AuthenticationScheme = "Facebook";
                facebookOptions.SignInScheme         = externalCookieOptions.AuthenticationScheme;
                facebookOptions.AppId     = site.FacebookAppId;
                facebookOptions.AppSecret = site.FacebookAppSecret;

                if (shouldUseFolder)
                {
                    facebookOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-facebook";
                }

                app.UseFacebookAuthentication(facebookOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.MicrosoftClientId))
            {
                var microsoftOptions = new MicrosoftAccountOptions();
                microsoftOptions.SignInScheme = externalCookieOptions.AuthenticationScheme;
                microsoftOptions.ClientId     = site.MicrosoftClientId;
                microsoftOptions.ClientSecret = site.MicrosoftClientSecret;
                if (shouldUseFolder)
                {
                    microsoftOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-microsoft";
                }

                app.UseMicrosoftAccountAuthentication(microsoftOptions);
            }

            //app.Use()

            //Func<HttpContext, bool> hasTwitterKeys = (HttpContext context) =>
            //{
            //    var tenant = context.GetTenant<SiteSettings>();
            //    if (tenant == null) return false;
            //    if (string.IsNullOrWhiteSpace(tenant.TwitterConsumerKey)) return false;
            //    if (string.IsNullOrWhiteSpace(tenant.TwitterConsumerSecret)) return false;

            //    return true;
            //};

            //app.UseWhen(context => hasTwitterKeys(context), appBuilder =>
            //{
            if (!string.IsNullOrWhiteSpace(site.TwitterConsumerKey))
            {
                var twitterOptions = new TwitterOptions();
                twitterOptions.SignInScheme   = externalCookieOptions.AuthenticationScheme;
                twitterOptions.ConsumerKey    = site.TwitterConsumerKey;
                twitterOptions.ConsumerSecret = site.TwitterConsumerSecret;

                if (shouldUseFolder)
                {
                    twitterOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-twitter";
                }

                app.UseTwitterAuthentication(twitterOptions);
            }

            //});



            return(app);
        }
Пример #6
0
        public static IApplicationBuilder UseSocialAuth(
            this IApplicationBuilder app,
            SiteContext site,
            CookieAuthenticationOptions externalCookieOptions,
            bool shouldUseFolder,
            bool sslIsAvailable = true
            )
        {
            // TODO: will this require a restart if the options are updated in the ui?
            // no just need to clear the tenant cache after updating the settings
            if (!string.IsNullOrWhiteSpace(site.GoogleClientId))
            {
                var googleOptions = new GoogleOptions();
                googleOptions.AuthenticationScheme = "Google";
                googleOptions.SignInScheme         = externalCookieOptions.AuthenticationScheme;
                googleOptions.ClientId             = site.GoogleClientId;
                googleOptions.ClientSecret         = site.GoogleClientSecret;
                if (shouldUseFolder)
                {
                    googleOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-google";
                }

                app.UseGoogleAuthentication(googleOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.FacebookAppId))
            {
                var facebookOptions = new FacebookOptions();
                facebookOptions.AuthenticationScheme = "Facebook";
                facebookOptions.SignInScheme         = externalCookieOptions.AuthenticationScheme;
                facebookOptions.AppId     = site.FacebookAppId;
                facebookOptions.AppSecret = site.FacebookAppSecret;

                if (shouldUseFolder)
                {
                    facebookOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-facebook";
                }

                app.UseFacebookAuthentication(facebookOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.MicrosoftClientId))
            {
                var microsoftOptions = new MicrosoftAccountOptions();
                microsoftOptions.SignInScheme = externalCookieOptions.AuthenticationScheme;
                microsoftOptions.ClientId     = site.MicrosoftClientId;
                microsoftOptions.ClientSecret = site.MicrosoftClientSecret;
                if (shouldUseFolder)
                {
                    microsoftOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-microsoft";
                }

                app.UseMicrosoftAccountAuthentication(microsoftOptions);
            }


            if (!string.IsNullOrWhiteSpace(site.TwitterConsumerKey))
            {
                var twitterOptions = new TwitterOptions();
                twitterOptions.SignInScheme   = externalCookieOptions.AuthenticationScheme;
                twitterOptions.ConsumerKey    = site.TwitterConsumerKey;
                twitterOptions.ConsumerSecret = site.TwitterConsumerSecret;

                if (shouldUseFolder)
                {
                    twitterOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-twitter";
                }

                app.UseTwitterAuthentication(twitterOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.OidConnectAuthority) &&
                !string.IsNullOrWhiteSpace(site.OidConnectAppId)
                // && !string.IsNullOrWhiteSpace(site.OidConnectAppSecret)
                )
            {
                var displayName = "ExternalOIDC";
                if (!string.IsNullOrWhiteSpace(site.OidConnectDisplayName))
                {
                    displayName = site.OidConnectDisplayName;
                }
                var oidOptions = new OpenIdConnectOptions();
                oidOptions.AuthenticationScheme          = "ExternalOIDC";
                oidOptions.SignInScheme                  = externalCookieOptions.AuthenticationScheme;
                oidOptions.Authority                     = site.OidConnectAuthority;
                oidOptions.ClientId                      = site.OidConnectAppId;
                oidOptions.ClientSecret                  = site.OidConnectAppSecret;
                oidOptions.GetClaimsFromUserInfoEndpoint = true;
                oidOptions.ResponseType                  = OpenIdConnectResponseType.CodeIdToken;
                oidOptions.RequireHttpsMetadata          = sslIsAvailable;
                oidOptions.SaveTokens                    = true;
                oidOptions.DisplayName                   = displayName;

                if (shouldUseFolder)
                {
                    oidOptions.CallbackPath          = "/" + site.SiteFolderName + "/signin-oidc";
                    oidOptions.SignedOutCallbackPath = "/" + site.SiteFolderName + "/signout-callback-oidc";
                    oidOptions.RemoteSignOutPath     = "/" + site.SiteFolderName + "/signout-oidc";
                }

                //oidOptions.Events = new OpenIdConnectEvents()
                //{
                //    OnAuthenticationFailed = c =>
                //    {
                //        c.HandleResponse();

                //        c.Response.StatusCode = 500;
                //        c.Response.ContentType = "text/plain";

                //        return c.Response.WriteAsync("An error occurred processing your authentication.");
                //    }
                //};
                app.UseOpenIdConnectAuthentication(oidOptions);
            }



            return(app);
        }
        /// <summary>
        /// Adds the <see cref="TwitterMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables Twitter authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">An action delegate to configure the provided <see cref="TwitterOptions"/>.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, TwitterOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(app.UseMiddleware <TwitterMiddleware>(Options.Create(options)));
        }
Пример #8
0
        public static IApplicationBuilder UseSocialAuth(
            this IApplicationBuilder app,
            SiteContext site,
            CookieAuthenticationOptions externalCookieOptions,
            bool shouldUseFolder)
        {
            // TODO: will this require a restart if the options are updated in the ui?
            // no just need to clear the tenant cache after updating the settings
            if (!string.IsNullOrWhiteSpace(site.GoogleClientId))
            {
                var googleOptions = new GoogleOptions();
                googleOptions.AuthenticationScheme = "Google";
                googleOptions.SignInScheme = externalCookieOptions.AuthenticationScheme;
                googleOptions.ClientId = site.GoogleClientId;
                googleOptions.ClientSecret = site.GoogleClientSecret;
                if (shouldUseFolder)
                {
                    googleOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-google";
                }

                app.UseGoogleAuthentication(googleOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.FacebookAppId))
            {
                var facebookOptions = new FacebookOptions();
                facebookOptions.AuthenticationScheme = "Facebook";
                facebookOptions.SignInScheme = externalCookieOptions.AuthenticationScheme;
                facebookOptions.AppId = site.FacebookAppId;
                facebookOptions.AppSecret = site.FacebookAppSecret;

                if (shouldUseFolder)
                {
                    facebookOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-facebook";
                }

                app.UseFacebookAuthentication(facebookOptions);
            }

            if (!string.IsNullOrWhiteSpace(site.MicrosoftClientId))
            {
                var microsoftOptions = new MicrosoftAccountOptions();
                microsoftOptions.SignInScheme = externalCookieOptions.AuthenticationScheme;
                microsoftOptions.ClientId = site.MicrosoftClientId;
                microsoftOptions.ClientSecret = site.MicrosoftClientSecret;
                if (shouldUseFolder)
                {
                    microsoftOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-microsoft";
                }

                app.UseMicrosoftAccountAuthentication(microsoftOptions);
            }

            //app.Use()

            //Func<HttpContext, bool> hasTwitterKeys = (HttpContext context) =>
            //{
            //    var tenant = context.GetTenant<SiteSettings>();
            //    if (tenant == null) return false;
            //    if (string.IsNullOrWhiteSpace(tenant.TwitterConsumerKey)) return false;
            //    if (string.IsNullOrWhiteSpace(tenant.TwitterConsumerSecret)) return false;

            //    return true;
            //};

            //app.UseWhen(context => hasTwitterKeys(context), appBuilder =>
            //{
            if (!string.IsNullOrWhiteSpace(site.TwitterConsumerKey))
            {
                var twitterOptions = new TwitterOptions();
                twitterOptions.SignInScheme = externalCookieOptions.AuthenticationScheme;
                twitterOptions.ConsumerKey = site.TwitterConsumerKey;
                twitterOptions.ConsumerSecret = site.TwitterConsumerSecret;

                if (shouldUseFolder)
                {
                    twitterOptions.CallbackPath = "/" + site.SiteFolderName + "/signin-twitter";
                }

                app.UseTwitterAuthentication(twitterOptions);
            }

            //});



            return app;
        }
 public static IApplicationBuilder UseTwitterAuthentication(this IApplicationBuilder app, TwitterOptions options)
 {
     throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470");
 }
Пример #10
0
 /// <summary>
 /// Initializes a <see cref="BaseTwitterContext"/>
 /// </summary>
 /// <param name="context">The HTTP environment</param>
 /// <param name="options">The options for Twitter</param>
 public BaseTwitterContext(HttpContext context, TwitterOptions options)
     : base(context)
 {
     Options = options;
 }
Пример #11
0
 private static TestServer CreateServer(TwitterOptions options, Func<HttpContext, bool> handler = null)
 {
     var builder = new WebHostBuilder()
         .Configure(app =>
         {
             app.UseCookieAuthentication(new CookieAuthenticationOptions
             {
                 AuthenticationScheme = "External"
             });
             app.UseTwitterAuthentication(options);
             app.Use(async (context, next) =>
             {
                 var req = context.Request;
                 var res = context.Response;
                 if (req.Path == new PathString("/signIn"))
                 {
                     await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignInAsync("Twitter", new ClaimsPrincipal()));
                 }
                 else if (req.Path == new PathString("/signOut"))
                 {
                     await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.SignOutAsync("Twitter"));
                 }
                 else if (req.Path == new PathString("/forbid"))
                 {
                     await Assert.ThrowsAsync<NotSupportedException>(() => context.Authentication.ForbidAsync("Twitter"));
                 }
                 else if (handler == null || !handler(context))
                 {
                     await next();
                 }
             });
         })
         .ConfigureServices(services =>
         {
             services.AddAuthentication();
             services.Configure<SharedAuthenticationOptions>(authOptions =>
             {
                 authOptions.SignInScheme = "External";
             });
         });
     return new TestServer(builder);
 }