// Token: 0x060002B8 RID: 696 RVA: 0x000124F4 File Offset: 0x000106F4 private void Application_PostAuthenticate(object source, EventArgs e) { HttpApplication httpApplication = (HttpApplication)source; HttpContext context = httpApplication.Context; Uri url = context.Request.Url; if (!context.Request.IsAuthenticated && !ExternalAuthentication.GetCurrent().Enabled&& (Common.IsWsSecurityAddress(url) || Common.IsWsSecuritySymmetricKeyAddress(url) || Common.IsWsSecurityX509CertAddress(url))) { context.Response.Close(); httpApplication.CompleteRequest(); return; } uint processCpuSlowDownThreshold = CPUBasedSleeper.ProcessCpuSlowDownThreshold; if (!context.Request.IsAuthenticated) { processCpuSlowDownThreshold = AutodiscoverThrottlingModule.anonymousSlowdownCpuThreshold; } int arg; float arg2; if (CPUBasedSleeper.SleepIfNecessary(processCpuSlowDownThreshold, out arg, out arg2)) { ExTraceGlobals.FrameworkTracer.TraceDebug <int, float>((long)this.GetHashCode(), "[AutodiscoverThrottlingModule::Application_PostAuthenticate] Slept request for {0} msec due to current process CPU percent of {1}%", arg, arg2); } }
private void ValidateForEnterprise(IRMConfiguration config) { if (config.ExternalLicensingEnabled && !ExternalAuthentication.GetCurrent().Enabled) { base.WriteError(new OrganizationNotFederatedException(), ErrorCategory.InvalidOperation, base.Identity); } if (config.InternalLicensingEnabled) { Uri rmsserviceLocation = RmsClientManager.GetRMSServiceLocation(OrganizationId.ForestWideOrgId, ServiceType.Certification); if (rmsserviceLocation == null) { base.WriteError(new NoRMSServersFoundException(), ErrorCategory.InvalidOperation, base.Identity); } this.ValidateRmsVersion(rmsserviceLocation, ServiceType.CertificationService); this.ValidateRmsVersion(rmsserviceLocation, ServiceType.LicensingService); } if (!MultiValuedPropertyBase.IsNullOrEmpty(config.LicensingLocation)) { foreach (Uri uri in config.LicensingLocation) { if (string.IsNullOrEmpty(RMUtil.ConvertUriToLicenseUrl(uri))) { base.WriteError(new RmsUrlIsInvalidException(uri), ErrorCategory.InvalidOperation, base.Identity); } this.ValidateRmsVersion(uri, ServiceType.LicensingService); } } }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { //services.AddDbContext<ApplicationDbContext>(options => // options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddDbContext <ApplicationDbContext>(options => options.UseSqlite(Configuration.GetConnectionString("SQLite"))); services.AddIdentity <ApplicationUser, IdentityRole>() .AddEntityFrameworkStores <ApplicationDbContext>() .AddDefaultTokenProviders(); // Add application services. services.AddTransient <IEmailSender, EmailSender>(); services.AddScoped <IToDoItemService, ToDoItemService>(); services.AddMvc(); services .AddAuthentication() .AddFacebook(o => { var opt = ExternalAuthentication .GetAuthentication(Configuration, "Facebook"); o.AppId = opt.AppId; o.AppSecret = opt.AppSecret; }) .AddGoogle(o => { var opt = ExternalAuthentication .GetAuthentication(Configuration, "Google"); o.ClientId = opt.AppId; o.ClientSecret = opt.AppSecret; }); }
public static ExternalAuthentication CreateExternalAuthentication() { var authentication = new ExternalAuthentication(); authentication.Issuer = CreateRandomString(8); authentication.SetToBase64Token(CreateRandomString(8, _extendedChars)); return authentication; }
public SharedFolderDataEncryption(ExternalAuthentication externalAuthentication) { if (!externalAuthentication.Enabled) { SharedFolderDataEncryption.Tracer.TraceError <SharedFolderDataEncryption>((long)this.GetHashCode(), "{0}: The organization is not federated.", this); throw new OrganizationNotFederatedException(); } this.externalAuthentication = externalAuthentication; }
public ExternalAuthenticationRequest(RequestLogger requestLogger, ExternalAuthentication externalAuthentication, ADUser user, SmtpAddress emailAddress, TokenTarget target, Offer offer) { this.requestLogger = requestLogger; this.user = user; this.emailAddress = emailAddress; this.target = target; this.offer = offer; this.securityTokenService = externalAuthentication.GetSecurityTokenService(user.OrganizationId); }
/// <summary> /// Delete the external authentication /// </summary> /// <param name="externalAuthenticationRecord">External authentication</param> public virtual async Task DeleteExternalAuthentication(ExternalAuthentication externalAuthentication) { if (externalAuthentication == null) { throw new ArgumentNullException(nameof(externalAuthentication)); } await _externalAuthenticationRecordRepository.DeleteAsync(externalAuthentication); }
private static SharingEngine Create(MailboxSession mailboxSession, StoreId sharingFolderId) { ADUser aduser = SharingEngine.GetADUser(mailboxSession); SharingSubscriptionData subscriptionData = SharingEngine.GetSubscriptionData(mailboxSession, (StoreObjectId)sharingFolderId); SharingEngine.Tracer.TraceDebug <IExchangePrincipal, SharingSubscriptionData>(0L, "{0}: Found subscription data: {1}", mailboxSession.MailboxOwner, subscriptionData); ExternalAuthentication externalAuthentication = SharingEngine.GetExternalAuthentication(mailboxSession); return(new SharingEngine(mailboxSession.Culture, mailboxSession.MailboxOwner, sharingFolderId, subscriptionData, externalAuthentication, aduser)); }
protected virtual bool TryGetSecurityTokenService(OrganizationId organizationId, out SecurityTokenService securityTokenService) { securityTokenService = null; ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (current.Enabled) { securityTokenService = current.GetSecurityTokenService(organizationId); } return(securityTokenService != null); }
private static ExternalAuthentication GetExternalAuthentication(MailboxSession mailboxSession) { ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (!current.Enabled) { SharingEngine.Tracer.TraceError <IExchangePrincipal>(0L, "{0}: The organization is not federated.", mailboxSession.MailboxOwner); throw new OrganizationNotFederatedException(); } return(current); }
public SamlSecurityTokenProvider(SamlClientCredentials samlCredentials) { if (samlCredentials == null) { throw new ArgumentNullException("samlCredentials"); } this.identity = samlCredentials.Identity; this.targetUri = samlCredentials.TargetUri; this.offer = samlCredentials.Offer; this.latencyTracker = (samlCredentials.RmsLatencyTracker ?? NoopRmsLatencyTracker.Instance); this.securityTokenService = ExternalAuthentication.GetCurrent().GetSecurityTokenService(samlCredentials.OrganizationId); }
public IEstablishedClientChannelBuilder WithExternalAuthentication(string token, string issuer) { Guard.Argument(token, nameof(token)).NotNull(); var authentication = new ExternalAuthentication { Token = token, Issuer = issuer }; return(WithAuthentication(authentication)); }
public FederatedClientCredentials GetFederatedCredentialsForDelegation(ExternalAuthentication extAuth) { this.UpdateCrossPremiseStatus(); if ((!this.isArchiveCrossPremise || !this.isCrossPremiseArchiveEnabled) && !this.isMailboxCrossPremise) { throw new InvalidOperationException("This is not an enabled remote mailbox."); } if (this.xropTokenRequest == null) { throw new InvalidOperationException("We shouldn't be requesting DelegationTokenRequest for misconfigured remote mailbox properties."); } FedOrgCredentials organizationCredentials = new FedOrgCredentials(this.xropTokenRequest, extAuth.GetSecurityTokenService(this.adUser.OrganizationId)); return(new FederatedClientCredentials(this.xropUserFederatedIdentity, this.xropUserEmailAddress, organizationCredentials)); }
private SecurityTokenService GetSecurityTokenService(OrganizationId organizationId) { if (this.securityTokenService == null) { ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (current.Enabled) { this.securityTokenService = current.GetSecurityTokenService(organizationId); if (this.securityTokenService == null) { throw new AutoDAccessException(ServerStrings.AutoDFailedToGetToken); } } } return(this.securityTokenService); }
/// <summary> /// Accociate external account with customer /// </summary> /// <param name="customer">Customer</param> /// <param name="parameters">External authentication parameters</param> public virtual async Task AssociateCustomer(Customer customer, ExternalAuthParam parameters) { if (customer == null) { throw new ArgumentNullException(nameof(customer)); } var externalAuthenticationRecord = new ExternalAuthentication { CustomerId = customer.Id, Email = parameters.Email, ExternalIdentifier = parameters.Identifier, ExternalDisplayIdentifier = parameters.Name, OAuthAccessToken = parameters.AccessToken, ProviderSystemName = parameters.ProviderSystemName, }; await _externalAuthenticationRecordRepository.InsertAsync(externalAuthenticationRecord); }
public async Task <ExternalAuthentication> GetAsync(ulong discordUserId, ExternalService service) { var userId = (long)discordUserId; var dbExternalAuth = await _botContext.ExternalAuthentication .Where(ea => ea.User.DiscordUserId == userId) .FirstOrDefaultAsync(ea => ea.Service == service).ConfigureAwait(false); if (dbExternalAuth == null) { return(null); } var auth = new ExternalAuthentication { AccessToken = _aes.Decrypt(dbExternalAuth.AccessTokenAes), TokenType = _aes.Decrypt(dbExternalAuth.TokenTypeAes), Scope = _aes.Decrypt(dbExternalAuth.ScopeAes), RefreshToken = _aes.Decrypt(dbExternalAuth.RefreshTokenAes), ExpiresIn = int.Parse(_aes.Decrypt(dbExternalAuth.ExpiresInAes)) }; if (dbExternalAuth.LastRefreshed + TimeSpan.FromSeconds(auth.ExpiresIn - 60) > DateTime.UtcNow) { return(auth); } // Get New Token var newToken = await UpdateAsync(auth.RefreshToken, service).ConfigureAwait(false); // Update DB dbExternalAuth.AccessTokenAes = _aes.Encrypt(newToken.AccessToken); dbExternalAuth.ExpiresInAes = _aes.Encrypt(newToken.ExpiresIn.ToString()); dbExternalAuth.LastRefreshed = DateTime.UtcNow; await _botContext.SaveChangesAsync().ConfigureAwait(false); // Update return object auth.AccessToken = newToken.AccessToken; auth.ExpiresIn = newToken.ExpiresIn; return(auth); }
private Authentication GetAuthenticationScheme() { Authentication result = null; if (IsGuest(Identifier)) { result = new GuestAuthentication(); } if (Password != null) { result = new PlainAuthentication() { Password = Password }; } if (AccessKey != null) { result = new KeyAuthentication { Key = AccessKey }; } if (Token != null && Issuer != null) { result = new ExternalAuthentication { Token = Token, Issuer = Issuer }; } if (result == null) { throw new InvalidOperationException( $"A password or accessKey should be defined. Please use the '{nameof(UsingPassword)}' or '{nameof(UsingAccessKey)}' methods for that."); } return(result); }
public async Task AddAsync(ulong discordUserId, ExternalService service, ExternalAuthentication authentication) { if (await GetAsync(discordUserId, service).ConfigureAwait(false) != null) { throw new InvalidOperationException($"The user {discordUserId} is already linked to the service {service}"); } var userId = (long)discordUserId; var user = await _botContext.Users.FirstOrDefaultAsync(u => u.DiscordUserId == userId).ConfigureAwait(false); _botContext.ExternalAuthentication.Add(new SQL.Models.ExternalAuthentication { User = user, Service = service, AccessTokenAes = _aes.Encrypt(authentication.AccessToken), TokenTypeAes = _aes.Encrypt(authentication.TokenType), ScopeAes = _aes.Encrypt(authentication.Scope), RefreshTokenAes = _aes.Encrypt(authentication.RefreshToken), ExpiresInAes = _aes.Encrypt(authentication.ExpiresIn.ToString()), LastRefreshed = DateTime.UtcNow }); await _botContext.SaveChangesAsync().ConfigureAwait(false); }
protected override object CreateBehavior() { object obj = base.CreateBehavior(); ServiceCredentials serviceCredentials = obj as ServiceCredentials; if (serviceCredentials == null) { ExTraceGlobals.AuthenticationTracer.TraceDebug <string>((long)this.GetHashCode(), "Not adding Exchange certificates to ServiceCredentials. Behavior is not a ServiceCredentials - instead, it is of type {0}", obj.GetType().FullName); return(obj); } if (serviceCredentials.IssuedTokenAuthentication == null) { ExTraceGlobals.AuthenticationTracer.TraceDebug((long)this.GetHashCode(), "Not adding Exchange certificates to ServiceCredentials. ServiceCredentials.IssuedTokenAuthentication is null"); return(obj); } if (serviceCredentials.IssuedTokenAuthentication.KnownCertificates == null) { ExTraceGlobals.AuthenticationTracer.TraceDebug((long)this.GetHashCode(), "Not adding Exchange certificates to ServiceCredentials. ServiceCredentials.IssuedTokenAuthentication.KnownCertificates is null"); return(obj); } ExternalAuthentication current = ExternalAuthentication.GetCurrent(); ApplicationPoolRecycler.EnableOnFederationTrustCertificateChange(); if (!current.Enabled) { ExTraceGlobals.AuthenticationTracer.TraceDebug((long)this.GetHashCode(), "Not adding Exchange certificates to ServiceCredentials. ExternalAuthentication.Enabled is false"); return(obj); } serviceCredentials.IssuedTokenAuthentication.AllowedAudienceUris.Add(current.TokenValidator.TargetUri.OriginalString); foreach (X509Certificate2 x509Certificate in current.Certificates) { ExTraceGlobals.AuthenticationTracer.TraceDebug <X509Certificate2>((long)this.GetHashCode(), "Adding Exchange certificate to ServiceCredentials: {0}", x509Certificate); serviceCredentials.IssuedTokenAuthentication.KnownCertificates.Add(x509Certificate); } return(obj); }
// Token: 0x06000284 RID: 644 RVA: 0x000115F4 File Offset: 0x0000F7F4 private static bool CheckClaimSetsForExternalUser(AuthorizationContext authorizationContext, OperationContext operationContext) { HttpContext.Current.Items["AuthType"] = "External"; SamlSecurityToken samlSecurityToken = null; foreach (SupportingTokenSpecification supportingTokenSpecification in operationContext.SupportingTokens) { samlSecurityToken = (supportingTokenSpecification.SecurityToken as SamlSecurityToken); if (samlSecurityToken != null) { break; } } if (samlSecurityToken == null) { ExTraceGlobals.AuthenticationTracer.TraceError(0L, "Found no security token in authorization context"); return(AutodiscoverAuthorizationManager.Return401UnauthorizedResponse(operationContext, "Cannot find security token in authorization context")); } ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (!current.Enabled) { ExTraceGlobals.AuthenticationTracer.TraceError(0L, "Federation is not enabled"); return(AutodiscoverAuthorizationManager.Return401UnauthorizedResponse(operationContext, "Federation is not enabled")); } TokenValidationResults tokenValidationResults = current.TokenValidator.ValidateToken(samlSecurityToken, Offer.Autodiscover); if (tokenValidationResults.Result != TokenValidationResult.Valid || !SmtpAddress.IsValidSmtpAddress(tokenValidationResults.EmailAddress)) { ExTraceGlobals.AuthenticationTracer.TraceError <TokenValidationResults>(0L, "Validation of security token in WS-Security header failed: {0}", tokenValidationResults); return(AutodiscoverAuthorizationManager.Return401UnauthorizedResponse(operationContext, "Validation of the delegation failed")); } SmtpAddress smtpAddress = SmtpAddress.Empty; int num = -1; try { num = operationContext.IncomingMessageHeaders.FindHeader("SharingSecurity", "http://schemas.microsoft.com/exchange/services/2006/types"); } catch (MessageHeaderException ex) { AutodiscoverAuthorizationManager.Return401UnauthorizedResponse(operationContext, "Exception when looking for SharingSecurity header in request: " + ex.ToString()); return(false); } if (num < 0) { ExTraceGlobals.AuthenticationTracer.TraceDebug(0L, "Request has no SharingSecurity header"); } else { XmlElement header = operationContext.IncomingMessageHeaders.GetHeader <XmlElement>(num); smtpAddress = SharingKeyHandler.Decrypt(header, tokenValidationResults.ProofToken); if (smtpAddress == SmtpAddress.Empty) { ExTraceGlobals.AuthenticationTracer.TraceError <string>(0L, "SharingSecurity is present but invalid: {0}", header.OuterXml); AutodiscoverAuthorizationManager.Return401UnauthorizedResponse(operationContext, "Validation of the SharingSecurity failed"); return(false); } ExTraceGlobals.AuthenticationTracer.TraceDebug <SmtpAddress>(0L, "SharingSecurity header contains external identity: {0}", smtpAddress); } AutodiscoverAuthorizationManager.PushUserAndOrgInfoToContext(tokenValidationResults.EmailAddress, null); HttpContext.Current.User = new GenericPrincipal(new ExternalIdentity(new SmtpAddress(tokenValidationResults.EmailAddress), smtpAddress), null); return(true); }
private SharedFolderData GetMatchingSharedFolderData(SharingContext context, ADRecipient mailboxOwner) { SharedFolderDataEncryption sharedFolderDataEncryption = new SharedFolderDataEncryption(ExternalAuthentication.GetCurrent()); bool flag = false; ExTraceGlobals.SharingTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "{0}: Decrypting the encrypted shared folder data.", mailboxOwner); foreach (EncryptedSharedFolderData encryptedSharedFolderData in context.EncryptedSharedFolderDataCollection) { SharedFolderData sharedFolderData = sharedFolderDataEncryption.TryDecrypt(encryptedSharedFolderData); if (sharedFolderData != null) { if (SharingProviderHandlerExternal.TryFindMatchingRecipient(sharedFolderData, mailboxOwner) != null) { ExTraceGlobals.SharingTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "{0}: Get the decrypted shared folder data.", mailboxOwner); return(sharedFolderData); } flag = true; } } ExTraceGlobals.SharingTracer.TraceError <ADRecipient>((long)this.GetHashCode(), "{0}: Failed to decrypt shared folder data.", mailboxOwner); if (flag) { throw new InvalidExternalSharingSubscriberException(); } throw new InvalidSharingDataException("SharedFolderData", string.Empty); }
protected virtual bool IsExternalAuthenticationEnabled() { return(ExternalAuthentication.GetCurrent().Enabled); }
protected override PerformInvitationResults InternalPerformInvitation(MailboxSession mailboxSession, SharingContext context, ValidRecipient[] recipients, IFrontEndLocator frontEndLocator) { ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (!current.Enabled) { ExTraceGlobals.SharingTracer.TraceError <string>((long)this.GetHashCode(), "{0}: The organization is not federated for external sharing.", context.InitiatorSmtpAddress); return(new PerformInvitationResults(new InvalidSharingRecipientsException(ValidRecipient.ConvertToStringArray(recipients), new OrganizationNotFederatedException()))); } SharedFolderDataEncryption sharedFolderDataEncryption = new SharedFolderDataEncryption(current); string text = StoreId.StoreIdToEwsId(mailboxSession.MailboxOwner.MailboxInfo.MailboxGuid, context.FolderId); PerformInvitationResults result; using (ExternalUserCollection externalUsers = mailboxSession.GetExternalUsers()) { PerformInvitationResults performInvitationResults = null; EncryptionResults encryptionResults = null; Exception ex = null; try { encryptionResults = sharedFolderDataEncryption.Encrypt(mailboxSession.MailboxOwner, mailboxSession.GetADRecipientSession(true, ConsistencyMode.IgnoreInvalid), externalUsers, recipients, context.InitiatorSmtpAddress, context.FolderClass, text, frontEndLocator); } catch (UserWithoutFederatedProxyAddressException ex2) { ex = ex2; } catch (InvalidFederatedOrganizationIdException ex3) { ex = ex3; } catch (StoragePermanentException ex4) { ex = ex4; } if (ex != null) { ExTraceGlobals.SharingTracer.TraceError <string, Exception>((long)this.GetHashCode(), "{0}: Error occurred when trying to encrypt. Exception = {1}", context.InitiatorSmtpAddress, ex); result = new PerformInvitationResults(new InvalidSharingRecipientsException(ValidRecipient.ConvertToStringArray(recipients), ex)); } else { if (encryptionResults.InvalidRecipients != null && encryptionResults.InvalidRecipients.Length > 0) { InvalidSharingRecipientsException exception = new InvalidSharingRecipientsException(encryptionResults.InvalidRecipients); if (encryptionResults.InvalidRecipients.Length == recipients.Length) { return(new PerformInvitationResults(exception)); } performInvitationResults = new PerformInvitationResults(recipients, exception); recipients = performInvitationResults.SucceededRecipients; } else { performInvitationResults = new PerformInvitationResults(recipients); } PermissionLevel permissionLevel = this.GetPermissionLevel(context); FreeBusyAccess? freeBusy = this.GetFreeBusy(context); using (FolderPermissionContext current2 = FolderPermissionContext.GetCurrent(mailboxSession, context)) { foreach (ValidRecipient validRecipient in recipients) { PermissionSecurityPrincipal principal = this.CreatePermissionSecurityPrincipal(validRecipient.SmtpAddress, externalUsers); current2.AddOrChangePermission(principal, permissionLevel, freeBusy); ExternalUser externalUser = externalUsers.FindReachUserWithOriginalSmtpAddress(new SmtpAddress(validRecipient.SmtpAddress)); if (externalUser != null) { current2.RemovePermission(new PermissionSecurityPrincipal(externalUser)); } } } context.FolderEwsId = text; context.EncryptedSharedFolderDataCollection = encryptionResults.EncryptedSharedFolderDataCollection; result = performInvitationResults; } } return(result); }
private SharingPolicyDomain GetEffectiveCalendarSharingPolicy(string recipientDomain, IFrontEndLocator frontEndLocator) { SharingPolicyDomain sharingPolicyDomain = null; SharingPolicyDomain sharingPolicyDomain2 = null; bool enabled = ExternalAuthentication.GetCurrent().Enabled; bool flag = false; this.TraceDebug("External authentication enabled:{0}", new object[] { enabled }); foreach (SharingPolicyDomain sharingPolicyDomain3 in this.SharingPolicy.Domains) { if (enabled) { if (StringComparer.OrdinalIgnoreCase.Equals(sharingPolicyDomain3.Domain, recipientDomain)) { this.TraceDebug("Found exact policy for domain {0}", new object[] { sharingPolicyDomain3.Domain }); sharingPolicyDomain = sharingPolicyDomain3; } else if (sharingPolicyDomain == null && StringComparer.OrdinalIgnoreCase.Equals(sharingPolicyDomain3.Domain, "*")) { this.TraceDebug("Found asterisk policy", new object[0]); sharingPolicyDomain = sharingPolicyDomain3; flag = true; } } if (StringComparer.OrdinalIgnoreCase.Equals(sharingPolicyDomain3.Domain, "Anonymous")) { if (OwaAnonymousVdirLocater.Instance.IsPublishingAvailable(this.mailboxOwner, frontEndLocator)) { this.TraceDebug("Found anonymous policy", new object[0]); sharingPolicyDomain2 = sharingPolicyDomain3; } else { this.TraceDebug("Found anonymous policy but publishing is not allowed", new object[0]); } } } if (flag && sharingPolicyDomain2 != null && PolicyAllowedDetailLevel.GetMaxAllowed(sharingPolicyDomain.Actions) <= PolicyAllowedDetailLevel.GetMaxAllowed(sharingPolicyDomain2.Actions)) { this.TraceDebug("Override AsteriskPolicy with anonymous policy", new object[0]); sharingPolicyDomain = null; } if (sharingPolicyDomain != null) { if (TargetUriResolver.Resolve(recipientDomain, this.mailboxOwner.MailboxInfo.OrganizationId) != null) { return(sharingPolicyDomain); } this.TraceDebug("Target domain '{0}' is not federated", new object[] { recipientDomain }); } return(sharingPolicyDomain2); }
private SharingEngine(CultureInfo culture, IExchangePrincipal exchangePrincipal, StoreId sharingFolderId, SharingSubscriptionData subscription, ExternalAuthentication externalAuthentication, ADUser adUser) { this.Culture = culture; this.MailboxOwner = exchangePrincipal; this.SharingFolderId = sharingFolderId; this.subscription = subscription; this.externalAuthentication = externalAuthentication; this.adUser = adUser; this.StartTime = DateTime.UtcNow; }
private async Task<string> ExternalAuthenticationSignIn(Uri requestUri, Uri redirectUri, ExternalAuthentication authenticationType) { var browser = Page.FindName("oauthBrowser") as WebBrowser; if (browser == null) return null; oauthBrowserWaiter = new AutoResetEvent(false); string responseUrl = null; EventHandler<NavigatingEventArgs> navigating = (sender, e) => { var url = e.Uri.ToString(); if ((authenticationType == ExternalAuthentication.OAuth && url.StartsWith(redirectUri.ToString())) || (authenticationType == ExternalAuthentication.Acs && url.Contains("#!/SignInWithToken/"))) { responseUrl = url.ToString(); e.Cancel = true; oauthBrowserWaiter.Set(); } }; NavigationFailedEventHandler failed = (sender, e) => oauthBrowserWaiter.Set(); browser.NavigationFailed += failed; browser.Navigating += navigating; try { browser.IsScriptEnabled = true; browser.Visibility = Visibility.Visible; browser.Navigate(requestUri); await Task.Factory.StartNew(() => oauthBrowserWaiter.WaitOne()); } catch { } finally { browser.Navigating -= navigating; browser.NavigationFailed -= failed; browser.Visibility = Visibility.Collapsed; oauthBrowserWaiter = null; } return responseUrl; }
internal override AutodiscoverResponseMessage Execute() { GetFederationInformationResponseMessage getFederationInformationResponseMessage = new GetFederationInformationResponseMessage(); GetFederationInformationResponse response = getFederationInformationResponseMessage.Response; if (this.Request == null || this.Request.Domain == null || !SmtpAddress.IsValidDomain(this.Request.Domain)) { response.ErrorCode = ErrorCode.InvalidRequest; response.ErrorMessage = Strings.InvalidRequest; } else { ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (!current.Enabled) { response.ErrorCode = ErrorCode.NotFederated; response.ErrorMessage = Strings.NotFederated; } else { IEnumerable <string> enumerable = null; OrganizationId organizationId = DomainToOrganizationIdCache.Singleton.Get(new SmtpDomain(this.Request.Domain)); if (organizationId != null) { OrganizationIdCacheValue organizationIdCacheValue = OrganizationIdCache.Singleton.Get(organizationId); enumerable = organizationIdCacheValue.FederatedDomains; } else { try { string text = MserveDomainCache.Singleton.Get(this.Request.Domain); if (!string.IsNullOrEmpty(text)) { AutodiscoverAuthorizationManager.BuildRedirectUrlAndRedirectCaller(OperationContext.Current, text); return(null); } } catch (OverBudgetException arg) { ExTraceGlobals.FrameworkTracer.TraceError <OverBudgetException>(0L, "GetFederationInformationRequestMessage.Execute() returning ServerBusy for exception: {0}.", arg); response.ErrorCode = ErrorCode.ServerBusy; response.ErrorMessage = Strings.ServerBusy; return(getFederationInformationResponseMessage); } } if (enumerable == null) { response.ErrorCode = ErrorCode.InvalidDomain; response.ErrorMessage = Strings.InvalidDomain; } else { List <TokenIssuer> list = new List <TokenIssuer>(2); SecurityTokenService securityTokenService = current.GetSecurityTokenService(organizationId); if (securityTokenService != null) { list.Add(new TokenIssuer(securityTokenService.TokenIssuerUri, securityTokenService.TokenIssuerEndpoint)); } response.ErrorCode = ErrorCode.NoError; response.ApplicationUri = current.ApplicationUri; response.Domains = new DomainCollection(enumerable); response.TokenIssuers = new TokenIssuerCollection(list); } } } return(getFederationInformationResponseMessage); }
// Token: 0x060003D2 RID: 978 RVA: 0x000159C4 File Offset: 0x00013BC4 internal string FindAddressFromWsSecurity(Stream stream, WsSecurityHeaderType headerType, out bool isDelegationToken) { isDelegationToken = false; long position = stream.Position; try { XmlReader xmlReader = XmlReader.Create(stream); if (xmlReader.Settings != null && xmlReader.Settings.DtdProcessing != DtdProcessing.Prohibit) { xmlReader.Settings.DtdProcessing = DtdProcessing.Prohibit; } XmlElement xmlElement = null; XmlElement xmlElement2 = null; XmlElement xmlElement3 = null; xmlReader.MoveToContent(); bool flag = true; while (flag && xmlReader.Read()) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Header") { if (!(xmlReader.NamespaceURI == "http://schemas.xmlsoap.org/soap/envelope/")) { if (!(xmlReader.NamespaceURI == "http://www.w3.org/2003/05/soap-envelope")) { continue; } } while (flag && xmlReader.Read()) { if (stream.Position > 73628L) { throw new QuotaExceededException(); } if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == "Header" && (xmlReader.NamespaceURI == "http://schemas.xmlsoap.org/soap/envelope/" || xmlReader.NamespaceURI == "http://www.w3.org/2003/05/soap-envelope")) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; Hit the end of the SOAP header unexpectedly", this.TraceContext); } flag = false; break; } if (headerType != WsSecurityHeaderType.PartnerAuth) { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Security" && xmlReader.NamespaceURI == "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") { while (flag) { if (!xmlReader.Read()) { break; } if (stream.Position > 73628L) { throw new QuotaExceededException(); } if (xmlReader.NodeType == XmlNodeType.EndElement && xmlReader.LocalName == "Security" && xmlReader.NamespaceURI == "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd") { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; Hit the end of the WS-Security header unexpectedly", this.TraceContext); } flag = false; break; } if (xmlReader.NodeType == XmlNodeType.Element && ((headerType == WsSecurityHeaderType.WSSecurityAuth && xmlReader.LocalName == "EncryptedData" && xmlReader.NamespaceURI == "http://www.w3.org/2001/04/xmlenc#") || (headerType == WsSecurityHeaderType.X509CertAuth && xmlReader.LocalName == "BinarySecurityToken" && xmlReader.NamespaceURI == "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"))) { using (XmlReader xmlReader2 = xmlReader.ReadSubtree()) { XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(xmlReader2); xmlElement = xmlDocument.DocumentElement; } flag = false; break; } } } } else { if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "ExchangeImpersonation" && xmlReader.NamespaceURI == "http://schemas.microsoft.com/exchange/services/2006/types") { using (XmlReader xmlReader3 = xmlReader.ReadSubtree()) { XmlDocument xmlDocument2 = new XmlDocument(); xmlDocument2.Load(xmlReader3); xmlElement2 = xmlDocument2.DocumentElement; } flag = false; break; } if (xmlReader.NodeType == XmlNodeType.Element && xmlReader.LocalName == "Attribute" && xmlReader.NamespaceURI == "urn:oasis:names:tc:SAML:1.0:assertion" && xmlReader.HasAttributes && xmlReader.GetAttribute("AttributeName") == "targettenant") { using (XmlReader xmlReader4 = xmlReader.ReadSubtree()) { XmlDocument xmlDocument3 = new XmlDocument(); xmlDocument3.Load(xmlReader4); xmlElement3 = xmlDocument3.DocumentElement; } flag = false; break; } } } } } if (headerType == WsSecurityHeaderType.PartnerAuth) { if (xmlElement2 != null) { if (xmlElement2.NodeType == XmlNodeType.Element && xmlElement2.FirstChild.NodeType == XmlNodeType.Element && xmlElement2.FirstChild.LocalName == "ConnectingSID") { XmlNode firstChild = xmlElement2.FirstChild.FirstChild; if (firstChild.LocalName == "PrincipalName" || firstChild.LocalName == "PrimarySmtpAddress" || firstChild.LocalName == "SmtpAddress" || firstChild.LocalName == "SID") { return(firstChild.InnerXml); } if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int, string>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; Unexpected type {1} in ConnectingSID in impersonation header", this.TraceContext, firstChild.Name); } return(null); } } else if (xmlElement3 != null && xmlElement3.NodeType == XmlNodeType.Element && xmlElement3.FirstChild.LocalName == "AttributeValue") { return(xmlElement3.FirstChild.InnerText); } } else if (xmlElement != null) { ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (!current.Enabled) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: ExternalAuthentication is not enabled"); } return(null); } if (headerType == WsSecurityHeaderType.X509CertAuth) { AuthorizationContext authorizationContext; if (current.TokenValidator.AuthorizationContextFromToken(xmlElement, ref authorizationContext).Result == null) { ReadOnlyCollection <ClaimSet> claimSets = authorizationContext.ClaimSets; X509CertUser x509CertUser = null; if (!X509CertUser.TryCreateX509CertUser(claimSets, ref x509CertUser)) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; Unable to create the x509certuser", this.TraceContext); } return(null); } OrganizationId organizationId; WindowsIdentity windowsIdentity; string text; if (!x509CertUser.TryGetWindowsIdentity(ref organizationId, ref windowsIdentity, ref text)) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int, X509CertUser, string>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; unable to find the windows identity for cert user: {1}, reason: {2}", this.TraceContext, x509CertUser, text); } return(null); } return(x509CertUser.UserPrincipalName); } } else { TokenValidationResults tokenValidationResults = current.TokenValidator.FindEmailAddress(xmlElement, ref isDelegationToken); if (!string.IsNullOrEmpty(tokenValidationResults.EmailAddress)) { return(tokenValidationResults.EmailAddress); } } } } catch (XmlException ex) { if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int, XmlException>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; XmlException {1}", this.TraceContext, ex); } } if (ExTraceGlobals.VerboseTracer.IsTraceEnabled(1)) { ExTraceGlobals.VerboseTracer.TraceDebug <int>((long)this.GetHashCode(), "[WsSecurityParser::FindAddressFromWsSecurity]: Context {0}; No email address found in Ws-Trust token", this.TraceContext); } return(null); }
protected override void InternalProcessRecord() { TaskLogger.LogEnter(); base.InternalProcessRecord(); ITopologyConfigurationSession topologyConfigurationSession = DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, ADSessionSettings.FromRootOrgScopeSet(), 66, "InternalProcessRecord", "f:\\15.00.1497\\sources\\dev\\Management\\src\\Management\\SystemConfigurationTasks\\Federation\\GetFederationInformation.cs"); string[] autodiscoverTrustedHosters = topologyConfigurationSession.GetAutodiscoverTrustedHosters(); using (AutodiscoverClient autodiscoverClient = new AutodiscoverClient()) { Server localServer = LocalServerCache.LocalServer; if (localServer != null && localServer.InternetWebProxy != null) { base.WriteVerbose(Strings.GetFederationInformationProxy(localServer.InternetWebProxy.ToString())); autodiscoverClient.Proxy = new WebProxy(localServer.InternetWebProxy); } if (this.TrustedHostnames != null) { autodiscoverClient.AllowedHostnames.AddRange(this.TrustedHostnames); } if (autodiscoverTrustedHosters != null) { autodiscoverClient.AllowedHostnames.AddRange(autodiscoverTrustedHosters); } base.WriteVerbose(Strings.GetFederationInformationTrustedHostnames(autodiscoverClient.AllowedHostnames.ToString())); base.WriteProgress(Strings.GetFederationInformationProgress, Strings.DiscoveringDomain(this.DomainName.Domain), 5); List <GetFederationInformationResult> list = new List <GetFederationInformationResult>(GetFederationInformationClient.Discover(autodiscoverClient, this.DomainName.Domain)); base.WriteProgress(Strings.GetFederationInformationProgress, Strings.DiscoveringDomain(this.DomainName.Domain), 25); base.WriteVerbose(Strings.GetFederationInformationResults(GetFederationInformation.GetFormattedResults(list))); GetFederationInformationResult result = this.GetResult(list); if (result == null) { base.WriteError(new GetFederationInformationFailedException(list.ToArray()), (ErrorCategory)1001, null); } else { ICollection domainNames; if (this.BypassAdditionalDomainValidation) { domainNames = result.Domains; } else { domainNames = this.GetValidatedAdditionalDomains(autodiscoverClient, result.ApplicationUri, result.Domains); } if (result.TokenIssuerUris != null && result.TokenIssuerUris.Length > 0) { bool flag = false; Uri[] array = Array.ConvertAll <string, Uri>(result.TokenIssuerUris, (string uri) => new Uri(uri, UriKind.RelativeOrAbsolute)); ExternalAuthentication current = ExternalAuthentication.GetCurrent(); if (current.Enabled) { foreach (SecurityTokenService securityTokenService in current.SecurityTokenServices) { Uri tokenIssuerUri = securityTokenService.TokenIssuerUri; foreach (Uri uri2 in array) { if (tokenIssuerUri.Equals(uri2)) { base.WriteVerbose(Strings.GetFederationInformationTokenIssuerMatches(tokenIssuerUri.ToString(), uri2.ToString())); flag = true; break; } base.WriteVerbose(Strings.GetFederationInformationTokenIssuerDoesntMatch(tokenIssuerUri.ToString(), uri2.ToString())); } } if (!flag) { StringBuilder stringBuilder = new StringBuilder(100); foreach (SecurityTokenService securityTokenService2 in current.SecurityTokenServices) { if (stringBuilder.Length > 0) { stringBuilder.Append(","); } stringBuilder.Append(securityTokenService2.TokenIssuerUri.ToString()); } this.WriteWarning(Strings.GetFederationInformationTokenIssuerDoesntMatchAny(this.DomainName.ToString(), string.Join(",", result.TokenIssuerUris), stringBuilder.ToString())); } } } base.WriteObject(new FederationInformation(this.DomainName, new Uri(result.ApplicationUri, UriKind.RelativeOrAbsolute), result.TokenIssuerUris, domainNames, EwsWsSecurityUrl.Fix(result.Url))); } base.WriteProgress(Strings.GetFederationInformationProgress, Strings.ProgressStatusFinished, 100); } TaskLogger.LogExit(); }