public static SecurityTokenProvider GetCertificateTokenProvider(
     SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, ChannelParameterCollection channelParameters)
 {
     if (tokenManager != null)
     {
         InitiatorServiceModelSecurityTokenRequirement certificateTokenRequirement =
             new InitiatorServiceModelSecurityTokenRequirement();
         certificateTokenRequirement.TokenType                 = SecurityTokenTypes.X509Certificate;
         certificateTokenRequirement.TargetAddress             = target;
         certificateTokenRequirement.Via                       = via;
         certificateTokenRequirement.RequireCryptographicToken = false;
         certificateTokenRequirement.TransportScheme           = transportScheme;
         if (channelParameters != null)
         {
             certificateTokenRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters;
         }
         return(tokenManager.CreateSecurityTokenProvider(certificateTokenRequirement));
     }
     return(null);
 }
        public override SecurityTokenAuthenticator CreateTokenAuthenticator(SecurityTokenParameters p, out SecurityTokenResolver resolver)
        {
            resolver = null;
            // This check might be almost extra, though it is
            // needed to check correct signing token existence.
            //
            // Not sure if it is limited to this condition, but
            // Ssl parameters do not support token provider and
            // still do not fail. X509 parameters do fail.
            if (!RecipientParameters.InternalSupportsServerAuthentication)
            {
                return(null);
            }

            SecurityTokenRequirement r = CreateRequirement();

            r.Properties [ReqType.MessageDirectionProperty] = MessageDirection.Input;
            InitializeRequirement(p, r);
            return(SecurityTokenManager.CreateSecurityTokenAuthenticator(r, out resolver));
        }
 protected void SetSecurityTokenAuthenticator(string scheme, BindingContext context)
 {
     if (base.ReceiveParameters.TransportSecurity.MsmqAuthenticationMode == MsmqAuthenticationMode.Certificate)
     {
         SecurityTokenResolver      resolver;
         SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();
         if (manager == null)
         {
             manager = ServiceCredentials.CreateDefaultCredentials();
         }
         SecurityTokenManager manager2 = manager.CreateSecurityTokenManager();
         RecipientServiceModelSecurityTokenRequirement tokenRequirement = new RecipientServiceModelSecurityTokenRequirement {
             TokenType       = SecurityTokenTypes.X509Certificate,
             TransportScheme = scheme,
             ListenUri       = this.Uri,
             KeyUsage        = SecurityKeyUsage.Signature
         };
         this.x509SecurityTokenAuthenticator = manager2.CreateSecurityTokenAuthenticator(tokenRequirement, out resolver);
     }
 }
        public static SecurityTokenProvider GetDigestTokenProvider(SecurityTokenManager tokenManager, EndpointAddress target, Uri via, string transportScheme, AuthenticationSchemes authenticationScheme, ChannelParameterCollection channelParameters)
        {
            if (tokenManager == null)
            {
                return(null);
            }
            InitiatorServiceModelSecurityTokenRequirement tokenRequirement = new InitiatorServiceModelSecurityTokenRequirement {
                TokenType                 = ServiceModelSecurityTokenTypes.SspiCredential,
                TargetAddress             = target,
                Via                       = via,
                RequireCryptographicToken = false,
                TransportScheme           = transportScheme
            };

            tokenRequirement.Properties[ServiceModelSecurityTokenRequirement.HttpAuthenticationSchemeProperty] = authenticationScheme;
            if (channelParameters != null)
            {
                tokenRequirement.Properties[ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty] = channelParameters;
            }
            return(tokenManager.CreateSecurityTokenProvider(tokenRequirement) as SspiSecurityTokenProvider);
        }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement,
                                                    BindingContext context, bool isClient)
            : base(context.Binding)
        {
            Contract.Assert(isClient, ".NET Core and .NET Native does not support server side");

            _extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            _protectionLevel = bindingElement.ProtectionLevel;
            _scheme          = context.Binding.Scheme;
            _isClient        = isClient;
            _listenUri       = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);

            SecurityCredentialsManager credentialProvider = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                credentialProvider = ClientCredentials.CreateDefaultCredentials();
            }

            _securityTokenManager = credentialProvider.CreateSecurityTokenManager();
        }
        void CallBegin(bool completedSynchronously)
        {
            IAsyncResult result    = null;
            Exception    exception = null;

            try
            {
                CardSpacePolicyElement[] chain;
                SecurityTokenManager     tokenManager = credentials.CreateSecurityTokenManager();
                requiresInfoCard = InfoCardHelper.IsInfocardRequired(binding, credentials, tokenManager, proxy.RemoteAddress, out chain, out relyingPartyIssuer);
                MessageSecurityVersion    bindingSecurityVersion = InfoCardHelper.GetBindingSecurityVersionOrDefault(binding);
                WSSecurityTokenSerializer tokenSerializer        = WSSecurityTokenSerializer.DefaultInstance;
                result = credentials.GetInfoCardTokenCallback.BeginInvoke(requiresInfoCard, chain, tokenManager.CreateSecurityTokenSerializer(bindingSecurityVersion.SecurityTokenVersion), callback, this);
            }
            catch (Exception e)
            {
                if (Fx.IsFatal(e))
                {
                    throw;
                }

                exception = e;
            }
            if (exception == null)
            {
                if (!result.CompletedSynchronously)
                {
                    return;
                }

                this.CallEnd(result, out exception);
            }
            if (exception != null)
            {
                return;
            }


            this.CallComplete(completedSynchronously, null);
        }
        public WindowsStreamSecurityUpgradeProvider(WindowsStreamSecurityBindingElement bindingElement, BindingContext context, bool isClient) : base(context.Binding)
        {
            this.extractGroupsForWindowsAccounts = true;
            this.protectionLevel = bindingElement.ProtectionLevel;
            this.scheme          = context.Binding.Scheme;
            this.isClient        = isClient;
            this.listenUri       = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            SecurityCredentialsManager manager = context.BindingParameters.Find <SecurityCredentialsManager>();

            if (manager == null)
            {
                if (isClient)
                {
                    manager = ClientCredentials.CreateDefaultCredentials();
                }
                else
                {
                    manager = ServiceCredentials.CreateDefaultCredentials();
                }
            }
            this.securityTokenManager = manager.CreateSecurityTokenManager();
        }
예제 #8
0
        internal SecurityProtocolFactory(SecurityProtocolFactory factory) : this()
        {
            if (factory == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(factory));
            }

            ActAsInitiator          = factory.ActAsInitiator;
            _addTimestamp           = factory._addTimestamp;
            _detectReplays          = factory._detectReplays;
            _incomingAlgorithmSuite = factory._incomingAlgorithmSuite;
            _maxCachedNonces        = factory._maxCachedNonces;
            _maxClockSkew           = factory._maxClockSkew;
            _outgoingAlgorithmSuite = factory._outgoingAlgorithmSuite;
            _replayWindow           = factory._replayWindow;
            _channelSupportingTokenAuthenticatorSpecification = new Collection <SupportingTokenAuthenticatorSpecification>(new List <SupportingTokenAuthenticatorSpecification>(factory._channelSupportingTokenAuthenticatorSpecification));
            _standardsManager          = factory._standardsManager;
            _timestampValidityDuration = factory._timestampValidityDuration;
            _securityBindingElement    = (SecurityBindingElement)factory._securityBindingElement?.Clone();
            _securityTokenManager      = factory._securityTokenManager;
            _nonceCache = factory._nonceCache;
        }
예제 #9
0
        private void ValidateToken(HeContext heContext, int userId, int tenantId, string eSpaceKey)
        {
            if (!HttpContext.Current.Request.Headers.AllKeys.Contains("Authorization"))
            {
                // check if in compatibility mode with pre-O11 versions
                if (RuntimePlatformSettings.Authentication.ReferencesAllowLegacyAuth.GetValue())
                {
                    // Check if the request is from a valid IP
                    if (!NetworkInterfaceUtils.IsLoopbackAddress(HttpContext.Current.Request.UserHostAddress))
                    {
                        ErrorLog.StaticWrite(DateTime.Now,
                                             heContext.Session.SessionID,
                                             heContext.AppInfo != null ? heContext.AppInfo.eSpaceId: 0,
                                             heContext.AppInfo != null ? heContext.AppInfo.Tenant.Id: 0,
                                             heContext.Session.UserId,
                                             "Access to ActivityActionsHandler with invalid IP: " + HttpContext.Current.Request.UserHostAddress,
                                             "The activity actions handler can only be accessed by the 127.0.0.1 IP", "BPM");

                        throw new Exception("The activity actions handler can only be accessed by the 127.0.0.1 IP");
                    }
                    else
                    {
                        // Request is valid in compatibility mode
                        return;
                    }
                }
                else
                {
                    throw new Exception("Token validation failed");
                }
            }

            SecurityTokenManager.ValidateAuthorizationHeader(
                RuntimeSettingsProvider.Instance,
                HttpContext.Current.Request.Headers["Authorization"],
                userId,
                tenantId,
                eSpaceKey);
        }
예제 #10
0
        public string FindAllByDate(string securityToken, string beginDate, string endDate, int length)
        {
            try
            {
                StringBuilder outString = new StringBuilder();

                string applicationId = SecurityTokenManager.Authenticate(securityToken);

                string whereClause = string.Format(" ApplicationId = ##{0}## AND ( CreateDate > ##{1}## AND CreateDate < ##{2}## ) ",
                                                   applicationId,
                                                   beginDate,
                                                   endDate);

                IList <TaskWorkItemInfo> list = TasksContext.Instance.TaskService.FindAll(whereClause, length);

                outString.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

                outString.Append("<root>");

                foreach (TaskWorkItemInfo item in list)
                {
                    // outString.Append(item.Serializable());
                }

                outString.Append("</root>");

                return(outString.ToString());
            }
            catch (Exception ex)
            {
                return(string.Format("SecurityToken:{0}\r\nBeginDate:{1}\r\nEndDate:{2}\r\nLength:{3}\r\nException:{4}",
                                     securityToken,
                                     beginDate,
                                     endDate,
                                     length,
                                     ex.ToString()));
            }
        }
예제 #11
0
        public string FindAllByLoginName(string securityToken, string loginName, int length)
        {
            try
            {
                StringBuilder outString = new StringBuilder();

                string applicationId = SecurityTokenManager.Authenticate(securityToken);

                IAccountInfo account = Membership.MembershipManagement.Instance.AccountService.FindOneByLoginName(loginName);

                string whereClause = string.Format(" ApplicationId = ##{0}## AND ( SenderId = ##{1}## OR Id IN ( SELECT TaskId FROM TaskReceiver WHERE ReceiverId = ##{1}## ))",
                                                   applicationId,
                                                   account.Id);

                IList <TaskWorkItemInfo> list = TasksContext.Instance.TaskService.FindAll(whereClause, length);

                outString.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");

                outString.Append("<root>");

                foreach (TaskWorkItemInfo item in list)
                {
                    // outString.Append(item.Serializable());
                }

                outString.Append("</root>");

                return(outString.ToString());
            }
            catch (Exception ex)
            {
                return(string.Format("SecurityToken:{0}\r\nloginName:{1}\r\nLength:{2}\r\nException:{3}",
                                     securityToken,
                                     loginName,
                                     length,
                                     ex.ToString()));
            }
        }
예제 #12
0
        // used by server WindowsStream security (from Open)
        public static NetworkCredential GetSspiCredential(SecurityTokenManager credentialProvider,
                                                          SecurityTokenRequirement sspiTokenRequirement, TimeSpan timeout,
                                                          out bool extractGroupsForWindowsAccounts)
        {
            extractGroupsForWindowsAccounts = TransportDefaults.ExtractGroupsForWindowsAccounts;
            NetworkCredential result = null;

            if (credentialProvider != null)
            {
                SecurityTokenProvider tokenProvider = credentialProvider.CreateSecurityTokenProvider(sspiTokenRequirement);
                if (tokenProvider != null)
                {
                    TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
                    SecurityUtils.OpenTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
                    bool success = false;
                    try
                    {
                        OutWrapper <TokenImpersonationLevel> dummyImpersonationLevelWrapper = new OutWrapper <TokenImpersonationLevel>();
                        OutWrapper <bool> dummyAllowNtlmWrapper = new OutWrapper <bool>();
                        OutWrapper <bool> extractGroupsForWindowsAccountsWrapper = new OutWrapper <bool>();
                        result = GetSspiCredentialAsync((SspiSecurityTokenProvider)tokenProvider, extractGroupsForWindowsAccountsWrapper,
                                                        dummyImpersonationLevelWrapper, dummyAllowNtlmWrapper, timeoutHelper.RemainingTime()).GetAwaiter().GetResult();

                        success = true;
                    }
                    finally
                    {
                        if (!success)
                        {
                            SecurityUtils.AbortTokenProviderIfRequired(tokenProvider);
                        }
                    }
                    SecurityUtils.CloseTokenProviderIfRequired(tokenProvider, timeoutHelper.RemainingTime());
                }
            }

            return(result);
        }
예제 #13
0
        BuildChannelFactoryCore <TChannel> (
            BindingContext context)
        {
            if (ProtectionTokenParameters == null)
            {
                throw new InvalidOperationException("Protection token parameters must be set before building channel factory.");
            }

            SetIssuerBindingContextIfRequired(ProtectionTokenParameters, context);

            ClientCredentials cred = context.BindingParameters.Find <ClientCredentials> ();

            if (cred == null)
            {
                // it happens when there is no ChannelFactory<T>.
                cred = new ClientCredentials();
            }
            SecurityTokenManager          manager      = cred.CreateSecurityTokenManager();
            ChannelProtectionRequirements requirements =
                context.BindingParameters.Find <ChannelProtectionRequirements> ();

            return(new SecurityChannelFactory <TChannel> (
                       context.BuildInnerChannelFactory <TChannel> (), new InitiatorMessageSecurityBindingSupport(GetCapabilities(), manager, requirements)));
        }
        public static SslStreamSecurityUpgradeProvider CreateServerProvider(
            SslStreamSecurityBindingElement bindingElement, BindingContext context)
        {
            SecurityCredentialsManager credentialProvider =
                context.BindingParameters.Find <SecurityCredentialsManager>();

            if (credentialProvider == null)
            {
                credentialProvider = ServiceCredentials.CreateDefaultCredentials();
            }

            Uri listenUri = TransportSecurityHelpers.GetListenUri(context.ListenUriBaseAddress, context.ListenUriRelativeAddress);
            SecurityTokenManager tokenManager = credentialProvider.CreateSecurityTokenManager();

            RecipientServiceModelSecurityTokenRequirement serverCertRequirement = new RecipientServiceModelSecurityTokenRequirement
            {
                TokenType = SecurityTokenTypes.X509Certificate,
                RequireCryptographicToken = true,
                KeyUsage        = SecurityKeyUsage.Exchange,
                TransportScheme = context.Binding.Scheme,
                ListenUri       = listenUri
            };

            SecurityTokenProvider tokenProvider = tokenManager.CreateSecurityTokenProvider(serverCertRequirement);

            if (tokenProvider == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCredentialsUnableToCreateLocalTokenProvider, serverCertRequirement)));
            }

            SecurityTokenAuthenticator certificateAuthenticator =
                TransportSecurityHelpers.GetCertificateTokenAuthenticator(tokenManager, context.Binding.Scheme, listenUri);

            return(new SslStreamSecurityUpgradeProvider(context.Binding, tokenProvider, bindingElement.RequireClientCertificate,
                                                        certificateAuthenticator, context.Binding.Scheme, bindingElement.IdentityVerifier, bindingElement.SslProtocols));
        }
예제 #15
0
        public static int SendEmailRequest(string url, string from, string to, string cc, string bcc,
                                           int activityId, int tenantId, int userId, string consumerKey, string producerKey,
                                           bool storeContent, EmailType type)
        {
            from = EmailFunctions.Normalize(from);
            to   = EmailFunctions.Normalize(to);
            cc   = EmailFunctions.Normalize(cc);
            bcc  = EmailFunctions.Normalize(bcc);

            if (to.IsEmpty() && cc.IsEmpty() && bcc.IsEmpty())
            {
                throw new InvalidOperationException("Error creating email. There must be at least one recipient.");
            }

            try {
                int emailId = 0;

                url = url
                      + (url.Contains("?") ? "&" : "?")
                      + "_From=" + HttpUtility.UrlEncode(from)
                      + "&_To=" + HttpUtility.UrlEncode(to)
                      + "&_CC=" + HttpUtility.UrlEncode(cc)
                      + "&_BCC=" + HttpUtility.UrlEncode(bcc)
                      + "&_ActivityId=" + activityId
                      + "&_TenantId=" + tenantId
                      + "&_UserId=" + userId
                      + "&_ProducerKey=" + producerKey
                      + "&_IsEmail=true"
                      + "&_StoreContent=" + ((storeContent || (type == EmailType.TestDownloadEmail)) ? "true" : "false")
                      + ((type == EmailType.TestSendEmail || type == EmailType.TestDownloadEmail) ? "&_IsTestEmail=true" : "");

                string baseUrl;
                EmailHelper.QueryParameter[] parameters;
                EmailHelper.SplitUrl(url, out baseUrl, out parameters);

                string content;
                string encoding;
                var    authHeader = SecurityTokenManager.GenerateAuthorizationHeader(RuntimeSettingsProvider.Instance, consumerKey, producerKey, userId, tenantId);
                var    headers    = new Dictionary <HttpRequestHeader, string>();
                headers.Add(HttpRequestHeader.Authorization, authHeader);
                EmailHelper.HttpPost(baseUrl, parameters, headers, "", null, out content, out encoding);

                var exceptionMatch = exceptionExp.Match(content);
                if (exceptionMatch != Match.Empty)
                {
                    string message    = HttpUtility.HtmlDecode(exceptionMatch.Groups[1].Value);
                    string stacktrace = HttpUtility.HtmlDecode(exceptionMatch.Groups[2].Value);
                    throw new EmailException("Error creating Email. " + message, stacktrace);
                }
                else
                {
                    var emailMatch = emailIdExp.Match(content);
                    if (emailMatch != Match.Empty)
                    {
                        emailId = Convert.ToInt32(emailMatch.Groups[1].Value);
                    }
                    else
                    {
                        throw new EmailException("Error creating Email. No EmailId was returned.");
                    }
                }

                if (type != EmailType.TestDownloadEmail)
                {
                    if (RuntimePlatformSettings.Sandbox.SandboxOperating.GetValue())
                    {
                        using (Transaction statusTransaction = DatabaseAccess.ForCurrentDatabase.GetCommitableTransaction()) {
                            DBRuntimePlatform.Instance.CreateEmailStatus(statusTransaction, emailId);
                            SendEmailNotifier.Current.NotifiyNewEmail();
                            statusTransaction.Commit();
                        }
                    }
                    else
                    {
                        using (Transaction trans = DatabaseAccess.ForRuntimeDatabase.GetRequestTransaction()) {
                            DBRuntimePlatform.Instance.CreateEmailStatus(trans, emailId);
                        }
                    }
                }
                return(emailId);
            } catch (EmailException) {
                throw;
            } catch (Exception e) {
                throw new EmailException("Error creating Email.", e);
            }
        }
        public static bool IsInfocardRequired(Binding binding, ClientCredentials clientCreds, SecurityTokenManager clientCredentialsTokenManager, EndpointAddress target, out CardSpacePolicyElement[] infocardChain, out Uri relyingPartyIssuer)
        {
            infocardChain = null;
            bool flag = false;

            relyingPartyIssuer = null;
            if (!clientCreds.SupportInteractive || ((null != clientCreds.IssuedToken.LocalIssuerAddress) && (clientCreds.IssuedToken.LocalIssuerBinding != null)))
            {
                return(false);
            }
            IssuedSecurityTokenParameters parameters = TryGetNextStsIssuedTokenParameters(binding);

            if (parameters != null)
            {
                Uri uri;
                int num;
                GetPrivacyNoticeLinkFromIssuerBinding(binding, out uri, out num);
                PolicyElement[] chain = GetPolicyChain(target, binding, parameters, uri, num, clientCredentialsTokenManager);
                relyingPartyIssuer = null;
                if (chain != null)
                {
                    flag = RequiresInfoCard(chain, out relyingPartyIssuer);
                }
                if (!flag)
                {
                    return(flag);
                }
                infocardChain = new CardSpacePolicyElement[chain.Length];
                for (int i = 0; i < chain.Length; i++)
                {
                    infocardChain[i] = chain[i].ToCardSpacePolicyElement();
                }
            }
            return(flag);
        }
예제 #17
0
        internal static SecurityStandardsManager CreateSecurityStandardsManager(SecurityTokenRequirement requirement, SecurityTokenManager tokenManager)
        {
            MessageSecurityTokenVersion securityVersion = (MessageSecurityTokenVersion)requirement.GetProperty <MessageSecurityTokenVersion>(ServiceModelSecurityTokenRequirement.MessageSecurityVersionProperty);

            if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10)
            {
                return(CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager));
            }
            if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005)
            {
                return(CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11, tokenManager));
            }
            if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005BasicSecurityProfile10)
            {
                return(CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, tokenManager));
            }
            if (securityVersion == MessageSecurityTokenVersion.WSSecurity10WSTrust13WSSecureConversation13BasicSecurityProfile10)
            {
                return(CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager));
            }
            if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13)
            {
                return(CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12, tokenManager));
            }
            if (securityVersion == MessageSecurityTokenVersion.WSSecurity11WSTrust13WSSecureConversation13BasicSecurityProfile10)
            {
                return(CreateSecurityStandardsManager(MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10, tokenManager));
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException());
        }
예제 #18
0
        internal static SecurityStandardsManager CreateSecurityStandardsManager(MessageSecurityVersion securityVersion, SecurityTokenManager tokenManager)
        {
            SecurityTokenSerializer tokenSerializer = tokenManager.CreateSecurityTokenSerializer(securityVersion.SecurityTokenVersion);

            return(new SecurityStandardsManager(securityVersion, tokenSerializer));
        }
        private static PolicyElement[] GetPolicyChain(EndpointAddress target, Binding outerBinding, IssuedSecurityTokenParameters parameters, Uri firstPrivacyNoticeLink, int firstPrivacyNoticeVersion, SecurityTokenManager clientCredentialsTokenManager)
        {
            EndpointAddress issuerAddress             = target;
            IssuedSecurityTokenParameters parameters2 = parameters;
            List <PolicyElement>          list        = new List <PolicyElement>();
            Uri  privacyNoticeLink    = firstPrivacyNoticeLink;
            int  privacyNoticeVersion = firstPrivacyNoticeVersion;
            bool isManagedIssuer      = false;

            while (parameters2 != null)
            {
                MessageSecurityVersion messageSecurityVersion = null;
                if (parameters2.IssuerBinding == null)
                {
                    messageSecurityVersion = GetBindingSecurityVersionOrDefault(outerBinding);
                }
                else
                {
                    messageSecurityVersion = GetBindingSecurityVersionOrDefault(parameters2.IssuerBinding);
                }
                list.Add(new PolicyElement(issuerAddress, parameters2.IssuerAddress, parameters2.CreateRequestParameters(messageSecurityVersion, clientCredentialsTokenManager.CreateSecurityTokenSerializer(messageSecurityVersion.SecurityTokenVersion)), privacyNoticeLink, privacyNoticeVersion, isManagedIssuer, parameters2.IssuerBinding));
                isManagedIssuer = IsReferralToManagedIssuer(parameters2.IssuerBinding);
                GetPrivacyNoticeLinkFromIssuerBinding(parameters2.IssuerBinding, out privacyNoticeLink, out privacyNoticeVersion);
                issuerAddress = parameters2.IssuerAddress;
                outerBinding  = parameters2.IssuerBinding;
                parameters2   = TryGetNextStsIssuedTokenParameters(parameters2.IssuerBinding);
            }
            if (isManagedIssuer)
            {
                list.Add(new PolicyElement(issuerAddress, null, null, privacyNoticeLink, privacyNoticeVersion, isManagedIssuer, null));
            }
            return(list.ToArray());
        }
 private SslStreamSecurityUpgradeProvider(IDefaultCommunicationTimeouts timeouts, SecurityTokenManager clientSecurityTokenManager, bool requireClientCertificate, string scheme, IdentityVerifier identityVerifier, SslProtocols sslProtocols)
     : base(timeouts)
 {
     _identityVerifier           = identityVerifier;
     _scheme                     = scheme;
     _clientSecurityTokenManager = clientSecurityTokenManager;
     _requireClientCertificate   = requireClientCertificate;
     _sslProtocols               = sslProtocols;
 }
예제 #21
0
        private string Process(string securityToken, string xml, string actionType)
        {
            try
            {
                /*
                 *
                 * Xml数据示例
                 *
                 * <?xml version="1.0" encoding="utf-8"?>
                 *
                 * <root>
                 *     <task>
                 *         <taskCode>T00001</taskCode>
                 *         <title>Some Title</title>
                 *         <url>http://www.google.com</url>
                 *         <category>Document</category>
                 *         <senderId>administrator</senderId>
                 *         <receiver>0#test1,1#test2#2008-1-1 08:08:08</receiver>
                 *         <createDate>2008-01-01</createDate>
                 *     </task>
                 *     <task>
                 *         <taskCode>T00002</taskCode>
                 *         <title>Some Title</title>
                 *         <url>http://www.google.com</url>
                 *         <category>Document</category>
                 *         <senderId>administrator</senderId>
                 *         <receiver>0#test1,1#test2#2008-1-1 08:08:08</receiver>
                 *         <createDate>2008-01-01</createDate>
                 *     </task>
                 * </root>
                 *
                 * (*) 接收者信息说明 格式:{0}#{1}#{2} , {0}代表代办状态 1 完成 0 未完成, {1}相关的帐号, {2}{任务完成时间}
                 *
                 *
                 *
                 */

                string result = null;

                string applicationId = SecurityTokenManager.Authenticate(securityToken);

                TaskWorkInfo param = null;

                XmlDocument doc = new XmlDocument();

                doc.LoadXml(xml);

                XmlNodeList list = doc.GetElementsByTagName("ajaxStorage")[0].ChildNodes;

                foreach (XmlNode item in list)
                {
                    param = new TaskWorkInfo(applicationId);

                    param.Deserialize((XmlElement)item);

                    if (param.ReceiverGroup.Count == 0)
                    {
                        result += string.Format("任务【{0}】没有指派给任何用户请重新设置,", param.TaskCode);
                    }
                    else
                    {
                        if (actionType == "发送" &&
                            TasksContext.Instance.TaskService.IsExistTaskCode(param.ApplicationId, param.TaskCode))
                        {
                            result += string.Format("发送失败(任务【{0}】已存在),", param.TaskCode);
                        }
                        else if (actionType == "更新" &&
                                 !TasksContext.Instance.TaskService.IsExistTaskCode(param.ApplicationId, param.TaskCode))
                        {
                            result += string.Format("更新失败(任务【{0}】不存在),", param.TaskCode);
                        }
                        else
                        {
                            param = TasksContext.Instance.TaskService.Save(param);

                            if (param == null)
                            {
                                result += string.Format("任务【{0}】" + actionType + "失败请重新" + actionType + ",", param.TaskCode);
                            }
                        }
                    }
                }

                if (string.IsNullOrEmpty(result))
                {
                    return("任务全部" + actionType + "成功。");
                }
                else
                {
                    return(result.TrimEnd(new char[] { ',' }) + "。");
                }
            }
            catch (Exception ex)
            {
                return(string.Format("SecurityToken:{0}\r\nXml:{1}\r\nException:{2}", securityToken, xml, ex.ToString()));
            }
        }
예제 #22
0
 private SslStreamSecurityUpgradeProvider(IDefaultCommunicationTimeouts timeouts, SecurityTokenManager clientSecurityTokenManager, bool requireClientCertificate, string scheme, System.ServiceModel.Security.IdentityVerifier identityVerifier) : base(timeouts)
 {
     this.identityVerifier           = identityVerifier;
     this.scheme                     = scheme;
     this.clientSecurityTokenManager = clientSecurityTokenManager;
     this.requireClientCertificate   = requireClientCertificate;
 }
예제 #23
0
        public static bool IsInfocardRequired(Binding binding, ClientCredentials clientCreds, SecurityTokenManager clientCredentialsTokenManager, EndpointAddress target, out CardSpacePolicyElement[] infocardChain, out Uri relyingPartyIssuer)
        {
            infocardChain = null;
            bool requiresInfoCard = false;

            relyingPartyIssuer = null;
            if (!clientCreds.SupportInteractive ||
                (null != clientCreds.IssuedToken.LocalIssuerAddress && null != clientCreds.IssuedToken.LocalIssuerBinding)
                )
            {
                return(false);
            }
            IssuedSecurityTokenParameters parameters = TryGetNextStsIssuedTokenParameters(binding);

            if (null != parameters)
            {
                Uri privacyNotice;
                int privacyVersion;
                GetPrivacyNoticeLinkFromIssuerBinding(binding, out privacyNotice, out privacyVersion);

                PolicyElement[] policyChain = GetPolicyChain(target, binding, parameters, privacyNotice, privacyVersion, clientCredentialsTokenManager);
                relyingPartyIssuer = null;
                if (null != policyChain)
                {
                    requiresInfoCard = RequiresInfoCard(policyChain, out relyingPartyIssuer);
                }
                if (requiresInfoCard)
                {
                    infocardChain = new CardSpacePolicyElement[policyChain.Length];
                    for (int i = 0; i < policyChain.Length; i++)
                    {
                        infocardChain[i] = policyChain[i].ToCardSpacePolicyElement();
                    }
                }
            }
            return(requiresInfoCard);
        }
예제 #24
0
        static PolicyElement[] GetPolicyChain(EndpointAddress target, Binding outerBinding, IssuedSecurityTokenParameters parameters, Uri firstPrivacyNoticeLink, int firstPrivacyNoticeVersion, SecurityTokenManager clientCredentialsTokenManager)
        {
            EndpointAddress nextTarget = target;
            IssuedSecurityTokenParameters nextParameters = parameters;

            List <PolicyElement> chain = new List <PolicyElement>();

            Uri  privacyNoticeLink    = firstPrivacyNoticeLink;
            int  privacyNoticeVersion = firstPrivacyNoticeVersion;
            bool isManagedIssuer      = false;


            //
            // this is the binding to the final STS in the chain. Start from here and walk the
            // chain backwards to the 1st STS in the chain
            //
            while (null != nextParameters)
            {
                MessageSecurityVersion bindingSecurityVersion = null;
                if (nextParameters.IssuerBinding == null)
                {
                    bindingSecurityVersion = GetBindingSecurityVersionOrDefault(outerBinding);
                }
                else
                {
                    bindingSecurityVersion = GetBindingSecurityVersionOrDefault(nextParameters.IssuerBinding);
                }
                chain.Add(new PolicyElement(nextTarget,
                                            nextParameters.IssuerAddress,
                                            nextParameters.CreateRequestParameters(bindingSecurityVersion, clientCredentialsTokenManager.CreateSecurityTokenSerializer(bindingSecurityVersion.SecurityTokenVersion)),
                                            privacyNoticeLink,
                                            privacyNoticeVersion,
                                            isManagedIssuer,
                                            nextParameters.IssuerBinding));

                isManagedIssuer = IsReferralToManagedIssuer(nextParameters.IssuerBinding);
                GetPrivacyNoticeLinkFromIssuerBinding(nextParameters.IssuerBinding, out privacyNoticeLink, out privacyNoticeVersion);
                nextTarget     = nextParameters.IssuerAddress;
                outerBinding   = nextParameters.IssuerBinding;
                nextParameters = TryGetNextStsIssuedTokenParameters(nextParameters.IssuerBinding);
            }

            //
            // Add the last element for the MCIP case
            //
            if (isManagedIssuer)
            {
                chain.Add(new PolicyElement(nextTarget,
                                            null,
                                            null,
                                            privacyNoticeLink,
                                            privacyNoticeVersion,
                                            isManagedIssuer,
                                            null));
            }
            return(chain.ToArray());
        }