public async Task<SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = await CreateSubjectAsync(validationResult);

            // create token for user
            var token = CreateSecurityToken(validationResult, outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm),
                Context = validationResult.SignInRequestMessage.Context,
                ReplyTo = validationResult.ReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var responseMessage = new SignInResponseMessage(
                new Uri(validationResult.ReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext());

            return responseMessage;
        }
        public async Task <SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = await CreateSubjectAsync(validationResult);

            // create token for user
            var token = CreateSecurityToken(validationResult, outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm),
                Context   = validationResult.SignInRequestMessage.Context,
                ReplyTo   = validationResult.ReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var responseMessage = new SignInResponseMessage(
                new Uri(validationResult.ReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext());

            return(responseMessage);
        }
        public SignInResponseMessage Generate(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // create token for user
            var token = CreateSecurityToken(outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context   = request.Context,
                ReplyTo   = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return(responseMessage);
        }
Example #4
0
        /// <summary>
        /// Call the STS to get an appropriate token for a request and build a response.
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns>The <see cref="SignInResponseMessage"/></returns>
        private SignInResponseMessage ProcessSignInRequest(SignInRequestMessage requestMessage)
        {
            // Ensure that the requestMessage has the required wtrealm parameter
            if (String.IsNullOrEmpty(requestMessage.Realm))
            {
                throw new InvalidOperationException("Missing realm");
            }

            SecurityTokenServiceConfiguration stsconfig = new SecurityTokenServiceConfiguration("PassiveFlowSTS");

            // Create our STS backend
            SecurityTokenService sts = new CustomSecurityTokenService(stsconfig);

            // Create the WS-Federation serializer to process the request and create the response
            WSFederationSerializer federationSerializer = new WSFederationSerializer();

            // Create RST from the request
            RequestSecurityToken request = federationSerializer.CreateRequest(requestMessage, new WSTrustSerializationContext());

            // Get RSTR from our STS backend
            RequestSecurityTokenResponse response = sts.Issue((ClaimsPrincipal)Thread.CurrentPrincipal, request);

            // Create Response message from the RSTR
            return(new SignInResponseMessage(new Uri(response.ReplyTo),
                                             federationSerializer.GetResponseAsString(response, new WSTrustSerializationContext())));
        }
        private SignInResponseMessage CreateResponse(SignInValidationResult validationResult, SecurityToken token)
        {
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(validationResult.Client.ClientId),
                Context   = validationResult.SignInRequestMessage.Context,
                ReplyTo   = validationResult.ReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            //var serializer = new WSFederationSerializer(
            //    new WSTrust13RequestSerializer(),
            //    new WSTrust13ResponseSerializer());

            // the asp.net core MW does currently not support WS-Trust 1.3
            var serializer = new WSFederationSerializer(
                new WSTrustFeb2005RequestSerializer(),
                new WSTrustFeb2005ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(validationResult.ReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return(responseMessage);
        }
        public SignInResponseMessage Generate(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // create token for user
            var token = CreateSecurityToken(outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context = request.Context,
                ReplyTo = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();
            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return responseMessage;
        }
        public virtual CookieContainer GetCookieOnPremises([NotNull] string url, [NotNull] RequestSecurityTokenResponse requestSecurityToken)
        {
            Assert.ArgumentNotNull(url, "url");
            Assert.ArgumentNotNull(requestSecurityToken, "requestSecurityToken");

            var serializer       = new WSFederationSerializer();
            var responseAsString = serializer.GetResponseAsString(requestSecurityToken, new WSTrustSerializationContext());

            return(this.GetCookieOnPremises(new Uri(url), responseAsString));
        }
Example #8
0
        protected override async Task <AuthenticationTicket> AuthenticateCoreAsync()
        {
            if (!string.Equals(Request.Method, "POST", StringComparison.OrdinalIgnoreCase))
            {
                return(null);
            }

            var form = await Request.ReadFormAsync();

            var nameValueForm = ConvertToNameValueCollection(form);

            WSFederationMessage message = WSFederationMessage.CreateFromNameValueCollection(
                new Uri(_federationConfiguration.WsFederationConfiguration.Realm),
                nameValueForm);

            var signIn = message as SignInResponseMessage;

            if (signIn == null)
            {
                return(null);
            }

            var extra = Options.StateDataFormat.Unprotect(message.Context);

            if (extra == null)
            {
                return(null);
            }

            // OAuth2 10.12 CSRF
            if (!ValidateCorrelationId(extra, _logger))
            {
                return(new AuthenticationTicket(null, extra));
            }

            XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateTextReader(Encoding.UTF8.GetBytes(signIn.Result), XmlDictionaryReaderQuotas.Max);
            var federationSerializer      = new WSFederationSerializer(xmlReader);
            var serializationContext      = new WSTrustSerializationContext(_federationConfiguration.IdentityConfiguration.SecurityTokenHandlerCollectionManager);
            RequestSecurityTokenResponse securityTokenResponse = federationSerializer.CreateResponse(signIn, serializationContext);
            string xml = securityTokenResponse.RequestedSecurityToken.SecurityTokenXml.OuterXml;

            SecurityToken securityToken = ReadToken(xml);

            var securityTokenReceivedContext = new SecurityTokenReceivedContext(securityToken);
            await Options.Provider.SecurityTokenReceived(securityTokenReceivedContext);

            ClaimsPrincipal principal = AuthenticateToken(securityToken, Request.Uri.AbsoluteUri);

            var securityTokenValidatedContext = new SecurityTokenValidatedContext(principal);
            await Options.Provider.SecurityTokenValidated(securityTokenValidatedContext);

            return(new AuthenticationTicket(
                       securityTokenValidatedContext.ClaimsPrincipal.Identities.FirstOrDefault(),
                       extra));
        }
Example #9
0
        private static string GetTokenXml(HttpRequest request)
        {
            var quotas = new XmlDictionaryReaderQuotas();
            quotas.MaxArrayLength = 0x200000;
            quotas.MaxStringContentLength = 0x200000;

            var wsFederationMessage = WSFederationMessage.CreateFromFormPost(request) as SignInResponseMessage;
            WSFederationSerializer federationSerializer;
            using (var reader = XmlDictionaryReader.CreateTextReader(Encoding.UTF8.GetBytes(wsFederationMessage.Result), quotas))
            {
                federationSerializer = new WSFederationSerializer(reader);
            }

            var serializationContext = new WSTrustSerializationContext(SecurityTokenHandlerCollectionManager.CreateDefaultSecurityTokenHandlerCollectionManager());
            var tokenXml = federationSerializer.CreateResponse(wsFederationMessage, serializationContext).RequestedSecurityToken.SecurityTokenXml.OuterXml;
            return tokenXml;
        }
Example #10
0
        public async Task <SignInResponseMessage> GenerateAsync(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // call custom claims tranformation logic
            var context = new CustomClaimsProviderContext
            {
                WindowsPrincipal = windowsPrincipal,
                OutgoingSubject  = outgoingSubject
            };
            await _options.CustomClaimsProvider.TransformAsync(context);

            // create token for user
            var token = CreateSecurityToken(context.OutgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context   = request.Context,
                ReplyTo   = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return(responseMessage);
        }
        public async Task<SignInResponseMessage> GenerateAsync(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // call custom claims tranformation logic
            var context = new CustomClaimsProviderContext
            {
                WindowsPrincipal = windowsPrincipal,
                OutgoingSubject = outgoingSubject
            };
            await _options.CustomClaimsProvider.TransformAsync(context);

            // create token for user
            var token = CreateSecurityToken(context.OutgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context = request.Context,
                ReplyTo = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();
            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return responseMessage;
        }
Example #12
0
        public void ReadXml(System.Xml.XmlReader reader)
        {
            string securityTokenXml = reader.ReadString();

            RequestSecurityTokenResponse rstr = new WSFederationSerializer().CreateResponse(
                new SignInResponseMessage(new Uri("http://notused"), securityTokenXml),
                new WSTrustSerializationContext());

            _token = new GenericXmlSecurityToken(
                rstr.RequestedSecurityToken.SecurityTokenXml,
                new BinarySecretSecurityToken(
                    rstr.RequestedProofToken.ProtectedKey.GetKeyBytes()),
                rstr.Lifetime.Created.HasValue ? rstr.Lifetime.Created.Value : DateTime.MinValue,
                rstr.Lifetime.Expires.HasValue ? rstr.Lifetime.Expires.Value : DateTime.MaxValue,
                rstr.RequestedAttachedReference,
                rstr.RequestedUnattachedReference,
                null);

            _rawToken = rstr;
        }
        /// <summary>
        /// Processes a WS-Federation sign in request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="principal">The client principal.</param>
        /// <param name="configuration">The token service configuration.</param>
        /// <returns>A SignInResponseMessage</returns>
        public static SignInResponseMessage ProcessSignInRequest(SignInRequestMessage request, IClaimsPrincipal principal, SecurityTokenServiceConfiguration configuration)
        {
            Contract.Requires(request != null);
            Contract.Requires(principal != null);
            Contract.Requires(configuration != null);
            Contract.Ensures(Contract.Result <SignInResponseMessage>() != null);


            // create token service and serializers
            var sts     = configuration.CreateSecurityTokenService();
            var context = new WSTrustSerializationContext(
                sts.SecurityTokenServiceConfiguration.SecurityTokenHandlerCollectionManager,
                sts.SecurityTokenServiceConfiguration.ServiceTokenResolver,
                sts.SecurityTokenServiceConfiguration.IssuerTokenResolver);
            var federationSerializer = new WSFederationSerializer(
                sts.SecurityTokenServiceConfiguration.WSTrust13RequestSerializer,
                sts.SecurityTokenServiceConfiguration.WSTrust13ResponseSerializer);

            // convert ws-fed message to RST and call issue pipeline
            var rst  = federationSerializer.CreateRequest(request, context);
            var rstr = sts.Issue(principal, rst);

            // check ReplyTo
            Uri result = null;

            if (!Uri.TryCreate(rstr.ReplyTo, UriKind.Absolute, out result))
            {
                throw new InvalidOperationException("Invalid ReplyTo");
            }

            var response = new SignInResponseMessage(result, rstr, federationSerializer, context);

            // copy the incoming context data (as required by the WS-Federation spec)
            if (!String.IsNullOrEmpty(request.Context))
            {
                response.Context = request.Context;
            }

            return(response);
        }
Example #14
0
        public void WriteXml(System.Xml.XmlWriter writer)
        {
            string securityTokenXml = new WSFederationSerializer().GetResponseAsString(_rawToken, new WSTrustSerializationContext());

            writer.WriteString(securityTokenXml);
        }
        /// <summary>
        /// Processes a WS-Federation sign in request.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="principal">The client principal.</param>
        /// <param name="configuration">The token service configuration.</param>
        /// <returns>A SignInResponseMessage</returns>
        public static SignInResponseMessage ProcessSignInRequest(SignInRequestMessage request, IClaimsPrincipal principal, SecurityTokenServiceConfiguration configuration)
        {
            Contract.Requires(request != null);
            Contract.Requires(principal != null);
            Contract.Requires(configuration != null);
            Contract.Ensures(Contract.Result<SignInResponseMessage>() != null);
            

            // create token service and serializers
            var sts = configuration.CreateSecurityTokenService();
            var context = new WSTrustSerializationContext(
                sts.SecurityTokenServiceConfiguration.SecurityTokenHandlerCollectionManager,
                sts.SecurityTokenServiceConfiguration.ServiceTokenResolver,
                sts.SecurityTokenServiceConfiguration.IssuerTokenResolver);
            var federationSerializer = new WSFederationSerializer(
                sts.SecurityTokenServiceConfiguration.WSTrust13RequestSerializer,
                sts.SecurityTokenServiceConfiguration.WSTrust13ResponseSerializer);

            // convert ws-fed message to RST and call issue pipeline
            var rst = federationSerializer.CreateRequest(request, context);
            var rstr = sts.Issue(principal, rst);

            // check ReplyTo
            Uri result = null;
            if (!Uri.TryCreate(rstr.ReplyTo, UriKind.Absolute, out result))
            {
                throw new InvalidOperationException("Invalid ReplyTo");
            }

            var response = new SignInResponseMessage(result, rstr, federationSerializer, context);

            // copy the incoming context data (as required by the WS-Federation spec)
            if (!String.IsNullOrEmpty(request.Context))
            {
                response.Context = request.Context;
            }

            return response;
        }