Esempio n. 1
0
        public void BuildAuthnRequest_test_scoping_default_overwritten_2_requesters()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var scopingConfiguration          = new ScopingConfiguration("http://localhost:59611/", "http://localhost:59612/")
            {
                PoxyCount = 10
            };
            var federationContext = federationPartyContextBuilder.BuildContext("local", scopingConfiguration);
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext  = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContext, supportedNameIdentifierFormats);
            var requestConfiguration = federationContext.GetAuthnRequestConfigurationFromContext(Guid.NewGuid().ToString());

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();

            //ACT
            var authnRequest = RequestHelper.BuildRequest(authnRequestContext) as AuthnRequest;

            //ASSERT
            Assert.NotNull(authnRequest);
            Assert.IsNotNull(authnRequest.Scoping);
            Assert.AreEqual("10", authnRequest.Scoping.ProxyCount);
            Assert.AreEqual(2, authnRequest.Scoping.RequesterId.Length);
            Assert.AreEqual("http://localhost:59611/", authnRequest.Scoping.RequesterId[0]);
            Assert.AreEqual("http://localhost:59612/", authnRequest.Scoping.RequesterId[1]);
        }
Esempio n. 2
0
        public void AuthnRequestSerialiser_test()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);

            var xmlSerialiser = new XMLSerialiser();
            var compressor    = new DeflateCompressor();
            var encoder       = new MessageEncoding(compressor);
            var logger        = new LogProviderMock();
            var serialiser    = new RequestSerialiser(xmlSerialiser, encoder, logger) as ISerializer;

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();
            var authnRequest = RequestHelper.BuildRequest(authnRequestContext);

            //ACT
            var serialised   = serialiser.Serialize(authnRequest);
            var deserialised = serialiser.Deserialize <AuthnRequest>(serialised);

            //ASSERT
            Assert.NotNull(serialised);
            Assert.AreEqual(authnRequest.Issuer.Value, deserialised.Issuer.Value);
        }
Esempio n. 3
0
        internal static AuthnRequest BuildAuthnRequest(AuthnRequestContext authnRequestContext)
        {
            if (AuthnRequestHelper.GetBuilders == null)
            {
                throw new InvalidOperationException("GetBuilders factory not set");
            }

            var requestConfig = authnRequestContext.FederationPartyContext.GetRequestConfigurationFromContext();

            var request = new AuthnRequest
            {
                IsPassive    = requestConfig.IsPassive,
                ForceAuthn   = requestConfig.ForceAuthn,
                Destination  = authnRequestContext.Destination.AbsoluteUri,
                Version      = requestConfig.Version,
                IssueInstant = DateTime.UtcNow
            };

            if (authnRequestContext.SupportedNameIdentifierFormats != null)
            {
                authnRequestContext.SupportedNameIdentifierFormats.Aggregate(requestConfig.SupportedNameIdentifierFormats, (t, next) =>
                {
                    t.Add(next);
                    return(t);
                });
            }

            var buiders = AuthnRequestHelper.GetBuilders();

            foreach (var b in buiders)
            {
                b.Build(request, requestConfig);
            }
            return(request);
        }
Esempio n. 4
0
        public void BuildAuthnRequest_test_requested_authn_context_default_overwritten_multiple_contexts()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local", NameIdentifierFormats.Transient);
            var requestedAuthnContextConfiguration = new Kernel.Federation.FederationPartner.RequestedAuthnContextConfiguration(AuthnContextComparisonType.Minimum.ToString());

            requestedAuthnContextConfiguration.RequestedAuthnContexts.Add((new Kernel.Federation.Protocols.AuthnContext(AuthnContextType.AuthnContextClassRef.ToString(), new Uri(AuthnticationContexts.Password))));
            requestedAuthnContextConfiguration.RequestedAuthnContexts.Add((new Kernel.Federation.Protocols.AuthnContext(AuthnContextType.AuthnContextClassRef.ToString(), new Uri(AuthnticationContexts.PasswordProtectedTransport))));
            var federationPartyAuthnRequestConfiguration = new FederationPartyAuthnRequestConfiguration(requestedAuthnContextConfiguration, new DefaultNameId(new Uri(NameIdentifierFormats.Transient)));

            federationContex.FederationPartyAuthnRequestConfiguration = federationPartyAuthnRequestConfiguration;

            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext  = new AuthnRequestContext(requestUri, federationContex, supportedNameIdentifierFormats);
            var requestConfiguration = federationContex.GetRequestConfigurationFromContext();

            AuthnRequestHelper.GetBuilders = AuthnRequestBuildersFactoryMock.GetBuildersFactory();
            //ACT
            var authnRequest = AuthnRequestHelper.BuildAuthnRequest(authnRequestContext);

            //ASSERT
            Assert.NotNull(authnRequest);
            Assert.IsNotNull(authnRequest.RequestedAuthnContext);
            Assert.AreEqual(AuthnContextComparisonType.Minimum, authnRequest.RequestedAuthnContext.Comparison);
            Assert.AreEqual(2, authnRequest.RequestedAuthnContext.Items.Length);
            Assert.AreEqual(2, authnRequest.RequestedAuthnContext.ItemsElementName.Length);
            Assert.AreEqual(AuthnContextType.AuthnContextClassRef, authnRequest.RequestedAuthnContext.ItemsElementName[0]);
            Assert.AreEqual(AuthnticationContexts.Password, authnRequest.RequestedAuthnContext.Items[0]);
            Assert.AreEqual(AuthnContextType.AuthnContextClassRef, authnRequest.RequestedAuthnContext.ItemsElementName[1]);
            Assert.AreEqual(AuthnticationContexts.PasswordProtectedTransport, authnRequest.RequestedAuthnContext.Items[1]);
        }
Esempio n. 5
0
        public async Task AuthnRequestSerialiser_test()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, federationContex, supportedNameIdentifierFormats);

            var xmlSerialiser = new XMLSerialiser();
            var compressor    = new DeflateCompressor();
            var encoder       = new MessageEncoding(compressor);
            var logger        = new LogProviderMock();
            var serialiser    = new AuthnRequestSerialiser(xmlSerialiser, encoder, logger);

            AuthnRequestHelper.GetBuilders = AuthnRequestBuildersFactoryMock.GetBuildersFactory();
            var authnRequest = AuthnRequestHelper.BuildAuthnRequest(authnRequestContext);

            //ACT
            var request = await serialiser.Serialize(authnRequest);

            //ASSERT
            Assert.NotNull(request);
        }
        private static AuthnRequest BuildAuthnRequest(AuthnRequestContext requestContext)
        {
            if (RequestHelper.GetAuthnRequestBuilders == null)
            {
                throw new InvalidOperationException("GetBuilders factory not set");
            }

            var requestConfig = requestContext.FederationPartyContext.GetAuthnRequestConfigurationFromContext(requestContext.RequestId);

            var request = new AuthnRequest
            {
                Destination = requestContext.Destination.AbsoluteUri,
            };

            if (requestContext.SupportedNameIdentifierFormats != null)
            {
                requestContext.SupportedNameIdentifierFormats.Aggregate(requestConfig.SupportedNameIdentifierFormats, (t, next) =>
                {
                    t.Add(next);
                    return(t);
                });
            }

            var buiders = RequestHelper.GetAuthnRequestBuilders();

            foreach (var b in buiders)
            {
                b.Build(request, requestConfig);
            }
            return(request);
        }
Esempio n. 7
0
        public void AuthnRequestType_test()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);
            var types         = ReflectionHelper.GetAllTypes(t => !t.IsAbstract && !t.IsInterface && typeof(RequestAbstract).IsAssignableFrom(t));
            var xmlSerialiser = new XMLSerialiser();
            var compressor    = new DeflateCompressor();
            var encoder       = new MessageEncoding(compressor);
            var logger        = new LogProviderMock();
            var serialiser    = new RequestSerialiser(xmlSerialiser, encoder, logger) as IRequestSerialiser;

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();
            var authnRequest = RequestHelper.BuildRequest(authnRequestContext);
            var typeResolver = new MessageTypeResolver();
            //ACT
            var serialised = serialiser.Serialize(authnRequest);
            var type       = typeResolver.ResolveMessageType(serialised, types);

            //ASSERT

            Assert.AreEqual(typeof(AuthnRequest), type);
        }
Esempio n. 8
0
        public void BuildAuthnRequest_test_nameid_fortmat_no_match_from_many_entries_supported()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local", NameIdentifierFormats.Windows);
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient), new Uri(NameIdentifierFormats.Persistent)
            };
            var authnRequestContext  = new AuthnRequestContext(requestUri, federationContex, supportedNameIdentifierFormats);
            var requestConfiguration = federationContex.GetRequestConfigurationFromContext();

            AuthnRequestHelper.GetBuilders = AuthnRequestBuildersFactoryMock.GetBuildersFactory();
            //ACT
            var authnRequest = AuthnRequestHelper.BuildAuthnRequest(authnRequestContext);
            var audience     = ((AudienceRestriction)authnRequest.Conditions.Items.Single())
                               .Audience
                               .Single();

            //ASSERT
            Assert.NotNull(authnRequest);
            Assert.AreEqual(requestConfiguration.IsPassive, authnRequest.IsPassive);
            Assert.AreEqual(requestConfiguration.ForceAuthn, authnRequest.ForceAuthn);
            Assert.AreEqual("2.0", authnRequest.Version);
            //issuer
            Assert.AreEqual(requestConfiguration.EntityId, authnRequest.Issuer.Value);
            Assert.AreEqual(NameIdentifierFormats.Entity, authnRequest.Issuer.Format);
            //audience
            Assert.AreEqual(requestConfiguration.AudienceRestriction.Count, authnRequest.Conditions.Items.Count);
            Assert.AreEqual(requestConfiguration.AudienceRestriction.Single(), audience);
            //nameIdPolicy
            Assert.IsFalse(authnRequest.NameIdPolicy.AllowCreate);
            Assert.AreEqual(authnRequest.NameIdPolicy.Format, NameIdentifierFormats.Unspecified);
        }
Esempio n. 9
0
        public void BuildAuthnRequest_test_scoping_default_overwritten()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local", NameIdentifierFormats.Transient);

            federationContex.ScopingConfiguration = new Kernel.Federation.FederationPartner.ScopingConfiguration("http://localhost:59611/")
            {
                PoxyCount = 10
            };
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext  = new AuthnRequestContext(requestUri, federationContex, supportedNameIdentifierFormats);
            var requestConfiguration = federationContex.GetRequestConfigurationFromContext();

            AuthnRequestHelper.GetBuilders = AuthnRequestBuildersFactoryMock.GetBuildersFactory();
            //ACT
            var authnRequest = AuthnRequestHelper.BuildAuthnRequest(authnRequestContext);

            //ASSERT
            Assert.NotNull(authnRequest);
            Assert.IsNotNull(authnRequest.Scoping);
            Assert.AreEqual("10", authnRequest.Scoping.ProxyCount);
            Assert.AreEqual(1, authnRequest.Scoping.RequesterId.Length);
            Assert.AreEqual("http://localhost:59611/", authnRequest.Scoping.RequesterId[0]);
        }
        public static async Task <Uri> BuildAuthnRequestRedirectUrl()
        {
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);
            var bindingContext      = await SamlRedirectRequestProviderMock.BuildRequestBindingContext(authnRequestContext);

            return(bindingContext.GetDestinationUrl());
        }
Esempio n. 11
0
        public static async Task <Tuple <string, string> > BuildAuthnRequest()
        {
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);
            var request             = await SamlPostRequestProviderMock.BuildRequest(authnRequestContext);

            return(new Tuple <string, string>(request, authnRequestContext.RequestId));
        }
Esempio n. 12
0
        public Uri BuildRedirectUri(AuthnRequestContext authnRequestContext)
        {
            var configuration = authnRequestContext.Configuration;
            var authnRequest  = new AuthnRequest
            {
                Id           = "Imperial.flowz.co.uk",
                IsPassive    = false,
                Destination  = authnRequestContext.Destination.AbsoluteUri,
                Version      = "2.0",
                IssueInstant = DateTime.UtcNow
            };

            authnRequest.Issuer = new NameId {
                Value = "Imperial.flowz.co.uk"
            };
            var audienceRestrictions = new List <ConditionAbstract>();
            var audienceRestriction  = new AudienceRestriction {
                Audience = new List <string>()
                {
                    "Imperial.flowz.co.uk"
                }
            };

            audienceRestrictions.Add(audienceRestriction);

            authnRequest.Conditions = new Conditions {
                Items = audienceRestrictions
            };

            var serialiser = new XMLSerialiser();

            serialiser.XmlNamespaces.Add("samlp", Saml20Constants.Protocol);
            serialiser.XmlNamespaces.Add("saml", Saml20Constants.Assertion);
            var sb = new StringBuilder();

            using (var ms = new MemoryStream())
            {
                serialiser.Serialize(ms, new[] { authnRequest });
                ms.Position = 0;
                var streamReader = new StreamReader(ms);
                var xmlString    = streamReader.ReadToEnd();
                ms.Position = 0;
                var encoded        = this.DeflateEncode(xmlString);
                var encodedEscaped = Uri.EscapeDataString(this.UpperCaseUrlEncode(encoded));
                sb.Append("SAMLRequest=");
                sb.Append(encodedEscaped);
                this.SignRequest(sb);
                var result = authnRequest.Destination + "?" + sb.ToString();
                return(new Uri(result));
            }
        }
Esempio n. 13
0
        public void BuildAuthnRequest_test_requested_authn_context_default()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local", NameIdentifierFormats.Transient);
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, federationContex, supportedNameIdentifierFormats);

            //ACT

            //ASSERT
            Assert.Throws <ArgumentNullException>(() => federationContex.GetRequestConfigurationFromContext());
        }
        public void BuildAuthnRequest_test_requested_authn_context_default()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local", (RequestedAuthnContextConfiguration)null);
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);

            //ACT
            var config = federationContex.GetAuthnRequestConfigurationFromContext(Guid.NewGuid().ToString());

            //ASSERT
            Assert.IsNull(config.RequestedAuthnContextConfiguration);
        }
        public async Task BuildRelayStateTest()
        {
            //ARRANGE
            var logger  = new LogProviderMock();
            var handler = new RelayStateAppender(logger);
            //ACT
            var federationPartyContextBuilderMock = new FederationPartyContextBuilderMock();
            var configuration       = federationPartyContextBuilderMock.BuildContext("local");
            var authnRequestContext = new AuthnRequestContext(new Uri("http://localhost"), new Uri("http://localhost"), configuration, new [] { new Uri("http://localhost") });
            await handler.BuildRelayState(authnRequestContext);

            //ASSERT
            Assert.AreEqual(3, authnRequestContext.RelyingState.Count);
            Assert.AreEqual("local", authnRequestContext.RelyingState["federationPartyId"]);
            Assert.AreEqual(authnRequestContext.RequestId, authnRequestContext.RelyingState.ElementAt(1).Value);
            Assert.AreEqual("http://localhost/", authnRequestContext.RelyingState.ElementAt(2).Value.ToString());
        }
Esempio n. 16
0
        public async Task <Uri> BuildRedirectUri(AuthnRequestContext authnRequestContext)
        {
            var bindingHandler = new HttpRedirectBindingHandler();
            var contex         = new HttpRedirectContext(authnRequestContext);
            await bindingHandler.BuildRequest(contex);

            var url = contex.GetDestinationUrl();

            return(url);
            //var authnRequest = AuthnRequestHelper.BuildAuthnRequest(authnRequestContext, this._federationPartyContextBuilder);

            //var sb = new StringBuilder();
            ////var query = await AuthnRequestHelper.SerialiseAndSign(authnRequest, authnRequestContext, this._serialiser, this._federationPartyContextBuilder, this._certificateManager, this._compression);
            ////sb.AppendFormat("{0}?{1}", authnRequest.Destination, query);
            //sb.AppendFormat("{0}?{1}", authnRequestContext.Destination, contex.ClauseBuilder.ToString());

            //return new Uri(sb.ToString());
        }
Esempio n. 17
0
        public void BuildAuthnRequest_test_default_overwritten_intex_endpoint()
        {
            //ARRANGE
            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local", 1);
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();
            //ACT
            var config       = federationContex.GetAuthnRequestConfigurationFromContext(Guid.NewGuid().ToString());
            var authnRequest = RequestHelper.BuildRequest(authnRequestContext) as AuthnRequest;

            //ASSERT
            Assert.IsNotNull(config.RequestedAuthnContextConfiguration);
            Assert.AreEqual(1, authnRequest.AssertionConsumerServiceIndex);
        }
Esempio n. 18
0
 public HttpRedirectContext(AuthnRequestContext authnRequestContext) : base(authnRequestContext.RelyingState, authnRequestContext.Destination)
 {
     this.AuthnRequestContext = authnRequestContext;
 }
Esempio n. 19
0
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (this.Response.StatusCode != 401)
            {
                return;
            }

            var challenge = this.Helper.LookupChallenge(this.Options.AuthenticationType, this.Options.AuthenticationMode);

            if (challenge == null)
            {
                return;
            }

            if (!this.Options.SSOPath.HasValue || base.Request.Path != this.Options.SSOPath)
            {
                return;
            }

            var federationPartyId = FederationPartyIdentifierHelper.GetFederationPartyIdFromRequestOrDefault(Request.Context);

            if (this._configuration == null)
            {
                var configurationManager = this._resolver.Resolve <IConfigurationManager <MetadataBase> >();
                this._configuration = await configurationManager.GetConfigurationAsync(federationPartyId, new System.Threading.CancellationToken());
            }

            Uri signInUrl    = null;
            var metadataType = this._configuration.GetType();
            var handlerType  = typeof(IMetadataHandler <>).MakeGenericType(metadataType);
            var handler      = this._resolver.Resolve(handlerType);

            //ToDo: sort this one in phase3 when implementing owin middleware.
            //no need to have two methods in the handler. use GetDelegateForIdpDescriptors
            var locationDel = IdpMetadataHandlerFactory.GetDelegateForIdpLocation(metadataType);

            signInUrl = locationDel(handler, this._configuration, new Uri(Bindings.Http_Redirect));

            //the lines below are likely to do all what we need.
            var idpDel = IdpMetadataHandlerFactory.GetDelegateForIdpDescriptors(this._configuration.GetType(), typeof(IdentityProviderSingleSignOnDescriptor));
            var idp    = idpDel(handler, this._configuration).Cast <IdentityProviderSingleSignOnDescriptor>().First();

            var federationPartyContextBuilder = this._resolver.Resolve <IFederationPartyContextBuilder>();
            var federationContext             = federationPartyContextBuilder.BuildContext(federationPartyId);

            var requestContext  = new AuthnRequestContext(signInUrl, federationContext, idp.NameIdentifierFormats);
            var protocolContext = new SamlProtocolContext
            {
                RequestContext = new HttpRedirectRequestContext
                {
                    BindingContext      = new HttpRedirectContext(requestContext),
                    RequestHanlerAction = redirectUri =>
                    {
                        this.Response.Redirect(redirectUri.AbsoluteUri);
                        return(Task.CompletedTask);
                    }
                }
            };
            var protocolFactory = this._resolver.Resolve <Func <string, IProtocolHandler> >();
            var protocolHanlder = protocolFactory(Bindings.Http_Redirect);
            await protocolHanlder.HandleRequest(protocolContext);
        }
        public async Task Redirect_end_to_end_test()
        {
            //ARRANGE
            var    isValid  = false;
            string url      = String.Empty;
            var    builders = new List <IRedirectClauseBuilder>();

            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var spDescriptor     = federationContex.MetadataContext.EntityDesriptorConfiguration.SPSSODescriptors.First();
            var certContext      = spDescriptor.KeyDescriptors.Where(x => x.Use == KeyUsage.Signing && x.IsDefault)
                                   .Select(x => x.CertificateContext)
                                   .First();
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);

            authnRequestContext.RelyingState.Add("relayState", "Test state");
            var xmlSerialiser = new XMLSerialiser();
            var compressor    = new DeflateCompressor();
            var encoder       = new MessageEncoding(compressor);
            var logger        = new LogProviderMock();
            var serialiser    = new RequestSerialiser(xmlSerialiser, encoder, logger);

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();
            var authnBuilder = new SamlRequestBuilder(serialiser);

            builders.Add(authnBuilder);

            //request compression builder
            var encodingBuilder = new RequestEncoderBuilder(encoder);

            builders.Add(encodingBuilder);

            //relay state builder
            var jsonSerialiser       = new NSJsonSerializer(new DefaultSettingsProvider());
            var relayStateSerialiser = new RelaystateSerialiser(jsonSerialiser, encoder, logger) as IRelayStateSerialiser;
            var relayStateBuilder    = new RelayStateBuilder(relayStateSerialiser);

            builders.Add(relayStateBuilder);

            //signature builder
            var certificateManager = new CertificateManager(logger);
            var signatureBuilder   = new SignatureBuilder(certificateManager, logger);

            builders.Add(signatureBuilder);

            //context
            var outboundContext = new HttpRedirectRequestContext
            {
                BindingContext   = new RequestBindingContext(authnRequestContext),
                DespatchDelegate = redirectUri =>
                {
                    url = redirectUri.GetLeftPart(UriPartial.Path);
                    var query = redirectUri.Query.TrimStart('?');
                    var cert  = certificateManager.GetCertificateFromContext(certContext);
                    isValid = this.VerifySignature(query, cert, certificateManager);
                    return(Task.CompletedTask);
                }
            };
            //dispatcher
            var dispatcher = new RedirectRequestDispatcher(() => builders);

            //ACT
            await dispatcher.SendAsync(outboundContext);

            //ASSERT
            Assert.AreEqual(url, requestUri.AbsoluteUri);
            Assert.IsTrue(isValid);
        }
Esempio n. 21
0
        protected override async Task ApplyResponseChallengeAsync()
        {
            if (this.Response.StatusCode != 401)
            {
                return;
            }

            var challenge = this.Helper.LookupChallenge(this.Options.AuthenticationType, this.Options.AuthenticationMode);

            if (challenge == null)
            {
                return;
            }

            if (!this.Options.SSOPath.HasValue || base.Request.Path != this.Options.SSOPath)
            {
                return;
            }

            //ToDo: shoudn't need those. The tests don't so probably reletated to IIS express etc
            ServicePointManager.Expect100Continue = true;
            ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
            var relyingPartyId = base.Options.Wtrealm;

            if (this._configuration == null)
            {
                this._configuration = await this.Options.ConfigurationManager.GetConfigurationAsync(relyingPartyId, new System.Threading.CancellationToken());
            }

            Uri signInUrl = null;

            var entitiesDescriptors = this._configuration as EntitiesDescriptor;

            if (entitiesDescriptors != null)
            {
                var idDescpritor = entitiesDescriptors.ChildEntities.SelectMany(x => x.RoleDescriptors)
                                   .First(x => x.GetType() == typeof(IdentityProviderSingleSignOnDescriptor)) as IdentityProviderSingleSignOnDescriptor;
                signInUrl = idDescpritor.SingleSignOnServices.FirstOrDefault(x => x.Binding == new Uri("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"))
                            .Location;
            }

            var entitityDescriptor = this._configuration as EntityDescriptor;

            if (entitityDescriptor != null)
            {
                var idDescpritor = entitityDescriptor.RoleDescriptors.Select(x => x)
                                   .First(x => x.GetType() == typeof(IdentityProviderSingleSignOnDescriptor)) as IdentityProviderSingleSignOnDescriptor;
                signInUrl = idDescpritor.SingleSignOnServices.FirstOrDefault(x => x.Binding == new Uri("urn:oasis:names:tc:SAML:2.0:bindings:HTTP-Redirect"))
                            .Location;
            }

            var requestContext     = new AuthnRequestContext(null, signInUrl);
            var redirectUriBuilder = this._resolver.Resolve <AuthnRequestBuilder>();
            var redirectUri        = redirectUriBuilder.BuildRedirectUri(requestContext);

            //string baseUri = this.Request.Scheme + Uri.SchemeDelimiter + (object)this.Request.Host + (object)this.Request.PathBase;
            //string currentUri = baseUri + (object)this.Request.Path + (object)this.Request.QueryString;
            //AuthenticationProperties properties = challenge.Properties;
            //if (string.IsNullOrEmpty(properties.RedirectUri))
            //    properties.RedirectUri = currentUri;
            //WsFederationMessage federationMessage = new WsFederationMessage();
            //federationMessage.IssuerAddress = this._configuration.TokenEndpoint ?? string.Empty;
            //federationMessage.Wtrealm = this.Options.Wtrealm;
            //federationMessage.Wctx = "WsFedOwinState=" + Uri.EscapeDataString(this.Options.StateDataFormat.Protect(properties));
            //federationMessage.Wa = "wsignin1.0";
            //WsFederationMessage wsFederationMessage = federationMessage;
            //if (!string.IsNullOrWhiteSpace(this.Options.Wreply))
            //    wsFederationMessage.Wreply = this.Options.Wreply;
            //RedirectToIdentityProviderNotification<WsFederationMessage, WsFederationAuthenticationOptions> notification = new RedirectToIdentityProviderNotification<WsFederationMessage, WsFederationAuthenticationOptions>(this.Context, this.Options)
            //{
            //    ProtocolMessage = wsFederationMessage
            //};
            //await this.Options.Notifications.RedirectToIdentityProvider(notification);
            //if (notification.HandledResponse)
            //    return;
            //string signInUrl = notification.ProtocolMessage.CreateSignInUrl();
            //if (!Uri.IsWellFormedUriString(signInUrl, UriKind.Absolute))
            //    this._logger.WriteWarning("The sign-in redirect URI is malformed: " + signInUrl);
            this.Response.Redirect(redirectUri.AbsoluteUri);
        }
Esempio n. 22
0
        public async Task DecodeTest()
        {
            string url      = String.Empty;
            var    builders = new List <IRedirectClauseBuilder>();

            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var spDescriptor     = federationContex.MetadataContext.EntityDesriptorConfiguration.SPSSODescriptors.First();
            var certContext      = spDescriptor.KeyDescriptors.Where(x => x.Use == KeyUsage.Signing && x.IsDefault)
                                   .Select(x => x.CertificateContext)
                                   .First();
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);

            authnRequestContext.RelyingState.Add("relayState", "Test state");
            var xmlSerialiser = new XMLSerialiser();
            var compressor    = new DeflateCompressor();
            var encoder       = new MessageEncoding(compressor);
            var logger        = new LogProviderMock();
            var serialiser    = new RequestSerialiser(xmlSerialiser, encoder, logger);

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();
            var authnBuilder = new SamlRequestBuilder(serialiser);

            builders.Add(authnBuilder);

            //request compression builder
            var encodingBuilder = new RequestEncoderBuilder(encoder);

            builders.Add(encodingBuilder);

            //relay state builder
            var jsonSerialiser       = new NSJsonSerializer(new DefaultSettingsProvider());
            var relayStateSerialiser = new RelaystateSerialiser(jsonSerialiser, encoder, logger) as IRelayStateSerialiser;
            var relayStateBuilder    = new RelayStateBuilder(relayStateSerialiser);

            builders.Add(relayStateBuilder);

            //signature builder
            var certificateManager = new CertificateManager(logger);
            var signatureBuilder   = new SignatureBuilder(certificateManager, logger);

            builders.Add(signatureBuilder);
            var bindingContext = new RequestBindingContext(authnRequestContext);

            foreach (var b in builders)
            {
                await b.Build(bindingContext);
            }
            var decoder = new RedirectBindingDecoder(logger, encoder);
            //ACT
            var message = await decoder.Decode(bindingContext.GetDestinationUrl());

            var stateFromResult    = message.Elements[HttpRedirectBindingConstants.RelayState];
            var requestFromContext = bindingContext.RequestParts[HttpRedirectBindingConstants.SamlRequest];
            var decoded            = await encoder.DecodeMessage(requestFromContext);

            //ASSERT
            Assert.IsNotNull(stateFromResult);
            Assert.AreEqual(bindingContext.RequestParts[HttpRedirectBindingConstants.RelayState], message.Elements[HttpRedirectBindingConstants.RelayState]);
            Assert.AreEqual(decoded, message.Elements[HttpRedirectBindingConstants.SamlRequest]);
        }
Esempio n. 23
0
        public async Task Post_end_to_end_test()
        {
            //ARRANGE
            var    isValid = false;
            string url     = String.Empty;
            IDictionary <string, object> relayState = null;
            var builders = new List <IPostClauseBuilder>();

            var requestUri = new Uri("http://localhost:59611/");
            var federationPartyContextBuilder = new FederationPartyContextBuilderMock();
            var federationContex = federationPartyContextBuilder.BuildContext("local");
            var spDescriptor     = federationContex.MetadataContext.EntityDesriptorConfiguration.SPSSODescriptors.First();
            var certContext      = spDescriptor.KeyDescriptors.Where(x => x.Use == KeyUsage.Signing && x.IsDefault)
                                   .Select(x => x.CertificateContext)
                                   .First();
            var supportedNameIdentifierFormats = new List <Uri> {
                new Uri(NameIdentifierFormats.Transient)
            };
            var authnRequestContext = new AuthnRequestContext(requestUri, new Uri("http://localhost"), federationContex, supportedNameIdentifierFormats);

            authnRequestContext.RelyingState.Add("relayState", "Test state");
            var xmlSerialiser = new XMLSerialiser();
            var compressor    = new DeflateCompressor();
            var encoder       = new MessageEncoding(compressor);
            var logger        = new LogProviderMock();
            var serialiser    = new RequestSerialiser(xmlSerialiser, encoder, logger);

            RequestHelper.GetAuthnRequestBuilders = AuthnRequestBuildersFactoryMock.GetAuthnRequestBuildersFactory();
            var authnBuilder = new SamlRequestBuilder(serialiser);

            builders.Add(authnBuilder);

            //relay state builder
            var jsonSerialiser       = new NSJsonSerializer(new DefaultSettingsProvider());
            var relayStateSerialiser = new RelaystateSerialiser(jsonSerialiser, encoder, logger) as IRelayStateSerialiser;
            var relayStateBuilder    = new RelayStateBuilder(relayStateSerialiser);

            builders.Add(relayStateBuilder);

            //signature builder
            var certificateManager = new CertificateManager(logger);
            var xmlSinatureManager = new XmlSignatureManager();
            var signatureBuilder   = new SignatureBuilder(certificateManager, logger, xmlSinatureManager);

            builders.Add(signatureBuilder);

            //context
            var outboundContext = new HttpPostRequestContext(new SAMLForm())
            {
                BindingContext   = new RequestPostBindingContext(authnRequestContext),
                DespatchDelegate = form =>
                {
                    url = form.ActionURL;
                    var request = ((SAMLForm)form).HiddenControls[HttpRedirectBindingConstants.SamlRequest];
                    var state   = ((SAMLForm)form).HiddenControls[HttpRedirectBindingConstants.RelayState];
                    var task    = relayStateSerialiser.Deserialize(state);
                    task.Wait();
                    relayState = task.Result as IDictionary <string, object>;
                    var cert = certificateManager.GetCertificateFromContext(certContext);
                    isValid = this.VerifySignature(request, cert);
                    return(Task.CompletedTask);
                }
            };

            //dispatcher
            var dispatcher = new PostRequestDispatcher(() => builders, logger);

            //ACT
            await dispatcher.SendAsync(outboundContext);

            //ASSERT
            Assert.AreEqual(url, requestUri.AbsoluteUri);
            Assert.IsTrue(Enumerable.SequenceEqual(relayState, authnRequestContext.RelyingState));
            Assert.IsTrue(isValid);
        }