public void SecurityTokenHandlerCollectionExtensions_Publics()
        {
            SecurityTokenHandlerCollection securityTokenValidators = new SecurityTokenHandlerCollection();
            string defaultSamlToken  = IdentityUtilities.CreateSamlToken();
            string defaultSaml2Token = IdentityUtilities.CreateSaml2Token();
            string defaultJwt        = IdentityUtilities.DefaultAsymmetricJwt;

            ExpectedException expectedException = ExpectedException.ArgumentNullException("Parameter name: securityToken");

            ValidateToken(null, null, securityTokenValidators, expectedException);

            expectedException = ExpectedException.ArgumentNullException("Parameter name: validationParameters");
            ValidateToken(defaultSamlToken, null, securityTokenValidators, expectedException);

            TokenValidationParameters tokenValidationParameters = new TokenValidationParameters();

            expectedException = ExpectedException.SecurityTokenValidationException("IDX10201");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            expectedException       = ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:");
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, expectedException);

            securityTokenValidators.Clear();
            securityTokenValidators.Add(new IMSamlTokenHandler());
            ValidateToken(defaultSamlToken, tokenValidationParameters, securityTokenValidators, ExpectedException.SignatureVerificationFailedException(substringExpected: "ID4037:"));
            ValidateToken(defaultSamlToken, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.SecurityTokenValidationException(substringExpected: "IDX10201:"));
            securityTokenValidators.Add(new IMSaml2TokenHandler());
            securityTokenValidators.Add(new System.IdentityModel.Tokens.JwtSecurityTokenHandler());
            ValidateToken(defaultSaml2Token, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
            ValidateToken(defaultJwt, IdentityUtilities.DefaultAsymmetricTokenValidationParameters, securityTokenValidators, ExpectedException.NoExceptionExpected);
        }
Ejemplo n.º 2
0
        public WsFederationAuthenticationOptions(string authenticationType)
            : base(authenticationType)
        {
            AuthenticationMode = Security.AuthenticationMode.Active;
            Caption            = WsFederationAuthenticationDefaults.Caption;

            _securityTokenHandlers     = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers(authenticationType);
            _tokenValidationParameters = new TokenValidationParameters();
            BackchannelTimeout         = TimeSpan.FromMinutes(1);
        }
        public WsFederationAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, WsFederationAuthenticationOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <WsFederationAuthenticationMiddleware>();

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.AuthenticationType))
            {
                Options.TokenValidationParameters.AuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            if (Options.StateDataFormat == null)
            {
                var dataProtector = app.CreateDataProtector(
                    typeof(WsFederationAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (Options.SecurityTokenHandlers == null)
            {
                Options.SecurityTokenHandlers = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            }

            if (Options.Notifications == null)
            {
                Options.Notifications = new WsFederationAuthenticationNotifications();
            }

            Uri wreply;

            if (!Options.CallbackPath.HasValue && !string.IsNullOrEmpty(Options.Wreply) && Uri.TryCreate(Options.Wreply, UriKind.Absolute, out wreply))
            {
                // Wreply must be a very specific, case sensitive value, so we can't generate it. Instead we generate CallbackPath from it.
                Options.CallbackPath = PathString.FromUriComponent(wreply);
            }

            if (Options.ConfigurationManager == null)
            {
                if (Options.Configuration != null)
                {
                    Options.ConfigurationManager = new StaticConfigurationManager <WsFederationConfiguration>(Options.Configuration);
                }
                else
                {
                    HttpClient httpClient = new HttpClient(ResolveHttpMessageHandler(Options));
                    httpClient.Timeout = Options.BackchannelTimeout;
                    httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
                    Options.ConfigurationManager            = new ConfigurationManager <WsFederationConfiguration>(Options.MetadataAddress, httpClient);
                }
            }
        }
        public void SecurityTokenHandlerCollectionExtensions_Defaults()
        {
            SecurityTokenHandlerCollection securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();

            foreach (var tokenHandler in securityTokenValidators)
            {
                ISecurityTokenValidator tokenValidator = tokenHandler as ISecurityTokenValidator;
                Assert.IsNotNull(tokenValidator, "tokenHandler is not ISecurityTokenHandler, is" + tokenHandler.GetType().ToString());
            }

            securityTokenValidators = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            foreach (var tokenHandler in securityTokenValidators)
            {
                ISecurityTokenValidator tokenValidator = tokenHandler as ISecurityTokenValidator;
                Assert.IsNotNull(tokenValidator, "tokenHandler is not ISecurityTokenHandler, is" + tokenHandler.GetType().ToString());
            }
        }
 public static Func <string, ClaimsPrincipal> CreateOwinWsFederationTokenValidator(this IAppBuilder app, string wtrealm, string metadataAddress)
 {
     // Need to supply an HttpClient instance, otherwise fails with "Digest verification failed for Reference '#_<guid>'. sometimes???
     using (var httpClient = new HttpClient())
     {
         var configurationManager      = new ConfigurationManager <WsFederationConfiguration>(metadataAddress, httpClient);
         var wsFederationConfiguration = configurationManager.GetConfigurationAsync().Result;
         var tokenValidationParameters = new TokenValidationParameters
         {
             NameClaimType     = ClaimTypes.NameIdentifier,
             IssuerSigningKeys = wsFederationConfiguration.SigningKeys,
             ValidIssuer       = wsFederationConfiguration.Issuer,
             ValidAudience     = wtrealm
         };
         Func <string, ClaimsPrincipal> tokenValidator = tokenString =>
         {
             SecurityToken securityToken;
             var           handlers  = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
             var           principal = handlers.ValidateToken(tokenString, tokenValidationParameters, out securityToken);
             return(principal);
         };
         return(tokenValidator);
     }
 }
        public WsFederationAuthenticationMiddleware(RequestDelegate next,
                                                    IOptions <WsFederationAuthenticationOptions> options,
                                                    IOptions <SharedAuthenticationOptions> sharedOptions,
                                                    ILoggerFactory loggerFactory,
                                                    IDataProtectionProvider dataProtectionProvider,
                                                    UrlEncoder encoder)
            : base(next, options, loggerFactory, encoder)
        {
            if (string.IsNullOrEmpty(Options.SignInScheme))
            {
                Options.SignInScheme = sharedOptions.Value.SignInScheme;
            }
            if (string.IsNullOrEmpty(Options.SignInScheme))
            {
                throw new ArgumentException("Options.SignInScheme is required.");
            }

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.AuthenticationType))
            {
                Options.TokenValidationParameters.AuthenticationType = Options.SignInScheme;
            }

            if (Options.StateDataFormat == null)
            {
                var dataProtector = dataProtectionProvider.CreateProtector(
                    typeof(WsFederationAuthenticationMiddleware).FullName,
                    typeof(string).FullName,
                    Options.AuthenticationScheme,
                    "v1"
                    );
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (Options.SecurityTokenHandlers == null)
            {
                Options.SecurityTokenHandlers = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            }

            if (Options.Events == null)
            {
                Options.Events = new WsFederationEvents();
            }

            Uri wreply;

            if (!Options.CallbackPath.HasValue && !string.IsNullOrEmpty(Options.Wreply) &&
                Uri.TryCreate(Options.Wreply, UriKind.Absolute, out wreply))
            {
                Options.CallbackPath = PathString.FromUriComponent(wreply);
            }

            if (Options.ConfigurationManager == null)
            {
                if (Options.Configuration != null)
                {
                    Options.ConfigurationManager =
                        new StaticConfigurationManager <WsFederationConfiguration>(Options.Configuration);
                }
                else
                {
                    var httpClient = new HttpClient(ResolveHttpMessageHandler(Options))
                    {
                        Timeout = Options.BackchannelTimeout,
                        MaxResponseContentBufferSize = 1024 * 1024 * 10
                    };
                    // 10 MB
                    Options.ConfigurationManager =
                        new ConfigurationManager <WsFederationConfiguration>(Options.MetadataAddress, httpClient);
                }
            }
        }
        public OpenIdConnectAuthenticationMiddleware(OwinMiddleware next, IAppBuilder app, OpenIdConnectAuthenticationOptions options)
            : base(next, options)
        {
            _logger = app.CreateLogger <OpenIdConnectAuthenticationMiddleware>();

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.AuthenticationType))
            {
                Options.TokenValidationParameters.AuthenticationType = app.GetDefaultSignInAsAuthenticationType();
            }

            if (Options.StateDataFormat == null)
            {
                var dataProtector = app.CreateDataProtector(
                    typeof(OpenIdConnectAuthenticationMiddleware).FullName,
                    Options.AuthenticationType, "v1");
                Options.StateDataFormat = new PropertiesDataFormat(dataProtector);
            }

            if (Options.SecurityTokenHandlers == null)
            {
                Options.SecurityTokenHandlers = SecurityTokenHandlerCollectionExtensions.GetDefaultHandlers();
            }

            // if the user has not set the AuthorizeCallback, set it from the redirect_uri
            if (!Options.CallbackPath.HasValue)
            {
                Uri redirectUri;
                if (!string.IsNullOrEmpty(Options.RedirectUri) && Uri.TryCreate(Options.RedirectUri, UriKind.Absolute, out redirectUri))
                {
                    // Redirect_Uri must be a very specific, case sensitive value, so we can't generate it. Instead we generate AuthorizeCallback from it.
                    Options.CallbackPath = PathString.FromUriComponent(redirectUri);
                }
            }

            if (Options.Notifications == null)
            {
                Options.Notifications = new OpenIdConnectAuthenticationNotifications();
            }

            if (string.IsNullOrWhiteSpace(Options.TokenValidationParameters.ValidAudience) && !string.IsNullOrWhiteSpace(Options.ClientId))
            {
                Options.TokenValidationParameters.ValidAudience = Options.ClientId;
            }

            if (Options.ConfigurationManager == null)
            {
                if (Options.Configuration != null)
                {
                    Options.ConfigurationManager = new StaticConfigurationManager <OpenIdConnectConfiguration>(Options.Configuration);
                }
                else
                {
                    if (string.IsNullOrWhiteSpace(Options.MetadataAddress) && !string.IsNullOrWhiteSpace(Options.Authority))
                    {
                        Options.MetadataAddress = Options.Authority;
                        if (!Options.MetadataAddress.EndsWith("/", StringComparison.Ordinal))
                        {
                            Options.MetadataAddress += "/";
                        }

                        Options.MetadataAddress += ".well-known/openid-configuration";
                    }

                    HttpClient httpClient = new HttpClient(ResolveHttpMessageHandler(Options));
                    httpClient.Timeout = Options.BackchannelTimeout;
                    httpClient.MaxResponseContentBufferSize = 1024 * 1024 * 10; // 10 MB
                    Options.ConfigurationManager            = new ConfigurationManager <OpenIdConnectConfiguration>(Options.MetadataAddress, httpClient);
                }
            }
        }