/// <summary>
        /// Adds Windows Azure Active Directory (WAAD) issued JWT bearer token middleware to your web application pipeline.
        /// </summary>
        /// <param name="app">The IAppBuilder passed to your configuration method.</param>
        /// <param name="options">An options class that controls the middleware behavior.</param>
        /// <returns>The original app parameter.</returns>
        public static IAppBuilder UseWindowsAzureActiveDirectoryBearerAuthentication(this IAppBuilder app, WindowsAzureActiveDirectoryBearerAuthenticationOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException("options");
            }
            if (string.IsNullOrWhiteSpace(options.Tenant))
            {
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Exception_OptionMustBeProvided, "Tenant"));
            }

            var bearerOptions = new OAuthBearerAuthenticationOptions
            {
                Realm = options.Realm,
                Provider = options.Provider,
                AccessTokenFormat = new JwtFormat(options.Audience,
                    new WsFedCachingSecurityTokenProvider(
                        string.Format(CultureInfo.InvariantCulture, SecurityTokenServiceAddressFormat, options.Tenant),
                        options.BackchannelCertificateValidator, options.BackchannelTimeout, options.BackchannelHttpHandler)),
                AuthenticationMode = options.AuthenticationMode,
                AuthenticationType = options.AuthenticationType,
                Description = options.Description
            };

            app.UseOAuthBearerAuthentication(bearerOptions);

            return app;
        }
        public void ConfigureAuth(IAppBuilder app)
        {
            WindowsAzureActiveDirectoryBearerAuthenticationOptions options = new WindowsAzureActiveDirectoryBearerAuthenticationOptions()
            {
                Tenant = ConfigurationManager.AppSettings["aad:Audience"],
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters()
                {
                    ValidAudience = ConfigurationManager.AppSettings["aad:Audience"]
                },
            };

            app.UseWindowsAzureActiveDirectoryBearerAuthentication(options);
        }
        public AmazonWebServicesProvider(
            string credentialsProfileName, 
            WindowsAzureActiveDirectoryBearerAuthenticationOptions authenticationOptions)
        {
            if (string.IsNullOrWhiteSpace(credentialsProfileName))
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameCredentialsProfileName);
            }

            if (null == authenticationOptions)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameAuthenticationOptions);
            }

            this.anchoringBehaviorValue = new AnchoringByIdentifierBehavior();
            this.Initialize(credentialsProfileName, this.anchoringBehaviorValue, authenticationOptions);
        }
        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;
        }
        private void Initialize(
            string credentialsProfileName,
            IAmazonWebServicesIdentityAnchoringBehavior anchoringBehavior,
            AuthenticationOptions authenticationOptions)
        {
            if (string.IsNullOrWhiteSpace(credentialsProfileName))
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameCredentialsProfileName);
            }

            if (null == anchoringBehavior)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameAnchoringBehavior);
            }

            if (null == authenticationOptions)
            {
                throw new ArgumentNullException(AmazonWebServicesProvider.ArgumentNameAuthenticationOptions);
            }

            this.credentials = new StoredProfileAWSCredentials(credentialsProfileName);

            this.anchoringBehaviorValue = anchoringBehavior;
            
            this.windowsAzureActiveDirectoryBearerAuthenticationOptions = 
                authenticationOptions as WindowsAzureActiveDirectoryBearerAuthenticationOptions;
            if (this.windowsAzureActiveDirectoryBearerAuthenticationOptions != null)
            {
                this.windowsAzureActiveDirectoryBearerAuthenticationOptions.TokenHandler = new TokenHandler();
            }
        }
        private void OnServiceStartup(IAppBuilder applicationBuilder, HttpConfiguration configuration)
        {
            logger.Info("OnServiceStartup.... ###############");

            // pvs
            // IFilter is defined in System.Web.Http.dll.  
            System.Web.Http.Filters.IFilter authorizationFilter =
              new System.Web.Http.AuthorizeAttribute(); // Defined in System.Web.Http.dll.configuration.Filters.Add(authorizationFilter);

            // SystemIdentityModel.Tokens.TokenValidationParameters is defined in    
            // System.IdentityModel.Token.Jwt.dll.
            System.IdentityModel.Tokens.TokenValidationParameters tokenValidationParameters =
              new TokenValidationParameters()
              {
                  ValidAudience = "00000002-0000-0000-c000-000000000000"
              };

            // WindowsAzureActiveDirectoryBearerAuthenticationOptions is defined in 
            // Microsoft.Owin.Security.ActiveDirectory.dll
            Microsoft.Owin.Security.ActiveDirectory.
            WindowsAzureActiveDirectoryBearerAuthenticationOptions authenticationOptions =
              new WindowsAzureActiveDirectoryBearerAuthenticationOptions()
              {
                  TokenValidationParameters = tokenValidationParameters,
                  Tenant = TENANT_ID // Substitute the appropriate tenant’s 
                  // identifier for this one.  
              };

            applicationBuilder.UseWindowsAzureActiveDirectoryBearerAuthentication(authenticationOptions);
            //~pvs
        }