internal SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement, bool disableInfoCard) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } SecurityTokenProvider result = null; if (disableInfoCard || !CardSpaceTryCreateSecurityTokenProviderStub(tokenRequirement, this, out result)) { if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange) { // this is the uncorrelated duplex case if (parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(parent.ClientCertificate.Certificate); } else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement) { InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement; #pragma warning suppress 56506 // initiatorRequirement will never be null due to the preceding 'is' validation. string tokenType = initiatorRequirement.TokenType; if (IsIssuedSecurityTokenRequirement(initiatorRequirement)) { FederatedClientCredentialsParameters additionalParameters = this.FindFederatedChannelParameters(tokenRequirement); if (additionalParameters != null && additionalParameters.IssuedSecurityToken != null) { return(new SimpleSecurityTokenProvider(additionalParameters.IssuedSecurityToken, tokenRequirement)); } result = CreateIssuedSecurityTokenProvider(initiatorRequirement, additionalParameters); } else if (tokenType == SecurityTokenTypes.X509Certificate) { if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange) { result = CreateServerX509TokenProvider(initiatorRequirement.TargetAddress); } else { if (parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(parent.ClientCertificate.Certificate); } } else if (tokenType == SecurityTokenTypes.Kerberos) { string spn = GetServicePrincipalName(initiatorRequirement); result = new KerberosSecurityTokenProviderWrapper( new KerberosSecurityTokenProvider(spn, parent.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(parent.Windows.ClientCredential)), GetCredentialsHandle(initiatorRequirement)); } else if (tokenType == SecurityTokenTypes.UserName) { if (parent.UserName.UserName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.UserNamePasswordNotProvidedOnClientCredentials))); } result = new UserNameSecurityTokenProvider(parent.UserName.UserName, parent.UserName.Password); } else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential) { if (IsDigestAuthenticationScheme(initiatorRequirement)) { result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(parent.HttpDigest.ClientCredential), true, parent.HttpDigest.AllowedImpersonationLevel); } else { #pragma warning disable 618 // to disable AllowNtlm obsolete wanring. result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(parent.Windows.ClientCredential), parent.Windows.AllowNtlm, parent.Windows.AllowedImpersonationLevel); #pragma warning restore 618 } } else if (tokenType == ServiceModelSecurityTokenTypes.Spnego) { result = CreateSpnegoTokenProvider(initiatorRequirement); } else if (tokenType == ServiceModelSecurityTokenTypes.MutualSslnego) { result = CreateTlsnegoTokenProvider(initiatorRequirement, true); } else if (tokenType == ServiceModelSecurityTokenTypes.AnonymousSslnego) { result = CreateTlsnegoTokenProvider(initiatorRequirement, false); } else if (tokenType == ServiceModelSecurityTokenTypes.SecureConversation) { result = CreateSecureConversationSecurityTokenProvider(initiatorRequirement); } } } if ((result == null) && !tokenRequirement.IsOptionalToken) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement))); } return(result); }
/// <summary> /// Sets the digital signature on the specified file. /// </summary> /// <param name="filePath"> /// The name of the file on which to perform the action. /// </param> /// <returns> /// The signature on the specified file. /// </returns> protected override Signature PerformAction(string filePath) { SigningOption option = GetSigningOption(IncludeChain); if (Certificate == null) { throw PSTraceSource.NewArgumentNullException("certificate"); } // // if the cert is not good for signing, we cannot // process any more files. Exit the command. // if (!SecuritySupport.CertIsGoodForSigning(Certificate)) { Exception e = PSTraceSource.NewArgumentException( "certificate", SignatureCommands.CertNotGoodForSigning); throw e; } if (!ShouldProcess(filePath)) { return(null); } FileInfo readOnlyFileInfo = null; try { if (this.Force) { try { // remove readonly attributes on the file FileInfo fInfo = new FileInfo(filePath); if (fInfo != null) { // Save some disk write time by checking whether file is readonly.. if ((fInfo.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) { // remember to reset the read-only attribute later readOnlyFileInfo = fInfo; //Make sure the file is not read only fInfo.Attributes &= ~(FileAttributes.ReadOnly); } } } // These are the known exceptions for File.Load and StreamWriter.ctor catch (ArgumentException e) { ErrorRecord er = new ErrorRecord( e, "ForceArgumentException", ErrorCategory.WriteError, filePath ); WriteError(er); return(null); } catch (IOException e) { ErrorRecord er = new ErrorRecord( e, "ForceIOException", ErrorCategory.WriteError, filePath ); WriteError(er); return(null); } catch (UnauthorizedAccessException e) { ErrorRecord er = new ErrorRecord( e, "ForceUnauthorizedAccessException", ErrorCategory.PermissionDenied, filePath ); WriteError(er); return(null); } catch (NotSupportedException e) { ErrorRecord er = new ErrorRecord( e, "ForceNotSupportedException", ErrorCategory.WriteError, filePath ); WriteError(er); return(null); } catch (System.Security.SecurityException e) { ErrorRecord er = new ErrorRecord( e, "ForceSecurityException", ErrorCategory.PermissionDenied, filePath ); WriteError(er); return(null); } } // // ProcessRecord() code in base class has already // ascertained that filePath really represents an existing // file. Thus we can safely call GetFileSize() below. // if (SecurityUtils.GetFileSize(filePath) < 4) { // Note that the message param comes first string message = String.Format( System.Globalization.CultureInfo.CurrentCulture, UtilsStrings.FileSmallerThan4Bytes, filePath); PSArgumentException e = new PSArgumentException(message, "filePath"); ErrorRecord er = SecurityUtils.CreateInvalidArgumentErrorRecord( e, "SignatureCommandsBaseFileSmallerThan4Bytes" ); WriteError(er); return(null); } return(SignatureHelper.SignFile(option, filePath, Certificate, TimestampServer, _hashAlgorithm)); } finally { // reset the read-only attribute if (readOnlyFileInfo != null) { readOnlyFileInfo.Attributes |= FileAttributes.ReadOnly; } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddCors(); services.AddControllers() .AddJsonOptions(options => { options.JsonSerializerOptions.NumberHandling = JsonNumberHandling.AllowReadingFromString; }); services.AddDbContext <MainDbContext>(b => { b.UseSqlite("Data Source=main.db;"); }); services.AddIdentity <ApplicationUser, IdentityRole>(c => { }) .AddEntityFrameworkStores <MainDbContext>(); services.AddScoped <IAuthenticationHandler, BasicAuthenticationHandler>(); services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(c => { c.TokenValidationParameters = new TokenValidationParameters { ClockSkew = TimeSpan.FromMinutes(5), // TODO: Create signing key from certificate IssuerSigningKey = SecurityUtils.CreateSecurityKey("THIS_IS_A_SECRET_THAT_I_AM_MAKING_LONGER"), RequireSignedTokens = true, RequireExpirationTime = true, ValidateLifetime = true, // TODO: Do stuff with Audience and Issuer }; }) .AddCookie(c => { c.LoginPath = "/api/AccountSvc/SignIn"; c.LogoutPath = "/api/AccountSvc/SignOut"; }) .AddScheme <AuthenticationSchemeOptions, BasicAuthenticationHandler>("Basic", c => { }); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new OpenApiInfo { Title = "Home Inventory", Version = "v1" }); var jwtSecurityScheme = new OpenApiSecurityScheme { Type = SecuritySchemeType.Http, Scheme = "bearer", In = ParameterLocation.Header, Reference = new OpenApiReference { Id = "Bearer", Type = ReferenceType.SecurityScheme } }; var basicSecurityScheme = new OpenApiSecurityScheme { Type = SecuritySchemeType.Http, Scheme = "basic", In = ParameterLocation.Header, Reference = new OpenApiReference { Id = "Basic", Type = ReferenceType.SecurityScheme } }; c.AddSecurityDefinition(basicSecurityScheme.Reference.Id, basicSecurityScheme); c.AddSecurityDefinition(jwtSecurityScheme.Reference.Id, jwtSecurityScheme); c.AddSecurityRequirement(new OpenApiSecurityRequirement { { basicSecurityScheme, Array.Empty <string>() }, { jwtSecurityScheme, Array.Empty <string>() } }); }); }
public StorageSpaceFolderShare ShareFolder(string fullPath, string shareName) { Runspace runspace = null; shareName = shareName.Replace(" ", ""); try { runspace = OpenRunspace(); if (ShareExist(shareName, runspace)) { var share = GetShare(shareName, runspace); if (String.Compare(share.Path, fullPath, StringComparison.InvariantCultureIgnoreCase) == 0) { return(share); } //finding first not used share name for (int i = 0; i < int.MaxValue; i++) { var tmpShareName = shareName + i; if (!ShareExist(tmpShareName, runspace)) { shareName = tmpShareName; break; } } } Log.WriteStart("ShareFolder"); Log.WriteInfo("FolderPath : {0}", fullPath); // 01.09.2015 [email protected] // Problem: On German Systems the Accounts 'NETWORK SERVICE' and 'EVERYONE' does not exist. // The equivalent in German is 'NETZWERKDIENST' for 'NETWORK SERVICE' and 'JEDER' for 'EVERYONE' // FIX: To Fix this translate the SID for the Accounts into the current Language //var scripts = new List<string> //{ // string.Format("net share {0}=\"{1}\" \"/grant:NETWORK SERVICE,full\" \"/grant:Everyone,full\"",shareName, fullPath) //}; var scripts = new List <string> { string.Format(CultureInfo.InvariantCulture, "net share {0}=\"{1}\" \"/grant:{2},full\" \"/grant:{3},full\"", shareName, fullPath, SecurityUtils.GetAccountNameFromSid(System.Security.Principal.WellKnownSidType.NetworkServiceSid, ServerSettings), SecurityUtils.GetAccountNameFromSid(SystemSID.EVERYONE, ServerSettings)) }; object[] errors = null; var result = ExecuteLocalScript(runspace, scripts, out errors); return(GetShare(shareName, runspace)); } catch (Exception ex) { Log.WriteError(ex); throw; } finally { CloseRunspace(runspace); Log.WriteEnd("ShareFolder"); } }
private object Deserialize() { object defaultValue = null; if (this.SerializedValue != null) { try { if (this.SerializedValue is string) { defaultValue = GetObjectFromString(this.Property.PropertyType, this.Property.SerializeAs, (string)this.SerializedValue); } else { MemoryStream serializationStream = new MemoryStream((byte[])this.SerializedValue); try { defaultValue = new BinaryFormatter().Deserialize(serializationStream); } finally { serializationStream.Close(); } } } catch (Exception exception) { try { if (this.IsHostedInAspnet()) { object[] args = new object[] { this.Property, this, exception }; Type.GetType("System.Web.Management.WebBaseEvent, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", true).InvokeMember("RaisePropertyDeserializationWebErrorEvent", BindingFlags.InvokeMethod | BindingFlags.NonPublic | BindingFlags.Static, null, null, args, CultureInfo.InvariantCulture); } } catch { } } if ((defaultValue != null) && !this.Property.PropertyType.IsAssignableFrom(defaultValue.GetType())) { defaultValue = null; } } if (defaultValue == null) { this._UsingDefaultValue = true; if ((this.Property.DefaultValue == null) || (this.Property.DefaultValue.ToString() == "[null]")) { if (this.Property.PropertyType.IsValueType) { return(SecurityUtils.SecureCreateInstance(this.Property.PropertyType)); } return(null); } if (this.Property.DefaultValue is string) { try { defaultValue = GetObjectFromString(this.Property.PropertyType, this.Property.SerializeAs, (string)this.Property.DefaultValue); } catch (Exception exception2) { throw new ArgumentException(System.SR.GetString("Could_not_create_from_default_value", new object[] { this.Property.Name, exception2.Message })); } } else { defaultValue = this.Property.DefaultValue; } if ((defaultValue != null) && !this.Property.PropertyType.IsAssignableFrom(defaultValue.GetType())) { throw new ArgumentException(System.SR.GetString("Could_not_create_from_default_value_2", new object[] { this.Property.Name })); } } if (defaultValue == null) { if (this.Property.PropertyType == typeof(string)) { return(""); } try { defaultValue = SecurityUtils.SecureCreateInstance(this.Property.PropertyType); } catch { } } return(defaultValue); }
/// <summary> /// 用户密码解密 /// </summary> /// <param name="password"></param> /// <returns></returns> public static String PasswordDecrypt(String password) { return(SecurityUtils.AESDecrypt(password, USER_PASSWORD_PREFIX)); }
private static SecurityMessageProperty CreateServerSecurity(NegotiateStream negotiateStream) { GenericIdentity remoteIdentity = (GenericIdentity)negotiateStream.RemoteIdentity; string principalName = remoteIdentity.Name; if ((principalName != null) && (principalName.Length > 0)) { ReadOnlyCollection <IAuthorizationPolicy> authorizationPolicies = SecurityUtils.CreatePrincipalNameAuthorizationPolicies(principalName); SecurityMessageProperty result = new SecurityMessageProperty(); result.TransportToken = new SecurityTokenSpecification(null, authorizationPolicies); result.ServiceSecurityContext = new ServiceSecurityContext(authorizationPolicies); return(result); } else { return(null); } }
/// <summary> /// Installs Ftp7 provider. /// </summary> /// <returns>Error messages.</returns> public override string[] Install() { List <string> messages = new List <string>(); FtpSite site = null; string folder = FileUtils.EvaluateSystemVariables(DefaultFtpSiteFolder); string logsDirectory = FileUtils.EvaluateSystemVariables(DefaultFtpSiteLogsFolder); // Create site folder. if (!FileUtils.DirectoryExists(folder)) { FileUtils.CreateDirectory(folder); } // Create logs folder. if (!FileUtils.DirectoryExists(logsDirectory)) { FileUtils.CreateDirectory(logsDirectory); } site = new FtpSite(); site.Name = this.SiteId; site.SiteId = this.SiteId; site.ContentPath = DefaultFtpSiteFolder; site.Bindings = new ServerBinding[1]; // set default log directory site.LogFileDirectory = DefaultFtpSiteLogsFolder; // set default logging fields site[FtpSite.MSFTP7_LOG_EXT_FILE_FIELDS] = DEFAULT_LOG_EXT_FILE_FIELDS; if (!String.IsNullOrEmpty(this.SharedIP)) { site.Bindings[0] = new ServerBinding(this.SharedIP, "21", String.Empty); } else { site.Bindings[0] = new ServerBinding("*", "21", "*"); //// Get information on local server. //IPHostEntry localServerHostEntry = Dns.GetHostEntry(Dns.GetHostName()); //foreach (IPAddress address in localServerHostEntry.AddressList) //{ // if (address.AddressFamily == AddressFamily.InterNetwork) // { // site.Bindings[0] = new ServerBinding(address.ToString(), "21", String.Empty); // } //} } if (this.IsFtpServerBindingsInUse(site)) { messages.Add("Cannot create ftp site because requested bindings are already in use."); return(messages.ToArray()); } try { SecurityUtils.EnsureOrganizationalUnitsExist(ServerSettings, UsersOU, GroupsOU); } catch (Exception ex) { messages.Add(String.Format("Could not check/create Organizational Units: {0}", ex.Message)); return(messages.ToArray()); } // create folder if it not exists if (String.IsNullOrEmpty(SiteId)) { messages.Add("Please, select FTP site to create accounts on"); } else { // create FTP group name if (String.IsNullOrEmpty(FtpGroupName)) { messages.Add("FTP Group can not be blank"); } else { try { // create group if (!SecurityUtils.GroupExists(FtpGroupName, ServerSettings, GroupsOU)) { SystemGroup group = new SystemGroup(); group.Name = FtpGroupName; group.Members = new string[] { }; group.Description = "WebsitePanel System Group"; SecurityUtils.CreateGroup(group, ServerSettings, UsersOU, GroupsOU); } } catch (Exception ex) { messages.Add(String.Format("There was an error while adding '{0}' group: {1}", FtpGroupName, ex.Message)); return(messages.ToArray()); } } if (!this.ftpSitesService.SiteExists(this.SiteId)) { this.CreateSite(site); } else { this.UpdateSite(site); } try { // set permissions on the site root SecurityUtils.GrantNtfsPermissions(site.ContentPath, FtpGroupName, NTFSPermission.Read, true, true, ServerSettings, UsersOU, GroupsOU); } catch (Exception ex) { messages.Add(String.Format("Can not set permissions on '{0}' folder: {1}", site.ContentPath, ex.Message)); return(messages.ToArray()); } } return(messages.ToArray()); }
IDisposable StartImpersonation2(ref MessageRpc rpc, ServiceSecurityContext securityContext, bool isSecurityContextImpersonationOn) { IDisposable impersonationContext = null; try { if (isSecurityContextImpersonationOn) { if (securityContext == null) { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SFxSecurityContextPropertyMissingFromRequestMessage)), rpc.Request); } WindowsIdentity impersonationToken = securityContext.WindowsIdentity; if (impersonationToken.User != null) { impersonationContext = impersonationToken.Impersonate(); } else if (securityContext.PrimaryIdentity is WindowsSidIdentity) { WindowsSidIdentity sidIdentity = (WindowsSidIdentity)securityContext.PrimaryIdentity; if (sidIdentity.SecurityIdentifier.IsWellKnown(WellKnownSidType.AnonymousSid)) { impersonationContext = new WindowsAnonymousIdentity().Impersonate(); } else { string fullyQualifiedDomainName = GetUpnFromDownlevelName(sidIdentity.Name); using (WindowsIdentity windowsIdentity = new WindowsIdentity(fullyQualifiedDomainName, SecurityUtils.AuthTypeKerberos)) { impersonationContext = windowsIdentity.Impersonate(); } } } else { throw TraceUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.SecurityContextDoesNotAllowImpersonation, rpc.Operation.Action)), rpc.Request); } } else if (AspNetEnvironment.Current.RequiresImpersonation) { if (rpc.HostingProperty != null) { impersonationContext = rpc.HostingProperty.Impersonate(); } } SecurityTraceRecordHelper.TraceImpersonationSucceeded(rpc.EventTraceActivity, rpc.Operation); // update the impersonation succeed audit if (AuditLevel.Success == (this.auditLevel & AuditLevel.Success)) { SecurityAuditHelper.WriteImpersonationSuccessEvent(this.auditLogLocation, this.suppressAuditFailure, rpc.Operation.Name, SecurityUtils.GetIdentityNamesFromContext(securityContext.AuthorizationContext)); } } catch (Exception ex) { if (Fx.IsFatal(ex)) { throw; } SecurityTraceRecordHelper.TraceImpersonationFailed(rpc.EventTraceActivity, rpc.Operation, ex); // // Update the impersonation failure audit // Copy SecurityAuthorizationBehavior.Audit level to here!!! // if (AuditLevel.Failure == (this.auditLevel & AuditLevel.Failure)) { try { string primaryIdentity; if (securityContext != null) { primaryIdentity = SecurityUtils.GetIdentityNamesFromContext(securityContext.AuthorizationContext); } else { primaryIdentity = SecurityUtils.AnonymousIdentity.Name; } SecurityAuditHelper.WriteImpersonationFailureEvent(this.auditLogLocation, this.suppressAuditFailure, rpc.Operation.Name, primaryIdentity, ex); } #pragma warning suppress 56500 catch (Exception auditException) { if (Fx.IsFatal(auditException)) { throw; } DiagnosticUtility.TraceHandledException(auditException, TraceEventType.Error); } } throw; } return(impersonationContext); }
/// <devdoc> /// This adds the delegate value as a listener to when this event is fired /// by the component, invoking the addOnXXX method. /// </devdoc> public override void AddEventHandler(object component, Delegate value) { FillMethods(); if (component != null) { ISite site = GetSite(component); IComponentChangeService changeService = null; // Announce that we are about to change this component // if (site != null) { changeService = (IComponentChangeService)site.GetService(typeof(IComponentChangeService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || changeService != null, "IComponentChangeService not found"); } if (changeService != null) { try { changeService.OnComponentChanging(component, this); } catch (CheckoutException coEx) { if (coEx == CheckoutException.Canceled) { return; } throw coEx; } } bool shadowed = false; if (site != null && site.DesignMode) { // Events are final, so just check the class if (EventType != value.GetType()) { throw new ArgumentException(SR.GetString(SR.ErrorInvalidEventHandler, Name)); } IDictionaryService dict = (IDictionaryService)site.GetService(typeof(IDictionaryService)); Debug.Assert(!CompModSwitches.CommonDesignerServices.Enabled || dict != null, "IDictionaryService not found"); if (dict != null) { Delegate eventdesc = (Delegate)dict.GetValue(this); eventdesc = Delegate.Combine(eventdesc, value); dict.SetValue(this, eventdesc); shadowed = true; } } if (!shadowed) { SecurityUtils.MethodInfoInvoke(addMethod, component, new object[] { value }); } // Now notify the change service that the change was successful. // if (changeService != null) { changeService.OnComponentChanged(component, this, null, value); } } }
public SecurityContextSecurityToken(UniqueId contextId, byte[] key, DateTime validFrom, DateTime validTo) : this(contextId, SecurityUtils.GenerateId(), key, validFrom, validTo) { }
private void Encrypt(string key, string filename, string outfile) { new Thread(() => { IsRunning = true; int tmp = 0, pro = 0; long total = 0; long finished = 0; try { SaveThumbnail(filename); FileStream fsr = new FileStream(filename, FileMode.Open); FileStream fout = new FileStream(outfile, FileMode.OpenOrCreate); total = fsr.Length; if (OnStart != null) { OnStart(total); } byte[] readBytes = new byte[HttpServer.BufferSize]; int len = 0; while ((len = fsr.Read(readBytes, 0, readBytes.Length)) != 0) { finished += len; if (IsStopped) { Logger.Warn("用户取消加密进程"); break; } if (len < HttpServer.BufferSize) { byte[] rest = new byte[len]; Array.Copy(readBytes, rest, len); byte[] en = SecurityUtils.AesEncrypt(key, rest); fout.Write(en, 0, en.Length); } else { byte[] en = SecurityUtils.AesEncrypt(key, readBytes); fout.Write(en, 0, en.Length); } // tmp = (int)(finished * 100 / total); if (pro < tmp) { pro = tmp; if (OnProgress != null) { OnProgress(pro); } } } fsr.Close(); fout.Close(); } catch (Exception ex) { if (OnError != null) { OnError(ex.Message); } } IsRunning = false; if (OnFinished != null) { OnFinished(); } }).Start(); }
public byte[] GetNonce() { return(SecurityUtils.CloneBuffer(_nonce)); }
public byte[] GetKeyBytes() { return(SecurityUtils.CloneBuffer(_key)); }
internal InstallationContext(Installation installation, RSA keyPairClient) : this(installation.SessionToken.Token, keyPairClient, SecurityUtils.CreatePublicKeyFromPublicKeyFormattedString(installation.GetPublicKeyServerString())) { }
public byte[] GetBuffer() { return(SecurityUtils.CloneBuffer(_identificationData)); }
public override SecurityTokenProvider CreateSecurityTokenProvider(SecurityTokenRequirement tokenRequirement) { if (tokenRequirement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenRequirement"); } SecurityTokenProvider result = null; if (tokenRequirement is RecipientServiceModelSecurityTokenRequirement && tokenRequirement.TokenType == SecurityTokenTypes.X509Certificate && tokenRequirement.KeyUsage == SecurityKeyUsage.Exchange) { // this is the uncorrelated duplex case if (_parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate, _parent.ClientCertificate.CloneCertificate); } else if (tokenRequirement is InitiatorServiceModelSecurityTokenRequirement) { InitiatorServiceModelSecurityTokenRequirement initiatorRequirement = tokenRequirement as InitiatorServiceModelSecurityTokenRequirement; string tokenType = initiatorRequirement.TokenType; if (IsIssuedSecurityTokenRequirement(initiatorRequirement)) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider (IsIssuedSecurityTokenRequirement(initiatorRequirement)"); } else if (tokenType == SecurityTokenTypes.X509Certificate) { if (initiatorRequirement.Properties.ContainsKey(SecurityTokenRequirement.KeyUsageProperty) && initiatorRequirement.KeyUsage == SecurityKeyUsage.Exchange) { throw ExceptionHelper.PlatformNotSupported("CreateSecurityTokenProvider X509Certificate - SecurityKeyUsage.Exchange"); } else { if (_parent.ClientCertificate.Certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.Format(SR.ClientCertificateNotProvidedOnClientCredentials))); } result = new X509SecurityTokenProvider(_parent.ClientCertificate.Certificate, _parent.ClientCertificate.CloneCertificate); } } else if (tokenType == SecurityTokenTypes.Kerberos) { string spn = GetServicePrincipalName(initiatorRequirement); result = new KerberosSecurityTokenProviderWrapper( new KerberosSecurityTokenProvider(spn, _parent.Windows.AllowedImpersonationLevel, SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential))); } else if (tokenType == SecurityTokenTypes.UserName) { if (_parent.UserName.UserName == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.UserNamePasswordNotProvidedOnClientCredentials)); } result = new UserNameSecurityTokenProvider(_parent.UserName.UserName, _parent.UserName.Password); } else if (tokenType == ServiceModelSecurityTokenTypes.SspiCredential) { if (IsDigestAuthenticationScheme(initiatorRequirement)) { result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.HttpDigest.ClientCredential), true, TokenImpersonationLevel.Delegation); } else { #pragma warning disable 618 // to disable AllowNtlm obsolete wanring. result = new SspiSecurityTokenProvider(SecurityUtils.GetNetworkCredentialOrDefault(_parent.Windows.ClientCredential), _parent.Windows.AllowNtlm, _parent.Windows.AllowedImpersonationLevel); #pragma warning restore 618 } } } if ((result == null) && !tokenRequirement.IsOptionalToken) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.Format(SR.SecurityTokenManagerCannotCreateProviderForRequirement, tokenRequirement))); } return(result); }
public override string ToString() { return(SecurityUtils.ClaimSetToString(this)); }
internal static object GetRuntimeObject(string className, Type baseType, string initializeData) { object obj2 = null; Type c = null; if (className.Length == 0) { throw new ConfigurationErrorsException(System.SR.GetString("EmptyTypeName_NotAllowed")); } c = Type.GetType(className); if (c == null) { throw new ConfigurationErrorsException(System.SR.GetString("Could_not_find_type", new object[] { className })); } if (!baseType.IsAssignableFrom(c)) { throw new ConfigurationErrorsException(System.SR.GetString("Incorrect_base_type", new object[] { className, baseType.FullName })); } Exception inner = null; try { if (string.IsNullOrEmpty(initializeData)) { if (IsOwnedTL(c)) { throw new ConfigurationErrorsException(System.SR.GetString("TL_InitializeData_NotSpecified")); } ConstructorInfo constructor = c.GetConstructor(new Type[0]); if (constructor == null) { throw new ConfigurationErrorsException(System.SR.GetString("Could_not_get_constructor", new object[] { className })); } obj2 = SecurityUtils.ConstructorInfoInvoke(constructor, new object[0]); } else { ConstructorInfo ctor = c.GetConstructor(new Type[] { typeof(string) }); if (ctor != null) { if ((IsOwnedTextWriterTL(c) && (initializeData[0] != Path.DirectorySeparatorChar)) && ((initializeData[0] != Path.AltDirectorySeparatorChar) && !Path.IsPathRooted(initializeData))) { string configFilePath = DiagnosticsConfiguration.ConfigFilePath; if (!string.IsNullOrEmpty(configFilePath)) { string directoryName = Path.GetDirectoryName(configFilePath); if (directoryName != null) { initializeData = Path.Combine(directoryName, initializeData); } } } obj2 = SecurityUtils.ConstructorInfoInvoke(ctor, new object[] { initializeData }); } else { ConstructorInfo[] constructors = c.GetConstructors(); if (constructors == null) { throw new ConfigurationErrorsException(System.SR.GetString("Could_not_get_constructor", new object[] { className })); } for (int i = 0; i < constructors.Length; i++) { ParameterInfo[] parameters = constructors[i].GetParameters(); if (parameters.Length == 1) { Type parameterType = parameters[0].ParameterType; try { object obj3 = ConvertToBaseTypeOrEnum(initializeData, parameterType); obj2 = SecurityUtils.ConstructorInfoInvoke(constructors[i], new object[] { obj3 }); goto Label_0223; } catch (TargetInvocationException exception2) { inner = exception2.InnerException; } catch (Exception exception3) { inner = exception3; } } } } } } catch (TargetInvocationException exception4) { inner = exception4.InnerException; } Label_0223: if (obj2 != null) { return(obj2); } if (inner != null) { throw new ConfigurationErrorsException(System.SR.GetString("Could_not_create_type_instance", new object[] { className }), inner); } throw new ConfigurationErrorsException(System.SR.GetString("Could_not_create_type_instance", new object[] { className })); }
protected override void ProcessRecord() { X509Certificate2 certFromPfxFile = null; string[] filePath = this.FilePath; for (int i = 0; i < (int)filePath.Length; i++) { string str = filePath[i]; List <string> strs = new List <string>(); if (!this.isLiteralPath) { try { foreach (PathInfo resolvedPSPathFromPSPath in base.SessionState.Path.GetResolvedPSPathFromPSPath(str)) { strs.Add(resolvedPSPathFromPSPath.ProviderPath); } } catch (ItemNotFoundException itemNotFoundException) { this.filesNotFound.Add(str); } } else { strs.Add(base.SessionState.Path.GetUnresolvedProviderPathFromPSPath(str)); } foreach (string str1 in strs) { string filePathOfExistingFile = SecurityUtils.GetFilePathOfExistingFile(this, str1); if (filePathOfExistingFile != null) { try { certFromPfxFile = GetPfxCertificateCommand.GetCertFromPfxFile(filePathOfExistingFile); } catch (CryptographicException cryptographicException2) { string getPfxCertPasswordPrompt = CertificateCommands.GetPfxCertPasswordPrompt; SecureString secureString = SecurityUtils.PromptForSecureString(base.Host.UI, getPfxCertPasswordPrompt); try { certFromPfxFile = GetPfxCertificateCommand.GetCertFromPfxFile(filePathOfExistingFile, secureString); } catch (CryptographicException cryptographicException1) { CryptographicException cryptographicException = cryptographicException1; ErrorRecord errorRecord = new ErrorRecord(cryptographicException, "GetPfxCertificateUnknownCryptoError", ErrorCategory.NotSpecified, null); base.WriteError(errorRecord); continue; } } base.WriteObject(certFromPfxFile); } else { this.filesNotFound.Add(str); } } } if (this.filesNotFound.Count > 0) { if (this.filesNotFound.Count != (int)this.FilePath.Length) { foreach (string str2 in this.filesNotFound) { object[] objArray = new object[1]; objArray[0] = str2; ErrorRecord errorRecord1 = SecurityUtils.CreateFileNotFoundErrorRecord(CertificateCommands.FileNotFound, "GetPfxCertCommandFileNotFound", objArray); base.WriteError(errorRecord1); } } else { ErrorRecord errorRecord2 = SecurityUtils.CreateFileNotFoundErrorRecord(CertificateCommands.NoneOfTheFilesFound, "GetPfxCertCommandNoneOfTheFilesFound", new object[0]); base.ThrowTerminatingError(errorRecord2); return; } } }
public void SetFolderNtfsPermissions(string fullPath, UserPermission[] permissions, bool isProtected, bool preserveInheritance) { Log.WriteStart("SetFolderNtfsPermissions"); Log.WriteInfo("Full path : {0}", fullPath); try { if (preserveInheritance == false && permissions != null) { // 06.09.2015 [email protected] // In German the Group 'Domain-Admins' is called 'Domänen-Admins' // So we try to get the correct Group by SID var domainAdminsAsString = SecurityUtils.GetAccountNameFromSid( System.Security.Principal.WellKnownSidType.AccountDomainAdminsSid, ServerSettings); // Add Current User (Normally WPServer Acccount) var currentUserName = Environment.UserName; if (permissions.All(x => !string.Equals(x.AccountName, currentUserName, StringComparison.InvariantCultureIgnoreCase))) { permissions = permissions.Concat(new[] { new UserPermission { AccountName = currentUserName, Read = true, Write = true } }).ToArray(); } if (permissions.All(x => !string.Equals(x.AccountName, domainAdminsAsString, StringComparison.InvariantCultureIgnoreCase))) { permissions = permissions.Concat(new[] { new UserPermission { AccountName = domainAdminsAsString, Read = true, Write = true } }).ToArray(); } if (permissions.All(x => !string.Equals(x.AccountName, "System", StringComparison.InvariantCultureIgnoreCase))) { permissions = permissions.Concat(new[] { new UserPermission { AccountName = "System", Read = true, Write = true } }).ToArray(); } } SecurityUtils.ResetNtfsPermissions(fullPath); // 06.09.2015 [email protected] // Problem: Serversettings for the Method 'GrantGroupNtfsPermission' is an Default Object, but we need the real Object // for the real Settings, to determine Objects from AD // Fix: Give the Helper-Class SecurityUtils the real ServerSettings-Object // SecurityUtils.GrantGroupNtfsPermissions(fullPath, permissions, false, new RemoteServerSettings(), null, null, isProtected, preserveInheritance); SecurityUtils.GrantGroupNtfsPermissions(fullPath, permissions, false, ServerSettings, "*", "*", isProtected, preserveInheritance); } catch (Exception ex) { Log.WriteError(ex); throw; } finally { Log.WriteEnd("SetFolderNtfsPermissions"); } }
public override void Validate(X509Certificate2 certificate) { if (certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(certificate)); } X509Chain chain = new X509Chain(); if (chainPolicy != null) { chain.ChainPolicy = chainPolicy; } if (!chain.Build(certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.Format(SR.X509ChainBuildFail, SecurityUtils.GetCertificateId(certificate), GetChainStatusInformation(chain.ChainStatus)))); } }
/// <summary> /// Processes records from the input pipeline. /// For each input file, the command retrieves its /// corresponding certificate. /// </summary> protected override void ProcessRecord() { // // this cannot happen as we have specified the Path // property to be a mandatory parameter // Dbg.Assert((FilePath != null) && (FilePath.Length > 0), "GetCertificateCommand: Param binder did not bind path"); X509Certificate2 cert = null; foreach (string p in FilePath) { List <string> paths = new List <string>(); // Expand wildcard characters if (_isLiteralPath) { paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } else { try { foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) { paths.Add(tempPath.ProviderPath); } } catch (ItemNotFoundException) { _filesNotFound.Add(p); } } foreach (string resolvedPath in paths) { string resolvedProviderPath = SecurityUtils.GetFilePathOfExistingFile(this, resolvedPath); if (resolvedProviderPath == null) { _filesNotFound.Add(p); } else { try { cert = GetCertFromPfxFile(resolvedProviderPath); } catch (CryptographicException) { // // CryptographicException is thrown when any error // occurs inside the crypto class library. It has a // protected member HResult that indicates the exact // error but it is not available outside the class. // Thus we have to assume that the above exception // was thrown because the pfx file is password // protected. // SecureString password = null; string prompt = null; prompt = CertificateCommands.GetPfxCertPasswordPrompt; password = SecurityUtils.PromptForSecureString(Host.UI, prompt); try { cert = GetCertFromPfxFile(resolvedProviderPath, password); } catch (CryptographicException e) { // // since we cannot really figure out the // meaning of a given CryptographicException // we have to use NotSpecified category here // ErrorRecord er = new ErrorRecord(e, "GetPfxCertificateUnknownCryptoError", ErrorCategory.NotSpecified, null); WriteError(er); continue; } } WriteObject(cert); } } } if (_filesNotFound.Count > 0) { if (_filesNotFound.Count == FilePath.Length) { ErrorRecord er = SecurityUtils.CreateFileNotFoundErrorRecord( CertificateCommands.NoneOfTheFilesFound, "GetPfxCertCommandNoneOfTheFilesFound"); ThrowTerminatingError(er); } else { // // we found some files but not others. // Write error for each missing file // foreach (string f in _filesNotFound) { ErrorRecord er = SecurityUtils.CreateFileNotFoundErrorRecord( CertificateCommands.FileNotFound, "GetPfxCertCommandFileNotFound", f ); WriteError(er); } } } }
public ActionResult ForgottenPassword(ForgottenPasswordModel model) { bool status = true; string exMsg = ""; if (ModelState.IsValid) { SystemSettingsRepository sysRepo = new SystemSettingsRepository(); var sys = sysRepo.GetSystemSettings(); using (DBEntities db = new DBEntities()) { var playerDashboard = db.PlayerDashboard.FirstOrDefault(u => u.DashboardURL == model.DashboardURLId); PlayersRepository playerRepo = new PlayersRepository(); var player = playerRepo.ReadOne_ByEmailAddress(model.Email); if (playerDashboard != null && player != null) { //Now Send an Email to User for Username and Password! // if (sys.EmailsEnabled) { try { //Random rndm = new Random(); //var RandomNum = rndm.Next(10001, int.MaxValue); Guid guid = Guid.NewGuid(); string EncryptedRandomNum = guid.ToString(); SecurityUtils.CheckforInvalidFileNameChar(ref EncryptedRandomNum); //it will remove any unsupported characters playerDashboard.PasswordResetCode = EncryptedRandomNum; playerDashboard.ResetCodeExpiry = DateTime.Now.AddHours(24); db.SaveChanges(); status = SendEmail(player, EncryptedRandomNum, sys.CurrentDomain); } catch (Exception ex) { ViewBag.status = "Failed to send an Email. Please contact your Site Administrator" + ex.Message; exMsg = ex.Message; } if (status) { //Add To Log SecurityUtils.AddAuditLog("Requested for Forgotten Password", "User \"" + player.FullName + "\" requested for Forgotten Password , Email Sent to: \"" + player.EmailAddress + "\"", this); ViewBag.status = "Your Login Details has been sent to above email address. <a style='color:black' href='/Member/Login/" + model.DashboardURLId + "'> Log In </a>"; } else { ViewBag.status = "Failed to send an Email. Please contact your Site Administrator." + exMsg + " - " + EmailsRepository.EmailErrorMsg; } } } else { ViewBag.status = "Your provided email address is not valid. Please contact us at [email protected]"; } } } ViewBag.ModelIsLogin = true; return(View()); }
/// <summary> /// Processes records from the input pipeline. /// For each input object, the command gets or /// sets the digital signature on the object, and /// and exports the object. /// </summary> protected override void ProcessRecord() { if (Content == null) { // // this cannot happen as we have specified the Path // property to be mandatory parameter // Dbg.Assert((FilePath != null) && (FilePath.Length > 0), "GetSignatureCommand: Param binder did not bind path"); foreach (string p in FilePath) { Collection <string> paths = new Collection <string>(); // Expand wildcard characters if (_isLiteralPath) { paths.Add(SessionState.Path.GetUnresolvedProviderPathFromPSPath(p)); } else { try { foreach (PathInfo tempPath in SessionState.Path.GetResolvedPSPathFromPSPath(p)) { paths.Add(tempPath.ProviderPath); } } catch (ItemNotFoundException) { WriteError( SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, "SignatureCommandsBaseFileNotFound", p)); } } if (paths.Count == 0) { continue; } bool foundFile = false; foreach (string path in paths) { if (!System.IO.Directory.Exists(path)) { foundFile = true; string resolvedFilePath = SecurityUtils.GetFilePathOfExistingFile(this, path); if (resolvedFilePath == null) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.FileNotFound, "SignatureCommandsBaseFileNotFound", path)); } else { if ((Signature = PerformAction(resolvedFilePath)) != null) { WriteObject(Signature); } } } } if (!foundFile) { WriteError(SecurityUtils.CreateFileNotFoundErrorRecord( SignatureCommands.CannotRetrieveFromContainer, "SignatureCommandsBaseCannotRetrieveFromContainer")); } } } else { foreach (string sourcePathOrExtension in SourcePathOrExtension) { if ((Signature = PerformAction(sourcePathOrExtension, Content)) != null) { WriteObject(Signature); } } } }
public override string ToString() { return(_disposed ? base.ToString() : SecurityUtils.ClaimSetToString(this)); }
public void Test_timeClaims() { Assert.IsTrue(SecurityUtils.compareStrings(expected, payload)); }
protected ISubject GetSubject() { return(SecurityUtils.GetSubject()); }
public override void Validate(X509Certificate2 certificate) { if (certificate == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull(nameof(certificate)); } // implies _useMachineContext = false // ctor for X509Chain(_useMachineContext, _chainPolicyOID) not present in CoreCLR X509Chain chain = new X509Chain(); if (_chainPolicy != null) { _chainPolicy.VerificationTime = DateTime.Now; chain.ChainPolicy = _chainPolicy; } if (!chain.Build(certificate)) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new SecurityTokenValidationException(SR.Format(SR.X509ChainBuildFail, SecurityUtils.GetCertificateId(certificate), GetChainStatusInformation(chain.ChainStatus)))); } }
SecurityTokenProvider CreateSecureConversationSecurityTokenProvider(InitiatorServiceModelSecurityTokenRequirement initiatorRequirement) { EndpointAddress targetAddress = initiatorRequirement.TargetAddress; if (targetAddress == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenRequirementDoesNotSpecifyTargetAddress, initiatorRequirement)); } SecurityBindingElement securityBindingElement = initiatorRequirement.SecurityBindingElement; if (securityBindingElement == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgument(SR.GetString(SR.TokenProviderRequiresSecurityBindingElement, initiatorRequirement)); } LocalClientSecuritySettings localClientSettings = securityBindingElement.LocalClientSettings; BindingContext issuerBindingContext = initiatorRequirement.GetProperty <BindingContext>(ServiceModelSecurityTokenRequirement.IssuerBindingContextProperty); ChannelParameterCollection channelParameters = initiatorRequirement.GetPropertyOrDefault <ChannelParameterCollection>(ServiceModelSecurityTokenRequirement.ChannelParametersCollectionProperty, null); bool isSessionMode = initiatorRequirement.SupportSecurityContextCancellation; if (isSessionMode) { SecuritySessionSecurityTokenProvider sessionTokenProvider = new SecuritySessionSecurityTokenProvider(GetCredentialsHandle(initiatorRequirement)); sessionTokenProvider.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(initiatorRequirement); sessionTokenProvider.IssuedSecurityTokenParameters = initiatorRequirement.GetProperty <SecurityTokenParameters>(ServiceModelSecurityTokenRequirement.IssuedSecurityTokenParametersProperty); sessionTokenProvider.IssuerBindingContext = issuerBindingContext; sessionTokenProvider.KeyEntropyMode = securityBindingElement.KeyEntropyMode; sessionTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite; sessionTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this); sessionTokenProvider.TargetAddress = targetAddress; sessionTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault <Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null); Uri privacyNoticeUri; if (initiatorRequirement.TryGetProperty <Uri>(ServiceModelSecurityTokenRequirement.PrivacyNoticeUriProperty, out privacyNoticeUri)) { sessionTokenProvider.PrivacyNoticeUri = privacyNoticeUri; } int privacyNoticeVersion; if (initiatorRequirement.TryGetProperty <int>(ServiceModelSecurityTokenRequirement.PrivacyNoticeVersionProperty, out privacyNoticeVersion)) { sessionTokenProvider.PrivacyNoticeVersion = privacyNoticeVersion; } EndpointAddress localAddress; if (initiatorRequirement.TryGetProperty <EndpointAddress>(ServiceModelSecurityTokenRequirement.DuplexClientLocalAddressProperty, out localAddress)) { sessionTokenProvider.LocalAddress = localAddress; } sessionTokenProvider.ChannelParameters = channelParameters; sessionTokenProvider.WebHeaders = initiatorRequirement.WebHeaders; return(sessionTokenProvider); } else { AcceleratedTokenProvider acceleratedTokenProvider = new AcceleratedTokenProvider(GetCredentialsHandle(initiatorRequirement)); acceleratedTokenProvider.IssuerAddress = initiatorRequirement.IssuerAddress; acceleratedTokenProvider.BootstrapSecurityBindingElement = SecurityUtils.GetIssuerSecurityBindingElement(initiatorRequirement); acceleratedTokenProvider.CacheServiceTokens = localClientSettings.CacheCookies; acceleratedTokenProvider.IssuerBindingContext = issuerBindingContext; acceleratedTokenProvider.KeyEntropyMode = securityBindingElement.KeyEntropyMode; acceleratedTokenProvider.MaxServiceTokenCachingTime = localClientSettings.MaxCookieCachingTime; acceleratedTokenProvider.SecurityAlgorithmSuite = initiatorRequirement.SecurityAlgorithmSuite; acceleratedTokenProvider.ServiceTokenValidityThresholdPercentage = localClientSettings.CookieRenewalThresholdPercentage; acceleratedTokenProvider.StandardsManager = SecurityUtils.CreateSecurityStandardsManager(initiatorRequirement, this); acceleratedTokenProvider.TargetAddress = targetAddress; acceleratedTokenProvider.Via = initiatorRequirement.GetPropertyOrDefault <Uri>(InitiatorServiceModelSecurityTokenRequirement.ViaProperty, null); Uri privacyNoticeUri; if (initiatorRequirement.TryGetProperty <Uri>(ServiceModelSecurityTokenRequirement.PrivacyNoticeUriProperty, out privacyNoticeUri)) { acceleratedTokenProvider.PrivacyNoticeUri = privacyNoticeUri; } acceleratedTokenProvider.ChannelParameters = channelParameters; int privacyNoticeVersion; if (initiatorRequirement.TryGetProperty <int>(ServiceModelSecurityTokenRequirement.PrivacyNoticeVersionProperty, out privacyNoticeVersion)) { acceleratedTokenProvider.PrivacyNoticeVersion = privacyNoticeVersion; } return(acceleratedTokenProvider); } }