Пример #1
0
        public void Configuration(IAppBuilder app)
        {
            var cookieAuthenticationOptions = new CookieAuthenticationOptions
            {
                ExpireTimeSpan = TimeSpan.FromMinutes(15.0)
            };

            var openIdConnectOptions = new OpenIdConnectAuthenticationOptions
            {
                MetadataAddress            = "https://.../oauth2/oidcdiscovery/.well-known/openid-configuration",
                ResponseType               = OpenIdConnectResponseType.Code,
                ClientId                   = ClientId,
                Scope                      = OpenIdConnectScope.OpenId,
                RedirectUri                = RedirectUri,
                PostLogoutRedirectUri      = RedirectUri,
                UseTokenLifetime           = false,
                SignInAsAuthenticationType = "Cookies",
                Notifications              = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = OnRedirectToIdentityProvider,
                    MessageReceived            = OnMessageReceived,
                    AuthenticationFailed       = notification =>
                    {
                        return(Task.FromResult(0));
                    },
                    SecurityTokenReceived = notification =>
                    {
                        // Test to check if Owin middleware takes care of access token validation as per https://openid.net/specs/openid-connect-core-1_0.html#CodeFlowTokenValidation
                        //notification.ProtocolMessage.AccessToken = "foo";

                        return(Task.FromResult(0));
                    },
                    SecurityTokenValidated = notification =>
                    {
                        // Test to check if Owin middleware takes care of decoded id token validation of payload
                        //notification.ProtocolMessage.IdToken = notification.ProtocolMessage.IdToken + 'a';
                        notification.AuthenticationTicket.Identity.AddClaim(new Claim("access_token", notification.ProtocolMessage.AccessToken));
                        notification.AuthenticationTicket.Identity.AddClaim(new Claim("id_token_hint", notification.ProtocolMessage.IdTokenHint));
                        notification.AuthenticationTicket.Identity.AddClaim(new Claim("refresh_token", notification.ProtocolMessage.RefreshToken));
                        notification.AuthenticationTicket.Properties.IsPersistent = true;
                        // Below line required to avoid the error -
                        // Error appears to be caused due to Token endpoint being invoked explicitly from MessageReceived notification rather than AuthorizationCodeReceived notification
                        notification.ProtocolMessage.RefreshToken = null;
                        return(Task.FromResult(0));
                    }
                }
            };

            app.UseCookieAuthentication(cookieAuthenticationOptions);
            app.UseOpenIdConnectAuthentication(openIdConnectOptions);
        }
Пример #2
0
        //private IOIDCNotificationHandlerService _oidcNotificationHandlerService;

        /// <summary>
        ///     Helper class to be invoked from within Application's Startup Configuration method,
        ///     Configure the OWIN MiddleWare
        /// </summary>
        /// <param name="appBuilder"></param>
        /// <param name="keyVaultService"></param>
        /// <param name="oidcNotificationHandlerService"></param>
        public void Configure(IAppBuilder appBuilder)
        {
            //Get basic OIDC Config settings:
            IAadOidcSettingsConfidentialClientConfiguration aadOidcSettingsConfidentialClientConfiguration =
                _keyVaultService.GetObject <AadOidcSettingsConfidentialSettingsClientConfiguration>();

            //Same for AAD as for OIDC:
            appBuilder.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            //Same for AAD as for OIDC:
            appBuilder.UseCookieAuthentication(new CookieAuthenticationOptions());

            var openIdConnectAuthenticationOptions = new OpenIdConnectAuthenticationOptions
            {
                //AAD does not need MetadataAddress (whereas B2C does)
                //MetadataAddress = ...

                // Sets the ClientId, authority, RedirectUri as obtained from web.config
                ClientId              = aadOidcSettingsConfidentialClientConfiguration.ClientId,
                Authority             = aadOidcSettingsConfidentialClientConfiguration.AuthorityUri,
                RedirectUri           = aadOidcSettingsConfidentialClientConfiguration.ClientRedirectUri,
                PostLogoutRedirectUri = aadOidcSettingsConfidentialClientConfiguration.ClientPostLogoutUri,

                // Specify the scope by appending all of the scopes requested into one string (separated by a blank space)
                Scope = OpenIdConnectScope.OpenIdProfile,

                // ResponseType [IdToken|CodeIdToken] is set to request the id_token - which
                // contains basic information about the signed-in user
                ResponseType = OpenIdConnectResponseType.IdToken,

                // ValidateIssuer set to false to allow personal and work accounts from any organization
                // to sign in to your application.
                // To only allow users from a single organizations,
                // set ValidateIssuer to true and 'tenant' setting in web.config to the tenant name
                // To allow users from only a list of specific organizations, set ValidateIssuer to true and use ValidIssuers parameter
                TokenValidationParameters =
                    new TokenValidationParameters
                {
                    ValidateIssuer = false     /*ValidIssuers = ...*/
                },

                // OpenIdConnectAuthenticationNotifications configures OWIN
                // to send notification of failed authentications
                // to OnAuthenticationFailed method
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = OnAuthenticationFailed
                }
            };

            appBuilder.UseOpenIdConnectAuthentication(openIdConnectAuthenticationOptions);
        }
Пример #3
0
        // We need to update these values each time we receive a new token, so the SingleSignOut
        // javascript has access to the correct values.
        public async static Task SecurityTokenValidated(SecurityTokenValidatedNotification <OpenIdConnectMessage, OpenIdConnectAuthenticationOptions> notification)
        {
            // Get Tenant-Specific Metadata (Authorization Endpoint), needed for making prompt=none request in RedirectToIdentityProvider
            OpenIdConnectAuthenticationOptions tenantSpecificOptions = new OpenIdConnectAuthenticationOptions();

            tenantSpecificOptions.Authority            = AADInstance + notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;
            tenantSpecificOptions.ConfigurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(tenantSpecificOptions.Authority + "/.well-known/openid-configuration");
            OpenIdConnectConfiguration tenantSpecificConfig = await tenantSpecificOptions.ConfigurationManager.GetConfigurationAsync(notification.Request.CallCancelled);

            notification.AuthenticationTicket.Identity.AddClaim(new Claim("issEndpoint", tenantSpecificConfig.AuthorizationEndpoint, ClaimValueTypes.String, "WebApp-Distributed-SignOut-DotNet"));

            CheckSessionIFrame = notification.AuthenticationTicket.Properties.Dictionary[OpenIdConnectSessionProperties.CheckSessionIFrame];
            return;
        }
        public void Configuration(IAppBuilder app)
        {
            //Configure the Identity user manager for use with Umbraco Back office

            // *** EXPERT: There are several overloads of this method that allow you to specify a custom UserStore or even a custom UserManager!
            app.ConfigureUserManagerForUmbracoBackOffice(
                ApplicationContext.Current,
                //The Umbraco membership provider needs to be specified in order to maintain backwards compatibility with the
                // user password formats. The membership provider is not used for authentication, if you require custom logic
                // to validate the username/password against an external data source you can create create a custom UserManager
                // and override CheckPasswordAsync
                global::Umbraco.Core.Security.MembershipProviderExtensions.GetUsersMembershipProvider().AsUmbracoMembershipProvider());

            //Ensure owin is configured for Umbraco back office authentication
            app
            .UseUmbracoBackOfficeCookieAuthentication(ApplicationContext.Current)
            .UseUmbracoBackOfficeExternalCookieAuthentication(ApplicationContext.Current);

            var identityOptions = new OpenIdConnectAuthenticationOptions
            {
                ClientId = "u-client-bo",
                SignInAsAuthenticationType = Constants.Security.BackOfficeExternalAuthenticationType,
                Authority             = "http://localhost:5000",
                RedirectUri           = "http://localhost:5003/umbraco",
                PostLogoutRedirectUri = "http://localhost:5003/umbraco",
                ResponseType          = "code id_token token",
                Scope = "openid profile email application.profile application.policy"
            };

            // Configure BackOffice Account Link button and style
            identityOptions.ForUmbracoBackOffice("btn-microsoft", "fa-windows");
            identityOptions.Caption = "OpenId Connect";

            // Fix Authentication Type
            identityOptions.AuthenticationType = "http://localhost:5000";

            // Configure AutoLinking
            identityOptions.SetExternalSignInAutoLinkOptions(new ExternalSignInAutoLinkOptions(
                                                                 autoLinkExternalAccount: true,
                                                                 defaultUserGroups: null,
                                                                 defaultCulture: null
                                                                 ));

            identityOptions.Notifications = new OpenIdConnectAuthenticationNotifications
            {
                SecurityTokenValidated = EnrollUser.GenerateIdentityAsync
            };

            app.UseOpenIdConnectAuthentication(identityOptions);
        }
Пример #5
0
        public static IAppBuilder UseAzureAdAuthentication(this IAppBuilder app, AzureAdAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            var openIdOptions = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = "aad",
                Caption            = "AzureAD",
                Scope = "openid profile",
                SignInAsAuthenticationType = options.SignInAsAuthenticationType,

                Authority   = $"https://login.microsoftonline.com/{options.TenantId}",
                ClientId    = options.ClientId,
                RedirectUri = options.RedirectUri,

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = n =>
                    {
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnect.OpenIdConnectRequestType.Authentication)
                        {
                            var    signInMessage = n.OwinContext.Environment.GetSignInMessage();
                            string webServiceUrl = n.OwinContext.Environment.GetIdentityServerWebServiceUri();
                            if (signInMessage != null)
                            {
                                n.ProtocolMessage.Prompt = signInMessage.PromptMode;
                                n.ProtocolMessage.State  = $"{Base64Url.Encode(Encoding.UTF8.GetBytes(webServiceUrl))}.{n.ProtocolMessage.State}";
                            }
                        }

                        return(Task.FromResult(0));
                    }
                }
            };

            if (options.TenantId.StartsWith("common"))
            {
                openIdOptions.TokenValidationParameters.IssuerValidator = ValidateIssuerWithPlaceholder;
            }

            if (!string.IsNullOrEmpty(options.CallbackUri))
            {
                openIdOptions.CallbackPath = PathString.FromUriComponent(new Uri(options.CallbackUri));
            }

            return(app.UseOpenIdConnectAuthentication(openIdOptions));
        }
Пример #6
0
        public void ConfigureAuth(IAppBuilder app)
        {
            ApplicationDbContext db = new ApplicationDbContext();

            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions();

            options.ClientId              = SettingsHelper.ClientId;
            options.Authority             = SettingsHelper.AzureADAuthority;
            options.PostLogoutRedirectUri = SettingsHelper.LogoutAuthority;

            OpenIdConnectAuthenticationNotifications notifications = new OpenIdConnectAuthenticationNotifications();

            notifications.AuthorizationCodeReceived = (context) =>
            {
                string code = context.Code;

                AuthenticationHelper authHelper = new AuthenticationHelper();

                String signInUserId = context.AuthenticationTicket.Identity.FindFirst(ClaimTypes.NameIdentifier).Value;

                AuthenticationContext authContext = new AuthenticationContext(SettingsHelper.AzureADAuthAuthority);
                AuthenticationResult  result      = authContext.AcquireTokenByAuthorizationCode(code, new Uri(HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Path)), authHelper.GetClientAssertionCertificate(), null);

                return(Task.FromResult(0));
            };

            notifications.RedirectToIdentityProvider = (context) =>
            {
                string appBaseUrl = context.Request.Scheme + "://" + context.Request.Host + context.Request.PathBase;
                context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl;

                return(Task.FromResult(0));
            };

            notifications.AuthenticationFailed = (context) =>
            {
                context.HandleResponse();
                return(Task.FromResult(0));
            };

            options.Notifications = notifications;

            app.UseOpenIdConnectAuthentication(options);
        }
Пример #7
0
        private OpenIdConnectAuthenticationOptions CreateOptionsFromPolicy(string policy)
        {
            var resp = new OpenIdConnectAuthenticationOptions
            {
                MetadataAddress    = String.Format(aadInstance, tenant, policy),
                AuthenticationType = policy,

                ClientId      = clientId,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = SetResponseUrls,
                    AuthenticationFailed       = AuthenticationFailed,
                    SecurityTokenValidated     = async(ctx) =>
                    {
                        try
                        {
                            ctx.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(Constants.TenantTypeClaim, Constants.B2CTenantType));
                            var userId = ctx.AuthenticationTicket.Identity.Claims.First(c => c.Type == Constants.ObjectIdClaim).Value;
                            var roles  = db.UserRoles.Where(r => r.UserObjectId == userId);
                            if (roles.Count() > 0)
                            {
                                //TODO: use a persistent cookie to hold unto user tenant preference for future sessions
                                var tenantId   = roles.First().TenantId;
                                var tenantName = db.Tenants.First(t => t.Id == tenantId).Name;
                                ctx.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(Constants.TenantIdClaim, tenantId));
                                ctx.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(Constants.TenantNameClaim, tenantName));
                                foreach (var r in roles.Where(role => role.TenantId == tenantId))
                                {
                                    ctx.AuthenticationTicket.Identity.AddClaim(new System.Security.Claims.Claim(Constants.RoleClaim, r.Role));
                                }
                            }
                            await Task.FromResult(0);
                        } catch (Exception ex)
                        {
                            throw new SecurityTokenValidationException();
                        }
                    },
                },
                Scope        = "openid",
                ResponseType = "id_token",
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name",
                    RoleClaimType = "role",
                },
            };

            return(resp);
        }
Пример #8
0
        public static void ConfigureIdentityProviders(IAppBuilder app, string signInAsType)
        {
            var aad = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType         = "AzureAd",
                Caption                    = "Azure AD",
                SignInAsAuthenticationType = signInAsType,
                Authority                  = "https://login.microsoftonline.com/katsoupitsouhotmail.onmicrosoft.com",
                ClientId                   = "b0d36085-a8ab-4f18-b10b-c0384eefbab2",
                ClientSecret               = "Qw8vTzvMP8gFIiwhRRJKnaeNRKDhfMZnU0LwBx3NkmI=",
                RedirectUri                = "http://localhost:8570/identity/signin-azuread"
            };

            app.UseOpenIdConnectAuthentication(aad);
        }
 private static void CodeReceivedAndRedeemedSkippedOptions(OpenIdConnectAuthenticationOptions options)
 {
     DefaultOptions(options);
     options.ResponseType    = OpenIdConnectResponseTypes.Code;
     options.StateDataFormat = new AuthenticationPropertiesFormaterKeyValue();
     options.Notifications   =
         new OpenIdConnectAuthenticationNotifications
     {
         AuthorizationCodeRedeemed = (notification) =>
         {
             notification.SkipToNextMiddleware();
             return(Task.FromResult <object>(null));
         }
     };
 }
Пример #10
0
        /// <summary>
        /// Creates a new instance of OpenIdConnectAuthenticationOptions.
        /// </summary>
        /// <param name="oktaMvcOptions">The <see cref="OktaMvcOptions"/> options.</param>
        /// <param name="notifications">The OpenIdConnectAuthenticationNotifications notifications.</param>
        /// <returns>A new instance of OpenIdConnectAuthenticationOptions.</returns>
        public static OpenIdConnectAuthenticationOptions BuildOpenIdConnectAuthenticationOptions(OktaMvcOptions oktaMvcOptions, OpenIdConnectAuthenticationNotifications notifications)
        {
            var issuer     = UrlHelper.CreateIssuerUrl(oktaMvcOptions.OktaDomain, oktaMvcOptions.AuthorizationServerId);
            var httpClient = new HttpClient(new UserAgentHandler("okta-aspnet", typeof(OktaMiddlewareExtensions).Assembly.GetName().Version));

            var configurationManager = new ConfigurationManager <OpenIdConnectConfiguration>(
                issuer + "/.well-known/openid-configuration",
                new OpenIdConnectConfigurationRetriever(),
                new HttpDocumentRetriever(httpClient));

            var tokenValidationParameters = new DefaultTokenValidationParameters(oktaMvcOptions, issuer)
            {
                NameClaimType = "name",
                ValidAudience = oktaMvcOptions.ClientId,
                // CLIST: 2019-11-08 - save the claims token into the bootstrap context for k2
                SaveSigninToken = true,
            };

            var tokenExchanger = new TokenExchanger(oktaMvcOptions, issuer, configurationManager);
            var definedScopes  = oktaMvcOptions.Scope?.ToArray() ?? OktaDefaults.Scope;
            var scopeString    = string.Join(" ", definedScopes);

            var oidcOptions = new OpenIdConnectAuthenticationOptions
            {
                ClientId                  = oktaMvcOptions.ClientId,
                ClientSecret              = oktaMvcOptions.ClientSecret,
                Authority                 = issuer,
                RedirectUri               = oktaMvcOptions.RedirectUri,
                ResponseType              = OpenIdConnectResponseType.CodeIdToken,
                Scope                     = scopeString,
                PostLogoutRedirectUri     = oktaMvcOptions.PostLogoutRedirectUri,
                TokenValidationParameters = tokenValidationParameters,
                SecurityTokenValidator    = new StrictSecurityTokenValidator(),
                AuthenticationMode        = (oktaMvcOptions.LoginMode == LoginMode.SelfHosted) ? AuthenticationMode.Passive : AuthenticationMode.Active,
                Notifications             = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived  = tokenExchanger.ExchangeCodeForTokenAsync,
                    RedirectToIdentityProvider = notifications.RedirectToIdentityProvider,
                },
            };

            if (oktaMvcOptions.SecurityTokenValidated != null)
            {
                oidcOptions.Notifications.SecurityTokenValidated = oktaMvcOptions.SecurityTokenValidated;
            }

            return(oidcOptions);
        }
Пример #11
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var openIdSettings = new OpenIdConnectAuthenticationOptions()
            {
                ClientId              = clientId,
                Authority             = authority,
                PostLogoutRedirectUri = postLogoutRedirectUri
            };

            app.UseOpenIdConnectAuthentication(openIdSettings);
            LogSettings(openIdSettings);
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            var authProvider = new CookieAuthenticationProvider
            {
                OnResponseSignIn = ctx =>
                {
                    //ctx.Identity = StartupAuth.InitAuth(ctx);
                }
            };
            var cookieOptions = new CookieAuthenticationOptions
            {
                Provider = authProvider
            };

            app.UseCookieAuthentication(cookieOptions);

            // Required for AAD
            OpenIdConnectAuthenticationOptions Options = new OpenIdConnectAuthenticationOptions
            {
                Authority = string.Format(aadInstance, tenant),
                ClientId  = clientId,
                //ProtocolValidator = new OpenIdConnectProtocolValidator
                //{
                //    RequireNonce = false
                //},
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    RedirectToIdentityProvider = (context) =>
                    {
                        string appBaseUrl = string.Format("{0}://{1}{2}", context.Request.Scheme, context.Request.Host, context.Request.PathBase);
                        context.ProtocolMessage.RedirectUri           = appBaseUrl + "/";
                        context.ProtocolMessage.PostLogoutRedirectUri = appBaseUrl + "/Account/SignedOut";
                        return(Task.FromResult(0));
                    },
                },
                TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                },
                AuthenticationType = CustomAuthTypes.B2E,
            };

            app.UseOpenIdConnectAuthentication(Options);
        }
Пример #13
0
        private static OpenIdConnectAuthenticationOptions GetOpenIdConnectAuthenticationOptions(IdentityProviderClientConfigurationElement provider)
        {
            OpenIdConnectAuthenticationOptions options = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = provider.Name,
                Caption            = provider.Name,
                ClientId           = provider.ClientId,
                Authority          = provider.Issuer.ToString(),
                RedirectUri        = provider.RedirectUrl.ToString(),
                // Leveraging Authorization Code grant
                ResponseType  = "code",
                Scope         = "openid email",
                Notifications = GetOpenIdConnectAuthenticationNotifications()
            };

            return(options);
        }
 private static void AuthorizationCodeReceivedHandledOptions(OpenIdConnectAuthenticationOptions options)
 {
     DefaultOptions(options);
     options.SecurityTokenValidators = new Collection <ISecurityTokenValidator> {
         MockSecurityTokenValidator()
     };
     options.ProtocolValidator = MockProtocolValidator();
     options.Notifications     =
         new OpenIdConnectAuthenticationNotifications
     {
         AuthorizationCodeReceived = (notification) =>
         {
             notification.HandleResponse();
             return(Task.FromResult <object>(null));
         }
     };
 }
 private static void AuthenticationErrorSkippedOptions(OpenIdConnectAuthenticationOptions options)
 {
     DefaultOptions(options);
     options.SecurityTokenValidators = new Collection <ISecurityTokenValidator> {
         MockSecurityTokenValidator()
     };
     options.ProtocolValidator = MockProtocolValidator();
     options.Notifications     =
         new OpenIdConnectAuthenticationNotifications
     {
         AuthenticationFailed = (notification) =>
         {
             notification.SkipToNextMiddleware();
             return(Task.FromResult <object>(null));
         }
     };
 }
        private static void SetProtocolMessageOptions(OpenIdConnectAuthenticationOptions options)
        {
            var mockOpenIdConnectMessage = new Mock <OpenIdConnectMessage>();

            mockOpenIdConnectMessage.Setup(m => m.CreateAuthenticationRequestUrl()).Returns(ExpectedAuthorizeRequest);
            mockOpenIdConnectMessage.Setup(m => m.CreateLogoutRequestUrl()).Returns(ExpectedLogoutRequest);
            options.AutomaticAuthentication = true;
            options.Notifications           =
                new OpenIdConnectAuthenticationNotifications
            {
                RedirectToIdentityProvider = (notification) =>
                {
                    notification.ProtocolMessage = mockOpenIdConnectMessage.Object;
                    return(Task.FromResult <object>(null));
                }
            };
        }
Пример #17
0
        /// <summary>
        /// Adds the <see cref="OpenIdConnectAuthenticationMiddleware"/> into the OWIN runtime.
        /// </summary>
        /// <param name="app">The <see cref="IAppBuilder"/> passed to the configuration method</param>
        /// <param name="openIdConnectOptions">A <see cref="OpenIdConnectAuthenticationOptions"/> contains settings for obtaining identities using the OpenIdConnect protocol.</param>
        /// <returns>The updated <see cref="IAppBuilder"/></returns>
        public static IAppBuilder UseOpenIdConnectAuthentication(this IAppBuilder app,
                                                                 OpenIdConnectAuthenticationOptions openIdConnectOptions)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }

            if (openIdConnectOptions == null)
            {
                throw new ArgumentNullException("openIdConnectOptions");
            }

            app.Use(typeof(OpenIdConnectAuthenticationMiddleware), app, openIdConnectOptions);
            app.UseStageMarker(PipelineStage.PostAcquireState);
            return(app);
        }
        public IEnumerable <OwinMiddlewareRegistration> GetOwinMiddlewares()
        {
            var middlewares = new List <OwinMiddlewareRegistration>();

            AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

            var openIdOptions = new OpenIdConnectAuthenticationOptions {
                ClientId              = _azureClientId,
                Authority             = string.Format(CultureInfo.InvariantCulture, _azureADInstance, _azureTenant),
                PostLogoutRedirectUri = _logoutRedirectUri,
                Notifications         = new OpenIdConnectAuthenticationNotifications()
            };

            var cookieOptions = new CookieAuthenticationOptions();

            var bearerAuthOptions = new WindowsAzureActiveDirectoryBearerAuthenticationOptions {
                TokenValidationParameters = new TokenValidationParameters {
                    ValidAudience = string.Format(_sslEnabled ? "https://{0}/{1}" : "http://{0}/{1}", _azureTenant, _azureAppName)
                }
            };

            if (_azureWebSiteProtectionEnabled)
            {
                middlewares.Add(new OwinMiddlewareRegistration {
                    Priority  = "9",
                    Configure = app => { app.SetDataProtectionProvider(new MachineKeyProtectionProvider()); }
                });
            }

            middlewares.Add(new OwinMiddlewareRegistration {
                Priority  = "10",
                Configure = app => {
                    app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

                    app.UseCookieAuthentication(cookieOptions);

                    app.UseOpenIdConnectAuthentication(openIdOptions);

                    //This is throwing an XML DTD is prohibited error?
                    //app.UseWindowsAzureActiveDirectoryBearerAuthentication(bearerAuthOptions);
                }
            });

            return(middlewares);
        }
        protected override void AttachToOwinApp(IGalleryConfigurationService config, IAppBuilder app)
        {
            // Fetch site root from configuration
            var siteRoot = config.Current.SiteRoot.TrimEnd('/') + "/";

            // We *always* require SSL for Authentication
            if (siteRoot.StartsWith("http://", StringComparison.OrdinalIgnoreCase))
            {
                siteRoot = siteRoot.Replace("http://", "https://");
            }

            if (!string.IsNullOrWhiteSpace(config.Current.AlternateSiteRootList))
            {
                var alternateSiteRootList = config
                                            .Current
                                            .AlternateSiteRootList
                                            .Split(';')
                                            .Select(d => d.Trim())
                                            .ToArray();

                _alternateSiteRootList = new HashSet <string>(alternateSiteRootList, StringComparer.OrdinalIgnoreCase);
            }

            // Configure OpenIdConnect
            var options = new OpenIdConnectAuthenticationOptions(BaseConfig.AuthenticationType)
            {
                RedirectUri           = siteRoot + _callbackPath,
                PostLogoutRedirectUri = siteRoot,
                Scope        = OpenIdConnectScope.OpenIdProfile + " email",
                ResponseType = OpenIdConnectResponseType.CodeIdToken,
                TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidateIssuer = false
                },
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed       = AuthenticationFailed,
                    RedirectToIdentityProvider = RedirectToIdentityProvider
                }
            };

            Config.ApplyToOwinSecurityOptions(options);

            app.UseOpenIdConnectAuthentication(options);
        }
        public void Configuration(IAppBuilder app)
        {
            JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary <string, string>();

            app.UseCookieAuthentication(new CookieAuthenticationOptions
            {
                AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie
            });

            var options = new OpenIdConnectAuthenticationOptions
            {
                ClientId              = "getstartedimplicit",
                Authority             = "http://localhost:53189/",
                RedirectUri           = "http://localhost:64584/",
                PostLogoutRedirectUri = "http://localhost:64584/",
                ResponseType          = "id_token token",
                Scope = "openid profile",
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    SecurityTokenValidated = notification =>
                    {
                        var identity = notification.AuthenticationTicket.Identity;
                        identity.AddClaim(new Claim("id_token", notification.ProtocolMessage.IdToken));
                        identity.AddClaim(new Claim("access_token", notification.ProtocolMessage.AccessToken));

                        notification.AuthenticationTicket = new AuthenticationTicket(identity, notification.AuthenticationTicket.Properties);

                        return(Task.FromResult(0));
                    },
                    RedirectToIdentityProvider = notification =>
                    {
                        if (notification.ProtocolMessage.RequestType != OpenIdConnectRequestType.LogoutRequest)
                        {
                            return(Task.FromResult(0));
                        }

                        notification.ProtocolMessage.IdTokenHint = notification.OwinContext.Authentication.User.FindFirst("id_token").Value;
                        return(Task.FromResult(0));
                    }
                }
            };

            app.UseOpenIdConnectAuthentication(options);
        }
        public static IAppBuilder UseMultitenantAadOidcAuthentication(this IAppBuilder app, MultitenantAadOidcOptions options)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }

            var aad = new OpenIdConnectAuthenticationOptions
            {
                AuthenticationType = options.AuthenticationType,
                Caption            = options.Caption,
                RedirectUri        = options.RedirectUri,
                ClientId           = options.MultitenantAppId.ToString(),
                Authority          = options.Authority,
                Scope         = "openid email",
                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    RedirectToIdentityProvider = (n) =>
                    {
                        var metadata = MetadataHelper.GetMetadataDocumentAsync("https://login.microsoftonline.com/lesterjtgmail.onmicrosoft.com/.well-known/openid-configuration", n.OwinContext.Request.CallCancelled).Result;
                        OpenIdConnectConfiguration config = new OpenIdConnectConfiguration(metadata);

                        //these values affect the redirect
                        n.ProtocolMessage.IssuerAddress = config.AuthorizationEndpoint;
                        n.ProtocolMessage.ClientId      = "4deaba2a-548d-47bc-809f-e010a0841769";

                        //these values affect the token validation when the reponse is received
                        n.Options.TokenValidationParameters.ValidAudience = "4deaba2a-548d-47bc-809f-e010a0841769";
                        n.Options.TokenValidationParameters.ValidIssuer   = config.Issuer;

                        return(Task.FromResult(0));
                    }
                },
                SignInAsAuthenticationType = options.SignInAsAuthenticationType
            };

            app.UseOpenIdConnectAuthentication(aad);

            return(app);
        }
Пример #22
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);
            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var oidcOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority    = OidcAuthority,
                ClientId     = OidcClientId,
                ClientSecret = OidcClientSecret,
                GetClaimsFromUserInfoEndpoint = true,
                PostLogoutRedirectUri         = OidcRedirectUrl,
                RedirectUri  = OidcRedirectUrl,
                ResponseType = OpenIdConnectResponseType.Code,
                Scope        = OpenIdConnectScope.OpenId
            };

            app.UseOpenIdConnectAuthentication(oidcOptions);
        }
Пример #23
0
 private static void ConfigureOpenIdConnectOptions(OktaMvcOptions oktaMvcOptions,
                                                   OpenIdConnectAuthenticationOptions oidcOptions)
 {
     oidcOptions.ClientId               = oktaMvcOptions.ClientId;
     oidcOptions.ClientSecret           = oktaMvcOptions.ClientSecret;
     oidcOptions.Authority              = domain;
     oidcOptions.CallbackPath           = new PathString("");
     oidcOptions.PostLogoutRedirectUri  = oktaMvcOptions.PostLogoutRedirectUri;
     oidcOptions.ResponseType           = "code id_token";
     oidcOptions.SecurityTokenValidator = new System.IdentityModel.Tokens.Jwt.JwtSecurityTokenHandler();
     oidcOptions.UseTokenLifetime       = true;
     oidcOptions.RedirectUri            = EnsureTrailingSlash(oktaMvcOptions.RedirectUri);
     oidcOptions.Scope = "openid profile";
     oidcOptions.TokenValidationParameters = new DefaultTokenValidationParameters(oktaMvcOptions, "Okta")
     {
         ValidAudience = oktaMvcOptions.ClientId,
         NameClaimType = "preferred_username",
     };
 }
Пример #24
0
 public void Signup(OpenIdConnectAuthenticationOptions openIdConnectOptions)
 {
     if (!Context.User.Identity.IsAuthenticated)
     {
         Context.Response.Redirect(
             $"https://login.microsoftonline.com/{Startup.Tenant}/oauth2/v2.0/authorize" +
             $"&client_id={Startup.SignUpPolicyId}" +
             $"&client_id={Startup.ClientId}" +
             "&response_type=id_token" +
             "&scope=openid" +
             "&response_mode=form_post" +
             $"&redirect_uri={Startup.RedirectUrl}"
             );
     }
     else
     {
         Context.Response.Redirect("/");
     }
 }
Пример #25
0
        protected override void ProcessCore(IdentityProvidersArgs args)
        {
            Assert.ArgumentNotNull(args, "args");
            IdentityProvider = this.GetIdentityProvider();

            var options = new OpenIdConnectAuthenticationOptions
            {
                ClientId                  = ClientId,
                ClientSecret              = ClientSecret,
                Authority                 = Authority,
                RedirectUri               = OAuthRedirectUri,
                ResponseType              = OpenIdConnectResponseType.CodeIdToken,
                Scope                     = OpenIdScope,
                AuthenticationType        = IdentityProvider.Name,
                TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = "name"
                },

                Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthorizationCodeReceived  = ProcessAuthorizationCodeReceived,
                    RedirectToIdentityProvider = n =>
                    {
                        // If signing out, add the id_token_hint
                        if (n.ProtocolMessage.RequestType == Microsoft.IdentityModel.Protocols.OpenIdConnectRequestType.LogoutRequest)
                        {
                            var idTokenClaim = n.OwinContext.Authentication.User.FindFirst("id_token");

                            if (idTokenClaim != null)
                            {
                                n.ProtocolMessage.IdTokenHint = idTokenClaim.Value;
                            }
                        }

                        return(Task.CompletedTask);
                    }
                }
            };

            args.App.UseOpenIdConnectAuthentication(options);
        }
Пример #26
0
        /// <summary>
        /// Configures the application to use Azure AD with Power BI
        /// </summary>
        /// <param name="app">The OWIN app builder</param>
        /// <param name="options">The autheentication options</param>
        /// <returns>The OWIN app build</returns>
        /// <exception cref="ArgumentNullException"></exception>
        public static IAppBuilder UsePowerBIAuthentication(this IAppBuilder app, PowerBIAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            ValidateOptions(options);

            var openIdAuthOptions = new OpenIdConnectAuthenticationOptions
            {
                ClientId     = options.ClientId,
                ClientSecret = options.ClientSecret,
                Authority    = options.Authority,
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidIssuer    = options.Issuer,
                    ValidateIssuer = options.ValidateIssuer
                },
                Notifications = new OpenIdConnectAuthenticationNotifications()
                {
                    AuthorizationCodeReceived = (context) =>
                    {
                        OnAuthorizationCodeReceived(context, options);
                        return(Task.FromResult(0));
                    },
                    AuthenticationFailed = (context) =>
                    {
                        var redirectUri = options.ErrorRedirectUri ?? new Uri("/", UriKind.Relative);
                        context.OwinContext.Response.Redirect(redirectUri.ToString());
                        context.HandleResponse();
                        return(Task.FromResult(0));
                    }
                }
            };

            app.UseOpenIdConnectAuthentication(openIdAuthOptions);
            ConfigureTokenManager();

            return(app);
        }
 private static void GetUserInfoFromUIEndpoint(OpenIdConnectAuthenticationOptions options)
 {
     DefaultOptions(options);
     options.ResponseType    = OpenIdConnectResponseTypes.Code;
     options.StateDataFormat = new AuthenticationPropertiesFormaterKeyValue();
     options.GetClaimsFromUserInfoEndpoint = true;
     options.SecurityTokenValidators       = new Collection <ISecurityTokenValidator> {
         MockSecurityTokenValidator()
     };
     options.Notifications =
         new OpenIdConnectAuthenticationNotifications
     {
         SecurityTokenValidated = (notification) =>
         {
             var claimValue = notification.AuthenticationTicket.Principal.FindFirst("test claim");
             Assert.Equal(claimValue.Value, "test value");
             notification.HandleResponse();
             return(Task.FromResult <object>(null));
         }
     };
 }
Пример #28
0
        private void ConfigureAuth(IAppBuilder app)
        {
            var cookieOptions = new CookieAuthenticationOptions();

            app.UseCookieAuthentication(cookieOptions);

            app.SetDefaultSignInAsAuthenticationType(cookieOptions.AuthenticationType);

            OpenIdConnectAuthenticationOptions oidcOptions = new OpenIdConnectAuthenticationOptions
            {
                Authority    = "https://localhost:5000",
                ClientId     = "mvc",
                ClientSecret = "49C1A7E1-0C79-4A89-A3D6-A37998FB86B0",
                RedirectUri  = "https://localhost:44348/signin-oidc",
                ResponseType = "code",
                RedeemCode   = true,
                SaveTokens   = true
            };

            app.UseOpenIdConnectAuthentication(oidcOptions);
        }
Пример #29
0
        public void ConfigureAuth(IAppBuilder app)
        {
            app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

            app.UseCookieAuthentication(new CookieAuthenticationOptions());

            var opt = new OktaMvcOptions()
            {
                ClientSecret          = clientSecret,
                ClientId              = clientId,
                OktaDomain            = domain,
                PostLogoutRedirectUri = postLogoutRedirectUri,
                RedirectUri           = redirectUri
            };
            var oidOptions = new OpenIdConnectAuthenticationOptions();

            ConfigureOpenIdConnectOptions(opt, oidOptions);
            LogSettings(oidOptions);

            app.UseOpenIdConnectAuthentication(oidOptions);
        }
Пример #30
0
        private static void ConfigureOpenIdForFrontEnd(IAppBuilder app)
        {
            // Uncomment the following lines to enable logging in with third party login providers

            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);

            //app.UseMicrosoftAccountAuthentication(
            //  clientId: "",
            //  clientSecret: "");

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

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

            //app.UseGoogleAuthentication(
            //  clientId: "",
            //  clientSecret: "");

            var identityOptions
                = new OpenIdConnectAuthenticationOptions
                {
                ClientId     = ConfigurationManager.AppSettings["FE_READYCONNECT_CLIENT_ID"],      // This client has already been registered. You may register more via https://members.readysignon.com
                Caption      = ConfigurationManager.AppSettings["FE_READYCONNECT_CLIENT_CAPTION"], // Text used for displaying this sign-in option on the login page.
                ResponseType = "code id_token token",                                              // This corresponds to the Hybrid Flow outlined in oidc core spec 1.0.
                Scope        = ConfigurationManager.AppSettings["FE_READYCONNECT_SCOPES"],         // When rso_rid is absent, rso_idp is used.
                SignInAsAuthenticationType = DefaultAuthenticationTypes.ExternalCookie,
                Authority             = "https://members.readysignon.com/",
                RedirectUri           = ConfigurationManager.AppSettings["MAIN_SITE_BASE_URL"], // This shouldn't be changed if you're running this code locally unless you want to register your own client application at https://members.readysignon.com
                PostLogoutRedirectUri = ConfigurationManager.AppSettings["MAIN_SITE_BASE_URL"]
                };

            // Give this middleware a unique type name
            identityOptions.AuthenticationType = "readyconnectsvc_for_umbraco_fe";

            ConfigureIdentityCreationAndCustomHandlers(app, identityOptions, autoLinkExternalAccount: true);
        }
Пример #31
0
	public static void ConfigureBackOfficeAzureActiveDirectoryA2BAuth(this IAppBuilder app, 
		string tenant, 
		string clientId, 
		string clientSecret, 
		string redirectUri, 
		string signUpPolicyId, 
		string signInPolicyId, 
		string userProfilePolicyId,
		
		string adminClientId,
		string adminClientSecret,
		
		//Guid issuerId,
		string caption = "Active Directory", string style = "btn-microsoft", string icon = "fa-windows")
	{

		//ORIGINAL OPTIONS SUPPLIED BY SAMPLE B2C APP

		//var options = new OpenIdConnectAuthenticationOptions
		//{
		//    // These are standard OpenID Connect parameters, with values pulled from web.config
		//    ClientId = clientId,
		//    RedirectUri = redirectUri,
		//    PostLogoutRedirectUri = redirectUri,
		//    Notifications = new OpenIdConnectAuthenticationNotifications
		//    {
		//        AuthenticationFailed = AuthenticationFailed,
		//        RedirectToIdentityProvider = OnRedirectToIdentityProvider,
		//    },
		//    Scope = "openid",
		//    ResponseType = "id_token",

		//    // The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
		//    // endpoints from the OpenID Connect metadata endpoint.  It is included in the PolicyAuthHelpers folder.
		//    ConfigurationManager = new PolicyConfigurationManager(
		//        string.Format(CultureInfo.InvariantCulture, AADInstance, tenant, "/v2.0", OIDCMetadataSuffix),
		//        new string[] { signUpPolicyId, signInPolicyId, userProfilePolicyId }),

		//    // This piece is optional - it is used for displaying the user's name in the navigation bar.
		//    TokenValidationParameters = new TokenValidationParameters
		//    {
		//        NameClaimType = "name"
		//    },
		//};

		var adOptions = new OpenIdConnectAuthenticationOptions
		{                         
			ClientId = clientId,                
			RedirectUri = redirectUri,
			PostLogoutRedirectUri = redirectUri,
			Notifications = new OpenIdConnectAuthenticationNotifications
			{
				//AuthenticationFailed = AuthenticationFailed,
				RedirectToIdentityProvider = OnRedirectToIdentityProvider,

				////When the user is authorized and we are not asking for an id_token (see way below for details on that),
				//// we will get an auth code which we can then use to retrieve information about the user.
				//AuthorizationCodeReceived = async notification =>
				//{
				//    // The user's objectId is extracted from the claims provided in the id_token, and used to cache tokens in ADAL
				//    // The authority is constructed by appending your B2C directory's name to "https://login.microsoftonline.com/"
				//    // The client credential is where you provide your application secret, and is used to authenticate the application to Azure AD
				//    var userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
				//    var authority = string.Format(CultureInfo.InvariantCulture, AADInstance, tenant, string.Empty, string.Empty);
				//    var credential = new ClientCredential(clientId, clientSecret);

				//    // We don't care which policy is used to access the TaskService, so let's use the most recent policy as indicated in the sign-in token
				//    var mostRecentPolicy = notification.AuthenticationTicket.Identity.FindFirst(AcrClaimType).Value;

				//    // The Authentication Context is ADAL's primary class, which represents your connection to your B2C directory
				//    // ADAL uses an in-memory token cache by default.  In this case, we've extended the default cache to use a simple per-user session cache
				//    var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));

				//    // Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
				//    // The token will be stored in the ADAL token cache, for use in our controllers
				//    var result = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), credential, new string[] { clientId }, mostRecentPolicy);

				//    //var userDetails = await GetUserByObjectId(result, userObjectId, tenant, clientId, clientSecret);

				//    var asdf = result;
				//},
				MessageReceived = notification =>
				{
					return Task.FromResult(0);
				},
				SecurityTokenReceived = notification =>
				{
					return Task.FromResult(0);
				},
				SecurityTokenValidated = notification =>
				{
					//var userObjectId = notification.AuthenticationTicket.Identity.FindFirst("http://schemas.microsoft.com/identity/claims/objectidentifier").Value;
					//var authority = string.Format(CultureInfo.InvariantCulture, AADInstance, tenant, string.Empty, string.Empty);
					//var credential = new ClientCredential(clientId, clientSecret);

					// We don't care which policy is used to access the TaskService, so let's use the most recent policy
					//var mostRecentPolicy = notification.AuthenticationTicket.Identity.FindFirst(AcrClaimType).Value;

					// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
					// AcquireTokenSilentAsync will return a token from the token cache, and throw an exception if it cannot do so.
					//var authContext = new AuthenticationContext(authority, new NaiveSessionCache(userObjectId));

					//var result = await authContext.AcquireTokenSilentAsync(new string[] { clientId }, credential, UserIdentifier.AnyUser, mostRecentPolicy);

					// Here you ask for a token using the web app's clientId as the scope, since the web app and service share the same clientId.
					// The token will be stored in the ADAL token cache, for use in our controllers
					//var result = await authContext.AcquireTokenByAuthorizationCodeAsync(notification.Code, new Uri(redirectUri), credential, new string[] { clientId }, mostRecentPolicy);

					//var asdf = result;



					//The returned identity doesn't actually have 'email' as a claim, but instead has a collection of "emails", so we're going to ensure one is 
					// in there and then set the Email claim to be the first so that auto-signin works
					var emails = notification.AuthenticationTicket.Identity.FindFirst("emails");
					if (emails != null)
					{
						var email = emails.Value;
						notification.AuthenticationTicket.Identity.AddClaim(new Claim(ClaimTypes.Email, email));
					}
					

					return Task.FromResult(0);
				}                    
			},

			//NOTE: in this article they are requesting this scope: https://azure.microsoft.com/en-us/documentation/articles/active-directory-b2c-devquickstarts-web-api-dotnet/
			// I'm unsure if we leave off the offline_access part if we'd get an authcode request back or not, so leaving it here
			// for now since it is working.
			//Scope = "openid offline_access",

			Scope = "openid",

			//NOTE: If we ask for this, then we'll simply get an ID Token back which we cannot use to request
			// additional data of the user. We need to get an authorization code reponse (I'm not sure what the 
			// string value for that is but if we don't specify then it's the default). 
			ResponseType = "id_token",

			// The PolicyConfigurationManager takes care of getting the correct Azure AD authentication
			// endpoints from the OpenID Connect metadata endpoint.  It is included in the PolicyAuthHelpers folder.
			// The first parameter is the metadata URL of your B2C directory
			// The second parameter is an array of the policies that your app will use.
			ConfigurationManager = new PolicyConfigurationManager(
				string.Format(CultureInfo.InvariantCulture, AADInstance, tenant, "/v2.0", OIDCMetadataSuffix),
				new string[] { signUpPolicyId, signInPolicyId, userProfilePolicyId }),

			// This piece is optional - it is used for displaying the user's name in the navigation bar.
			TokenValidationParameters = new TokenValidationParameters
			{
				NameClaimType = "name",
			},

			SignInAsAuthenticationType = Umbraco.Core.Constants.Security.BackOfficeExternalAuthenticationType
		};

		adOptions.SetChallengeResultCallback(context => new AuthenticationProperties(
			new Dictionary<string, string>
			{
				{UmbracoADAuthExtensions.PolicyKey, signInPolicyId}
			})
		{
			RedirectUri = "/Umbraco",
		});
		
		var orig = adOptions.AuthenticationType;
		adOptions.ForUmbracoBackOffice(style, icon);
		adOptions.AuthenticationType = orig;

		adOptions.Caption = caption;

		//NOTE: This needs to be set after the ForUmbracoBackOffice
		// this needs to be set to what AD returns otherwise you cannot unlink an account
		adOptions.AuthenticationType = string.Format(
			CultureInfo.InvariantCulture,
			"https://login.microsoftonline.com/{0}/v2.0/",
			//Not sure where this comes from! ... perhaps 'issuerId', but i don't know where to find this,
			// i just know this based on the response we get from B2C
			"ae25bf5e-871e-454a-a1b6-a3560a09ec5e");

		//This will auto-create users based on the authenticated user if they are new
		//NOTE: This needs to be set after the explicit auth type is set
		adOptions.SetExternalSignInAutoLinkOptions(new ExternalSignInAutoLinkOptions(autoLinkExternalAccount: true));

		app.UseOpenIdConnectAuthentication(adOptions);            
	}