public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out TokenResponse response)
        {
            SecurityToken token = null;
            response = new TokenResponse { TokenType = tokenType };

            var result = TryIssueToken(appliesTo, principal, tokenType, out token);
            if (result == false)
            {
                return false;
            }

            var ts = token.ValidTo.Subtract(DateTime.UtcNow);
            response.ExpiresIn = (int)ts.TotalSeconds;

            if (tokenType == TokenTypes.JsonWebToken || tokenType == TokenTypes.SimpleWebToken)
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers[tokenType];
                response.AccessToken = handler.WriteToken(token);
            }
            else
            {
                var handler = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.SecurityTokenHandlers;
                var sb = new StringBuilder(128);
                handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);

                response.AccessToken = sb.ToString();
            }

            return result;
        }
Esempio n. 2
0
        public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType,
            out SecurityToken token)
        {
            token = null;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = appliesTo,
                KeyType = KeyTypes.Bearer,
                TokenType = tokenType
            };

            try
            {
                var rstr = _sts.Issue(principal, rst);
                token = rstr.RequestedSecurityToken.SecurityToken;
                return true;
            }
            catch (Exception e)
            {
                Tracing.Error("Failed to issue token. An exception occurred. " + e);
                return false;
            }
        }
        private void ValidateAppliesTo(EndpointReference appliesTo)
        {
            if (appliesTo == null)
            {
                throw new InvalidRequestException("The AppliesTo is null.");
            }

            // should check applies to, but for convienence, not
        }
        public HttpResponseMessage Post(TokenRequest tokenRequest)
        {
            Tracing.Information("OAuth2 endpoint called.");

            Client client = null;
            if (!ValidateClient(out client))
            {
                Tracing.Error("Invalid client: " + ClaimsPrincipal.Current.Identity.Name);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidClient);
            }

            Tracing.Information("Client: " + client.Name);

            var tokenType = ConfigurationRepository.Global.DefaultHttpTokenType;

            // validate scope
            EndpointReference appliesTo;
            try
            {
                appliesTo = new EndpointReference(tokenRequest.Scope);
                Tracing.Information("OAuth2 endpoint called for scope: " + tokenRequest.Scope);
            }
            catch
            {
                Tracing.Error("Malformed scope: " + tokenRequest.Scope);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidScope);
            }

            // check grant type
            if (string.Equals(tokenRequest.Grant_Type, OAuth2Constants.GrantTypes.Password, System.StringComparison.Ordinal))
            {
                if (ConfigurationRepository.OAuth2.EnableResourceOwnerFlow)
                {
                    if (client.AllowResourceOwnerFlow)
                    {
                        return ProcessResourceOwnerCredentialRequest(tokenRequest.UserName, tokenRequest.Password, appliesTo, tokenType, client);
                    }
                    else
                    {
                        Tracing.Error("Client is not allowed to use the resource owner password flow:" + client.Name);
                    }
                }
            }

            Tracing.Error("invalid grant type: " + tokenRequest.Grant_Type);
            return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
        }
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            Tracing.Information("Simple HTTP endpoint called.");

            var query = request.GetQueryNameValuePairs();
            var auth = new AuthenticationHelper();

            var realm = query.FirstOrDefault(p => p.Key.Equals("realm", System.StringComparison.OrdinalIgnoreCase)).Value;
            var tokenType = query.FirstOrDefault(p => p.Key.Equals("tokenType", System.StringComparison.OrdinalIgnoreCase)).Value;

            if (string.IsNullOrWhiteSpace(realm))
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "realm parameter is missing.");
            }

            EndpointReference appliesTo;
            try
            {
                appliesTo = new EndpointReference(realm);
                Tracing.Information("Simple HTTP endpoint called for realm: " + realm);
            }
            catch
            {
                Tracing.Error("Malformed realm: " + realm);
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "malformed realm name.");
            }

            if (string.IsNullOrWhiteSpace(tokenType))
            {
                tokenType = ConfigurationRepository.Global.DefaultHttpTokenType;
            }

            Tracing.Verbose("Token type: " + tokenType);

            TokenResponse tokenResponse;
            var sts = new STS();
            if (sts.TryIssueToken(appliesTo, ClaimsPrincipal.Current, tokenType, out tokenResponse))
            {
                var resp = request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return request.CreateErrorResponse(HttpStatusCode.BadRequest, "invalid request.");
            }
        }
        public string GetFederationMetadata(Uri endpoint)
        {
            // hostname
            var passiveEndpoint = new EndpointReference(endpoint.AbsoluteUri);
            var activeEndpoint = new EndpointReference(endpoint.AbsoluteUri);

            // metadata document 
            var entity = new EntityDescriptor(new EntityId(TwitterClaims.IssuerName));
            var sts = new SecurityTokenServiceDescriptor();
            entity.RoleDescriptors.Add(sts);

            // signing key
            var signingKey = new KeyDescriptor(SigningCredentials.SigningKeyIdentifier) { Use = KeyType.Signing };
            sts.Keys.Add(signingKey);

            // claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name, "Name", "User name"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.NameIdentifier, "Name Identifier", "User name identifier"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(TwitterClaims.TwitterToken, "Token", "Service token"));
            sts.ClaimTypesOffered.Add(new DisplayClaim(TwitterClaims.TwitterTokenSecret, "Token Secret", "Service token secret"));

            // passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // supported protocols

            //Inaccessable due to protection level
            //sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));
            sts.ProtocolsSupported.Add(new Uri("http://docs.oasis-open.org/wsfed/federation/200706"));

            // add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(activeEndpoint);

            // metadata signing
            entity.SigningCredentials = SigningCredentials;

            // serialize 
            var serializer = new MetadataSerializer();

            using (var memoryStream = new MemoryStream())
            {
                serializer.WriteMetadata(memoryStream, entity);
                return Encoding.UTF8.GetString(memoryStream.ToArray());
            }
        }
        public byte[] GetFederationMetadata(Uri passiveSignInUrl, Uri identifier, X509Certificate2 signingCertificate)
        {
            var credentials = new X509SigningCredentials(signingCertificate);

            // Figure out the hostname exposed from Azure and what port the service is listening on
            var realm = new EndpointAddress(identifier);
            var passiveEndpoint = new EndpointReference(passiveSignInUrl.AbsoluteUri);

            // Create metadata document for relying party
            EntityDescriptor entity = new EntityDescriptor(new EntityId(realm.Uri.AbsoluteUri));
            SecurityTokenServiceDescriptor sts = new SecurityTokenServiceDescriptor();
            entity.RoleDescriptors.Add(sts);

            // Add STS's signing key
            KeyDescriptor signingKey = new KeyDescriptor(credentials.SigningKeyIdentifier);
            signingKey.Use = KeyType.Signing;
            sts.Keys.Add(signingKey);

            // Add offered claim types
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationMethod));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.AuthenticationInstant));
            sts.ClaimTypesOffered.Add(new DisplayClaim(ClaimTypes.Name));

            // Add passive federation endpoint
            sts.PassiveRequestorEndpoints.Add(passiveEndpoint);

            // Add supported protocols
            sts.ProtocolsSupported.Add(new Uri(WSFederationConstants.Namespace));

            // Add passive STS endpoint
            sts.SecurityTokenServiceEndpoints.Add(passiveEndpoint);

            // Set credentials with which to sign the metadata
            entity.SigningCredentials = credentials;

            // Serialize the metadata and convert it to an XElement
            MetadataSerializer serializer = new MetadataSerializer();
            MemoryStream stream = new MemoryStream();
            serializer.WriteMetadata(stream, entity);
            stream.Flush();

            return stream.ToArray();
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(TokenRequest request, string tokenType, Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);
            var appliesTo = new EndpointReference(request.Scope);

            if (string.IsNullOrWhiteSpace(request.UserName) || string.IsNullOrWhiteSpace(request.Password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            if (UserRepository.ValidateUser(request.UserName, request.Password))
            {
                return CreateTokenResponse(request.UserName, client, appliesTo, tokenType, includeRefreshToken: client.AllowRefreshToken);
            }
            else
            {
                Tracing.Error("Resource owner credential validation failed: " + request.UserName);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Reads an <see cref="EndpointReference"/> from xml dictionary reader. The addressing version is defaulted to
        /// <see cref="WSAddressing10Constants.Elements.Address"/>.
        /// </summary>
        /// <param name="reader">The xml dictionary reader.</param>
        /// <returns>An <see cref="EndpointReference"/> instance.</returns>
        public static EndpointReference ReadFrom(XmlDictionaryReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            reader.ReadFullStartElement();
            reader.MoveToContent();

            if (reader.IsNamespaceUri(WSAddressing10Constants.NamespaceUri) || reader.IsNamespaceUri(WSAddressing200408Constants.NamespaceUri))
            {
                if (reader.IsStartElement(WSAddressing10Constants.Elements.Address, WSAddressing10Constants.NamespaceUri) ||
                    reader.IsStartElement(WSAddressing10Constants.Elements.Address, WSAddressing200408Constants.NamespaceUri))
                {
                    EndpointReference er = new EndpointReference(reader.ReadElementContentAsString());
                    while (reader.IsStartElement())
                    {
                        bool emptyElement = reader.IsEmptyElement;

                        XmlReader   subtreeReader = reader.ReadSubtree();
                        XmlDocument doc           = new XmlDocument();
                        doc.PreserveWhitespace = true;
                        doc.Load(subtreeReader);
                        er._details.Add(doc.DocumentElement);
                        if (!emptyElement)
                        {
                            reader.ReadEndElement();
                        }
                    }

                    reader.ReadEndElement();
                    return(er);
                }
            }

            return(null);
        }
        public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType, out SecurityToken token)
        {
            token = null;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = appliesTo,
                KeyType = KeyTypes.Bearer,
                TokenType = tokenType
            };

            try
            {
                var rstr = _sts.Issue(principal, rst);
                token = rstr.RequestedSecurityToken.SecurityToken;
                return true;
            }
            catch
            {
                return false;
            }
        }
        private HttpResponseMessage ProcessResourceOwnerCredentialRequest(string userName, string password, EndpointReference appliesTo, string tokenType, Client client)
        {
            Tracing.Information("Starting resource owner password credential flow for client: " + client.Name);

            if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password))
            {
                Tracing.Error("Invalid resource owner credentials for: " + appliesTo.Uri.AbsoluteUri);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            var auth = new AuthenticationHelper();
            ClaimsPrincipal principal;
            if (UserRepository.ValidateUser(userName, password))
            {
                principal = auth.CreatePrincipal(userName, "OAuth2",
                    new Claim[]
                        {
                            new Claim(Constants.Claims.Client, client.Name),
                            new Claim(Constants.Claims.Scope, appliesTo.Uri.AbsoluteUri)
                        });

                if (!ClaimsAuthorization.CheckAccess(principal, Constants.Actions.Issue, Constants.Resources.OAuth2))
                {
                    Tracing.Error("OAuth2 endpoint authorization failed for user: "******"Resource owner credential validation failed: " + userName);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            var sts = new STS();
            TokenResponse tokenResponse;
            if (sts.TryIssueToken(appliesTo, principal, tokenType, out tokenResponse))
            {
                var resp = Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest);
            }
        }
        private HttpResponseMessage ValidateRequest(TokenRequest request, out Client client)
        {
            client = null;

            // grant type is required
            if (string.IsNullOrWhiteSpace(request.Grant_Type))
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
            }

            // check supported grant types
            if (!request.Grant_Type.Equals(OAuth2Constants.GrantTypes.AuthorizationCode) &&
                !request.Grant_Type.Equals(OAuth2Constants.GrantTypes.Password) &&
                !request.Grant_Type.Equals(OAuth2Constants.GrantTypes.RefreshToken))
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
            }

            // resource owner password flow requires a well-formed scope
            EndpointReference appliesTo = null;
            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.Password))
            {
                try
                {
                    appliesTo = new EndpointReference(request.Scope);
                    Tracing.Information("OAuth2 endpoint called for scope: " + request.Scope);
                }
                catch
                {
                    Tracing.Error("Malformed scope: " + request.Scope);
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidScope);
                }
            }

            if (!ValidateClient(out client))
            {
                Tracing.Error("Invalid client: " + ClaimsPrincipal.Current.Identity.Name);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidClient);
            }

            // validate grant types against global and client configuration
            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.AuthorizationCode))
            {
                if (!ConfigurationRepository.OAuth2.EnableCodeFlow ||
                    !client.AllowCodeFlow)
                {
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
                }
            }

            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.Password))
            {
                if (!ConfigurationRepository.OAuth2.EnableResourceOwnerFlow ||
                    !client.AllowResourceOwnerFlow)
                {
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
                }
            }

            if (request.Grant_Type.Equals(OAuth2Constants.GrantTypes.RefreshToken))
            {
                if (!client.AllowRefreshToken)
                {
                    return OAuthErrorResponseMessage(OAuth2Constants.Errors.UnsupportedGrantType);
                }
            }

            return null;
        }
        void ValidateAppliesTo(EndpointReference appliesTo)
        {
            if (appliesTo == null)
            {
                throw new InvalidRequestException("The appliesTo is null.");
            }

            if (!appliesTo.Uri.Equals(new Uri(_addressExpected)))
            {
                throw new InvalidRequestException(String.Format("The relying party address is not valid. Expected value is {0}, the actual value is {1}.", _addressExpected, appliesTo.Uri.AbsoluteUri));
            }
        }
Esempio n. 14
0
 private void ValidateAppliesTo(EndpointReference appliesTo)
 {
     if (appliesTo == null)
     {
         throw new InvalidRequestException("The AppliesTo is null.");
     }
 }
        private HttpResponseMessage CreateTokenResponse(string userName, Client client, EndpointReference scope, string tokenType, bool includeRefreshToken)
        {
            var auth = new AuthenticationHelper();

            var principal = auth.CreatePrincipal(userName, "OAuth2",
                    new Claim[]
                        {
                            new Claim(Constants.Claims.Client, client.Name),
                            new Claim(Constants.Claims.Scope, scope.Uri.AbsoluteUri)
                        });

            if (!ClaimsAuthorization.CheckAccess(principal, Constants.Actions.Issue, Constants.Resources.OAuth2))
            {
                Tracing.Error("OAuth2 endpoint authorization failed for user: " + userName);
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidGrant);
            }

            var sts = new STS();
            TokenResponse tokenResponse;
            if (sts.TryIssueToken(scope, principal, tokenType, out tokenResponse))
            {
                if (includeRefreshToken)
                {
                    tokenResponse.RefreshToken = RefreshTokenRepository.AddCode(CodeTokenType.RefreshTokenIdentifier, client.ID, userName, scope.Uri.AbsoluteUri);
                }

                var resp = Request.CreateResponse<TokenResponse>(HttpStatusCode.OK, tokenResponse);
                return resp;
            }
            else
            {
                return OAuthErrorResponseMessage(OAuth2Constants.Errors.InvalidRequest);
            }
        }
        static void ValidateAppliesTo(EndpointReference appliesTo)
        {
            if (SupportedWebApps == null || SupportedWebApps.Length == 0) return;

            var validAppliesTo = SupportedWebApps.Any(x => appliesTo.Uri.Equals(x));

            if (!validAppliesTo)
            {
                throw new InvalidRequestException(String.Format("The 'appliesTo' address '{0}' is not valid.", appliesTo.Uri.OriginalString));
            }
        }
        public static void WriteAppliesTo(XmlWriter writer, EndpointReference appliesTo, WSTrustConstantsAdapter trustConstants)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (appliesTo == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("appliesTo");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            writer.WriteStartElement(WSPolicyConstants.Prefix, WSPolicyConstants.ElementNames.AppliesTo, WSPolicyConstants.NamespaceURI);
            appliesTo.WriteTo(writer);
            writer.WriteEndElement();
        }
        /// <summary>
        /// Reads an <see cref="EndpointReference"/> from xml dictionary reader. The addressing version is defaulted to
        /// <see cref="WSAddressing10Constants.Elements.Address"/>.
        /// </summary>
        /// <param name="reader">The xml dictionary reader.</param>
        /// <returns>An <see cref="EndpointReference"/> instance.</returns>
        public static EndpointReference ReadFrom(XmlDictionaryReader reader)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            reader.ReadFullStartElement();
            reader.MoveToContent();

            if (reader.IsNamespaceUri(WSAddressing10Constants.NamespaceUri) || reader.IsNamespaceUri(WSAddressing200408Constants.NamespaceUri))
            {
                if (reader.IsStartElement(WSAddressing10Constants.Elements.Address, WSAddressing10Constants.NamespaceUri) ||
                    reader.IsStartElement(WSAddressing10Constants.Elements.Address, WSAddressing200408Constants.NamespaceUri))
                {
                    EndpointReference er = new EndpointReference(reader.ReadElementContentAsString());
                    while ( reader.IsStartElement() )
                    {
                        bool emptyElement = reader.IsEmptyElement;
                        
                        XmlReader subtreeReader = reader.ReadSubtree();
                        XmlDocument doc = new XmlDocument();
                        doc.PreserveWhitespace = true;
                        doc.Load( subtreeReader );
                        er._details.Add( doc.DocumentElement );
                        if ( !emptyElement )
                        {
                            reader.ReadEndElement();
                        }
                    }

                    reader.ReadEndElement();
                    return er;
                }
            }

            return null;
        }
Esempio n. 19
0
        internal virtual void Read(string xml, bool validateXmlSignature = false)
        {
#if DEBUG
            Debug.WriteLine("Saml2P: " + xml);
#endif
            
            XmlDocument = xml.ToXmlDocument();

            if (XmlDocument.DocumentElement.NamespaceURI != Saml2Constants.ProtocolNamespace.OriginalString)
            {
                throw new Saml2ResponseException("Not SAML2 Protocol.");
            }

            ValidateElementName();

            Id = new Saml2Id(XmlDocument.DocumentElement.Attributes[Saml2Constants.Message.Id].GetValueOrNull());

            Version = XmlDocument.DocumentElement.Attributes[Saml2Constants.Message.Version].GetValueOrNull();
            if (Version != Saml2Constants.VersionNumber)
            {
                throw new Saml2ResponseException("Invalid SAML2 version.");
            }

            IssueInstant = DateTime.Parse(XmlDocument.DocumentElement.Attributes[Saml2Constants.Message.IssueInstant].GetValueOrNull(), CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

            var issuerString = XmlDocument.DocumentElement[Saml2Constants.Message.Issuer, Saml2Constants.AssertionNamespace.OriginalString].GetTextOrNull();
            if (!string.IsNullOrEmpty(issuerString))
            {
                Issuer = new EndpointReference(issuerString);
            }

            var destinationString = XmlDocument.DocumentElement.Attributes[Saml2Constants.Message.Destination].GetValueOrNull();
            if (!string.IsNullOrEmpty(destinationString))
            {
                Destination = new EndpointAddress(destinationString);
            }
        }
        public ActionResult Issue()
        {
            Tracing.Verbose("Sitefinity endpoint called.");

            var query = _currrenContext.Request.QueryString;

            var realm = query[query.AllKeys.FirstOrDefault(p => p.Equals("realm", System.StringComparison.OrdinalIgnoreCase))];
            var tokenType = query[query.AllKeys.FirstOrDefault(p => p.Equals("tokenType", System.StringComparison.OrdinalIgnoreCase))];
            var reply = query[query.AllKeys.FirstOrDefault(p => p.Equals("redirect_uri", System.StringComparison.OrdinalIgnoreCase))];
            var deflateTemp = query[query.AllKeys.FirstOrDefault(p => p.Equals("deflate", System.StringComparison.OrdinalIgnoreCase))];
            var isSignout = query[query.AllKeys.FirstOrDefault(p => p.Equals("sign_out", System.StringComparison.OrdinalIgnoreCase))];

            //if this is a signout request, sign out the user and redirect
            if (!string.IsNullOrWhiteSpace(isSignout))
            {
                Tracing.Verbose("Sitefinity signout request detected - signout var = " + isSignout);
                if (isSignout.Equals("true", StringComparison.OrdinalIgnoreCase))
                {
                    Tracing.Verbose("Sitefinity logout request");
                    FederatedAuthentication.SessionAuthenticationModule.SignOut();
                    return Redirect((new Uri(new Uri(realm), reply)).AbsoluteUri);
                }
            }

            if (string.IsNullOrWhiteSpace(deflateTemp))
                deflateTemp = "false";

            var deflate = "true".Equals(deflateTemp, StringComparison.OrdinalIgnoreCase);

            Tracing.Verbose("Sitefinity query string parsed");

            if (string.IsNullOrWhiteSpace(realm))
            {
                Tracing.Error("Malformed realm: " + realm);
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "realm parameter is missing.");
            }

            EndpointReference appliesTo;
            try
            {
                appliesTo = new EndpointReference(realm);
                Tracing.Information("Sitefinity Simple HTTP endpoint called for realm: " + realm);
            }
            catch
            {
                Tracing.Error("Malformed realm: " + realm);
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "malformed realm name.");// request.CreateErrorResponse(HttpStatusCode.BadRequest, "malformed realm name.");
            }

            if (string.IsNullOrWhiteSpace(tokenType))
                tokenType = TokenTypes.SimpleWebToken;


            Tracing.Verbose("Sitefinity Token type: " + tokenType);
            Tracing.Verbose("Sitefinity Current Claims Principal: " + ClaimsPrincipal.Current.Claims.ToString() + ", " + ClaimsPrincipal.Current.Identity.Name + ", " + appliesTo.Uri + ", " + appliesTo.Details.ToString());

            SecurityToken tokenResponse;
            var sts = new STS();
            if (sts.TryIssueToken(appliesTo, ClaimsPrincipal.Current, tokenType, out tokenResponse))
            {

                NameValueCollection queryString;
                if (tokenResponse != null)
                    Tracing.Verbose(string.Join(", ", "UID: " + tokenResponse.Id));
                else
                    Tracing.Error("Token is null after being issued");
                var token = new SFSimpleWebToken(tokenResponse as SimpleWebToken);
                //if (token != null)
                //    Tracing.Verbose("Sitefinity Token: " + token.ToString());
                //else
                //    Tracing.Error("Sitefinity Token is null");
                try
                {
                    if (!String.IsNullOrEmpty(reply))
                    {
                        string path;
                        var issuer = HttpContext.Request.Url.AbsoluteUri;
                        var idx = issuer.IndexOf("?");
                        idx = reply.IndexOf('?');
                        if (idx != -1)
                        {
                            path = reply.Substring(0, idx);
                            queryString = HttpUtility.ParseQueryString(reply.Substring(idx + 1));
                        }
                        else
                        {
                            path = reply;
                            queryString = new NameValueCollection();
                        }
                        Tracing.Verbose("Begin wrapping SWT");
                        SFHelper.WrapSWT(queryString, token, deflate);
                        Tracing.Verbose("Begin building path and query for return url");
                        path = String.Concat(path, SFHelper.ToQueryString(queryString));
                        var uri = new Uri(new Uri(realm), path);
                        return Redirect(uri.AbsoluteUri);
                    }

                    queryString = new NameValueCollection();
                    SFHelper.WrapSWT(queryString, token, deflate);
                    return File(SFHelper.ToQueryString(queryString), "application/x-www-form-urlencoded", "token");
                }
                catch (Exception e)
                {
                    Tracing.Error(e.Message + " " + e.InnerException);
                    Tracing.Error("invalid request - token couldn't issue for realm " + realm);
                    return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "invalid request.");
                }
            }
            else
            {
                Tracing.Error("invalid request - token couldn't issue for realm " + realm);
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest, "invalid request.");
            }
        }
        private void FillEndpoints(SecurityTokenServiceDescriptor sts)
        {
            if (string.IsNullOrEmpty(Endpoint)) return;

            var endpoint = new EndpointReference(string.Format("{0}", Endpoint));

            sts.SecurityTokenServiceEndpoints.Add(endpoint);
            sts.PassiveRequestorEndpoints.Add(endpoint);
        }
        public static void WriteOnBehalfOfIssuer(XmlWriter writer, EndpointReference issuer, WSTrustConstantsAdapter trustConstants)
        {
            if (writer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("writer");
            }

            if (issuer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("issuer");
            }

            if (trustConstants == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("trustConstants");
            }

            writer.WriteStartElement(trustConstants.Prefix, trustConstants.Elements.Issuer, trustConstants.NamespaceURI);
            issuer.WriteTo(writer);
            writer.WriteEndElement();
        }