public RemoteSignOutContext(
     HttpContext context,
     OpenIdConnectOptions options,
     OpenIdConnectMessage message)
     : base(context, options)
 {
     ProtocolMessage = message;
 }
        public BaseOpenIdConnectContext(HttpContext context, OpenIdConnectOptions options)
            : base(context)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            Options = options;
        }
Beispiel #3
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseStaticFiles();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationScheme = "Cookies",
                AutomaticAuthenticate = true
            });

            var oidcOptions = new OpenIdConnectOptions
            {
                AuthenticationScheme = "oidc",
                SignInScheme = "Cookies",
                Authority = "http://localhost:47627",
                RequireHttpsMetadata = false,
                PostLogoutRedirectUri = "http://localhost:47834/",
                ClientId = "gabmileagemvc",
                ClientSecret = "diVeTryCOner",
                ResponseType = "code id_token",
                GetClaimsFromUserInfoEndpoint = true,
                SaveTokens = true
            };

            oidcOptions.Scope.Clear();
            oidcOptions.Scope.Add("openid");
            oidcOptions.Scope.Add("profile");
            oidcOptions.Scope.Add("gabMileageApi");

            app.UseOpenIdConnectAuthentication(oidcOptions);



            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
        /// <summary>
        /// Adds the <see cref="OpenIdConnectMiddleware"/> middleware to the specified <see cref="IApplicationBuilder"/>, which enables OpenID Connect authentication capabilities.
        /// </summary>
        /// <param name="app">The <see cref="IApplicationBuilder"/> to add the middleware to.</param>
        /// <param name="options">A <see cref="OpenIdConnectOptions"/> that specifies options for the middleware.</param>
        /// <returns>A reference to this instance after the operation has completed.</returns>
        public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, OpenIdConnectOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return app.UseMiddleware<OpenIdConnectMiddleware>(Options.Create(options));
        }
        public static IApplicationBuilder UseWingTipOpenIdConnectAuthentication(
            this IApplicationBuilder applicationBuilder,
            OpenIdConnectOptions options)
        {
            if (applicationBuilder == null)
            {
                throw new ArgumentNullException(nameof(applicationBuilder));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            return(applicationBuilder.UseMiddleware <WingTipOpenIdConnectMiddleware>(Options.Create(options)));
        }
 /// <summary>
 /// Creates a <see cref="AuthorizationCodeReceivedContext"/>
 /// </summary>
 public AuthorizationCodeReceivedContext(HttpContext context, OpenIdConnectOptions options)
     : base(context, options)
 {
 }
        public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddConsole(minLevel: LogLevel.Warning);

            app.UseStatusCodePagesWithRedirects("~/Home/StatusCodePage");

            // Display custom error page in production when error occurs
            // During development use the ErrorPage middleware to display error information in the browser
            app.UseDeveloperExceptionPage();

            app.UseDatabaseErrorPage();

            // Add the runtime information page that can be used by developers
            // to see what packages are used by the application
            // default path is: /runtimeinfo
            app.UseRuntimeInfoPage();

            // Configure Session.
            app.UseSession();

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

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

            // Create an Azure Active directory application and copy paste the following
            var options = new OpenIdConnectOptions
            {
                Authority = "https://login.windows.net/[tenantName].onmicrosoft.com",
                ClientId = "c99497aa-3ee2-4707-b8a8-c33f51323fef",
                BackchannelHttpHandler = new OpenIdConnectBackChannelHttpHandler(),
                StringDataFormat = new CustomStringDataFormat(),
                StateDataFormat = new CustomStateDataFormat(),
                UseTokenLifetime = false,

                Events = new OpenIdConnectEvents
                {
                    OnMessageReceived = TestOpenIdConnectEvents.MessageReceived,
                    OnAuthorizationCodeReceived = TestOpenIdConnectEvents.AuthorizationCodeReceived,
                    OnRedirectToIdentityProvider = TestOpenIdConnectEvents.RedirectToIdentityProvider,
                    OnTokenValidated = TestOpenIdConnectEvents.TokenValidated,
                }
            };
            options.TokenValidationParameters.ValidateLifetime = false;
            options.ProtocolValidator.RequireNonce = true;
            options.ProtocolValidator.NonceLifetime = TimeSpan.FromDays(36500);
            app.UseOpenIdConnectAuthentication(options);

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

                routes.MapRoute(
                    name: "default",
                    template: "{controller}/{action}/{id?}",
                    defaults: new { controller = "Home", action = "Index" });

                routes.MapRoute(
                    name: "api",
                    template: "{controller}/{id?}");
            });

            //Populates the MusicStore sample data
            SampleData.InitializeMusicStoreDatabaseAsync(app.ApplicationServices).Wait();
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<FranceConnectConfiguration> opts)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseBrowserLink();
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture("fr-FR") });

            app.UseStaticFiles();

            app.UseIdentity();

            // To configure external authentication please see http://go.microsoft.com/fwlink/?LinkID=532715
            var franceConnectOptions = new OpenIdConnectOptions();
            franceConnectOptions.AuthenticationScheme = Scheme.FranceConnect;
            franceConnectOptions.DisplayName = "FranceConnect";
            franceConnectOptions.ClientId = opts.Value.ClientId;
            franceConnectOptions.ClientSecret = opts.Value.ClientSecret;
            franceConnectOptions.Authority = opts.Value.Issuer;
            franceConnectOptions.ResponseType = OpenIdConnectResponseType.Code;
            franceConnectOptions.Scope.Clear();
            franceConnectOptions.Scope.Add("openid");
            franceConnectOptions.Scope.Add("profile");
            franceConnectOptions.Scope.Add("birth");
            franceConnectOptions.Scope.Add("email");
            franceConnectOptions.GetClaimsFromUserInfoEndpoint = true;
            franceConnectOptions.TokenValidationParameters.IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(opts.Value.ClientSecret));
            franceConnectOptions.Configuration = new OpenIdConnectConfiguration
            {
                Issuer = opts.Value.Issuer,
                AuthorizationEndpoint = opts.Value.AuthorizationEndpoint + "?acr_values=" + opts.Value.EIdas,
                TokenEndpoint = opts.Value.TokenEndpoint,
                UserInfoEndpoint = opts.Value.UserInfoEndpoint,
                EndSessionEndpoint = opts.Value.EndSessionEndpoint
            };
            app.UseOpenIdConnectAuthentication(franceConnectOptions);

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }
 public UserInformationReceivedContext(HttpContext context, OpenIdConnectOptions options)
     : base(context, options)
 {
 }
 /// <summary>
 /// Creates a <see cref="TokenResponseReceivedContext"/>
 /// </summary>
 public TokenResponseReceivedContext(HttpContext context, OpenIdConnectOptions options, AuthenticationProperties properties)
     : base(context, options)
 {
     Properties = properties;
 }
 private static void DefaultChallengeOptions(OpenIdConnectOptions options)
 {
     options.AuthenticationScheme = "OpenIdConnectHandlerTest";
     options.AutomaticChallenge = true;
     options.ClientId = Guid.NewGuid().ToString();
     options.ConfigurationManager = TestUtilities.DefaultOpenIdConnectConfigurationManager;
     options.StateDataFormat = new AuthenticationPropertiesFormaterKeyValue();
 }
 public MessageReceivedContext(HttpContext context, OpenIdConnectOptions options)
     : base(context, options)
 {
 }
 /// <summary>
 /// Creates a <see cref="TokenValidatedContext"/>
 /// </summary>
 public TokenValidatedContext(HttpContext context, OpenIdConnectOptions options)
     : base(context, options)
 {
 }
        private static void GenerateCorrelationId(HttpContext context, OpenIdConnectOptions options, AuthenticationProperties properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException(nameof(properties));
            }

            var bytes = new byte[32];
            CryptoRandom.GetBytes(bytes);
            var correlationId = Base64UrlTextEncoder.Encode(bytes);

            var cookieOptions = new CookieOptions
            {
                HttpOnly = true,
                Secure = context.Request.IsHttps,
                Expires = DateTimeOffset.UtcNow + options.ProtocolValidator.NonceLifetime
            };

            properties.Items[CorrelationProperty] = correlationId;

            var cookieName = CookieStatePrefix + OpenIdConnectDefaults.AuthenticationScheme + "." + correlationId;

            context.Response.Cookies.Append(cookieName, NonceProperty, cookieOptions);
        }
 private static OpenIdConnectOptions GetProtocolMessageOptions()
 {
     var options = new OpenIdConnectOptions();
     var fakeOpenIdRequestMessage = new FakeOpenIdConnectMessage(ExpectedAuthorizeRequest, ExpectedLogoutRequest);
     options.AutomaticChallenge = true;
     options.Events = new OpenIdConnectEvents()
     {
         OnRedirectToIdentityProvider = (context) =>
         {
             context.ProtocolMessage = fakeOpenIdRequestMessage;
             return Task.FromResult(0);
         },
         OnRedirectToIdentityProviderForSignOut = (context) =>
         {
             context.ProtocolMessage = fakeOpenIdRequestMessage;
             return Task.FromResult(0);
         }
     };
     options.ClientId = "Test Id";
     options.Configuration = TestUtilities.DefaultOpenIdConnectConfiguration;
     return options;
 }
        private OpenIdConnectOptions GetOptions(List<string> parameters, ExpectedQueryValues queryValues, ISecureDataFormat<AuthenticationProperties> secureDataFormat = null)
        {
            var options = new OpenIdConnectOptions();
            foreach (var param in parameters)
            {
                if (param.Equals(OpenIdConnectParameterNames.ClientId))
                    options.ClientId = queryValues.ClientId;
                else if (param.Equals(OpenIdConnectParameterNames.Resource))
                    options.Resource = queryValues.Resource;
                else if (param.Equals(OpenIdConnectParameterNames.Scope)) {
                    options.Scope.Clear();

                    foreach (var scope in queryValues.Scope.Split(' ')) {
                        options.Scope.Add(scope);
                    }
                }
            }

            options.Authority = queryValues.Authority;
            options.Configuration = queryValues.Configuration;
            options.StateDataFormat = secureDataFormat ?? new AuthenticationPropertiesFormaterKeyValue();

            return options;
        }
        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);
        }
        private static TestServer CreateServer(OpenIdConnectOptions options, Func<HttpContext, Task> handler = null, AuthenticationProperties properties = null)
        {
            var builder = new WebHostBuilder()
                .Configure(app =>
                {
                    app.UseCookieAuthentication(new CookieAuthenticationOptions
                    {
                        AuthenticationScheme = CookieAuthenticationDefaults.AuthenticationScheme
                    });
                    app.UseOpenIdConnectAuthentication(options);
                    app.Use(async (context, next) =>
                    {
                        var req = context.Request;
                        var res = context.Response;

                        if (req.Path == new PathString(Challenge))
                        {
                            await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme);
                        }
                        else if (req.Path == new PathString(ChallengeWithProperties))
                        {
                            await context.Authentication.ChallengeAsync(OpenIdConnectDefaults.AuthenticationScheme, properties);
                        }
                        else if (req.Path == new PathString(ChallengeWithOutContext))
                        {
                            res.StatusCode = 401;
                        }
                        else if (req.Path == new PathString(Signin))
                        {
                            // REVIEW: this used to just be res.SignIn()
                            await context.Authentication.SignInAsync(OpenIdConnectDefaults.AuthenticationScheme, new ClaimsPrincipal());
                        }
                        else if (req.Path == new PathString(Signout))
                        {
                            await context.Authentication.SignOutAsync(OpenIdConnectDefaults.AuthenticationScheme);
                        }
                        else if (req.Path == new PathString("/signout_with_specific_redirect_uri"))
                        {
                            await context.Authentication.SignOutAsync(
                                OpenIdConnectDefaults.AuthenticationScheme,
                                new AuthenticationProperties() { RedirectUri = "http://www.example.com/specific_redirect_uri" });
                        }
                        else if (handler != null)
                        {
                            await handler(context);
                        }
                        else
                        {
                            await next();
                        }
                    });
                })
                .ConfigureServices(services =>
                {
                    services.AddAuthentication();
                    services.Configure<SharedAuthenticationOptions>(authOptions =>
                    {
                        authOptions.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
                    });
                });
            return new TestServer(builder);
        }
Beispiel #19
0
 public RedirectContext(HttpContext context, OpenIdConnectOptions options, AuthenticationProperties properties)
     : base(context, options)
 {
     Properties = properties;
 }
 public static IApplicationBuilder UseOpenIdConnectAuthentication(this IApplicationBuilder app, OpenIdConnectOptions options)
 {
     throw new NotSupportedException("This method is no longer supported, see https://go.microsoft.com/fwlink/?linkid=845470");
 }
 public AuthenticationFailedContext(HttpContext context, OpenIdConnectOptions options)
     : base(context, options)
 {
 }