Ejemplo n.º 1
0
        /// <summary>
        /// Handles the click event on the logon button.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private void _logonButton_Click(object sender, EventArgs e)
        {
            // Get the user provider.
            var userProvider = this.Container.Resolve <IUserProvider>();

            // Get the principal object for the current user.
            IPrincipal principal;

            try
            {
                principal = userProvider.Logon(this._loginTextBox.Text, this._passwordTextBox.Text);
            }
            catch (SecurityException)
            {
                return;
            }

            // Create the sign in request.
            var signInRequestMessage =
                (SignInRequestMessage)WSFederationMessage.CreateFromUri(this.Request.Url);

            // Create the security token service.
            var securityTokenService =
                new SecurityTokenService(new SecurityTokenServiceConfiguration());

            // Send the sign request to the security token service and get a sign in response.
            var signInResponseMessage =
                FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                    signInRequestMessage, principal, securityTokenService);

            // Redirect based on the sign in response.
            FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(
                signInResponseMessage, this.Response);
        }
Ejemplo n.º 2
0
        private RequestedToken GetDelegationToken(ADUser user, Uri target, SecurityTokenService securityTokenService)
        {
            RequestedToken result;

            try
            {
                DelegationTokenRequest request = new DelegationTokenRequest
                {
                    FederatedIdentity = user.GetFederatedIdentity(),
                    EmailAddress      = user.GetFederatedSmtpAddress().ToString(),
                    Target            = new TokenTarget(target),
                    Offer             = TestFederationTrust.TokenOffer
                };
                RequestedToken requestedToken = securityTokenService.IssueToken(request);
                this.Log(EventTypeEnumeration.Success, TestFederationTrust.TestFederationTrustEventId.TokenRequest, Strings.DelegationTokenRequestSuccess);
                result = requestedToken;
            }
            catch (LocalizedException ex)
            {
                this.Log(EventTypeEnumeration.Error, TestFederationTrust.TestFederationTrustEventId.TokenRequest, Strings.TokenRequestFailed);
                base.WriteVerbose(Strings.FailureAndReason(Strings.TokenRequestFailed.ToString(), ex.ToString()));
                result = null;
            }
            return(result);
        }
Ejemplo n.º 3
0
        private async Task <ItemResponse <Guid> > SendNewConfirmationEmail(string firstName, string lastName, string email, string id)
        {
            SecurityTokenAddRequest securityToken = new SecurityTokenAddRequest();

            securityToken.FirstName    = firstName;
            securityToken.LastName     = lastName;
            securityToken.Email        = email;
            securityToken.TokenTypeId  = 1;
            securityToken.AspNetUserId = id;

            Guid emailSecurityToken = SecurityTokenService.Insert(securityToken);

            ConfirmationEmailRequest emailRequest = new ConfirmationEmailRequest();

            emailRequest.FirstName     = firstName;
            emailRequest.LastName      = lastName;
            emailRequest.Email         = email;
            emailRequest.SecurityToken = emailSecurityToken;
            //Removed static to enable DI
            await _emailService.ConfirmRegistration(emailRequest);

            ItemResponse <Guid> response = new ItemResponse <Guid>();

            response.Item = emailSecurityToken;
            return(response);
        }
Ejemplo n.º 4
0
        public HttpResponseMessage ConfirmToken(String userId, Guid guid)
        {
            SecurityToken securityToken = SecurityTokenService.SelectByGuid(guid);

            if (securityToken.AspNetUserId != null && securityToken.AspNetUserId == userId)
            {
                DateTime now         = DateTime.UtcNow;
                TimeSpan daysElapsed = (now - securityToken.DateCreated);
                if (daysElapsed.TotalDays > 1)
                {
                    String        errorMessage = "1|Not activated in 24 hours";
                    ErrorResponse response     = new ErrorResponse(errorMessage);
                    return(Request.CreateResponse(HttpStatusCode.NotAcceptable, response));
                }
                else
                {
                    UserService.ConfirmEmail(securityToken.AspNetUserId);
                    if (!PersonService.CheckIfPerson(securityToken.AspNetUserId))
                    {
                        PersonAddRequest person = new PersonAddRequest();
                        person.Email        = securityToken.Email;
                        person.AspNetUserId = securityToken.AspNetUserId;
                        int id = PersonService.Insert(person);
                    }
                    SuccessResponse response = new SuccessResponse();
                    return(Request.CreateResponse(HttpStatusCode.OK, response));
                }
            }
            else
            {
                String        errorMessage = "2|Confirm failed";
                ErrorResponse response     = new ErrorResponse(errorMessage);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, response));
            }
        }
Ejemplo n.º 5
0
        public HttpResponseMessage ConfirmResetToken(Guid guid)
        {
            SecurityToken securityToken = SecurityTokenService.SelectByGuid(guid);

            if (securityToken.AspNetUserId != null)
            {
                DateTime now         = DateTime.UtcNow;
                TimeSpan daysElapsed = (now - securityToken.DateCreated);
                if (daysElapsed.TotalDays > 1)
                {
                    String        errorMessage = "1|Not activated in 24 hours";
                    ErrorResponse response     = new ErrorResponse(errorMessage);
                    return(Request.CreateResponse(HttpStatusCode.NotAcceptable, response));
                }
                else
                {
                    ItemResponse <SecurityToken> response = new ItemResponse <SecurityToken>();
                    response.Item = securityToken;
                    return(Request.CreateResponse(HttpStatusCode.OK, response));
                }
            }
            else
            {
                String        errorMessage = "2|Confirm failed";
                ErrorResponse response     = new ErrorResponse(errorMessage);
                return(Request.CreateResponse(HttpStatusCode.BadRequest, response));
            }
        }
Ejemplo n.º 6
0
        private async Task <ItemResponse <Guid> > SendResetPasswordEmail(PersonBase pb, ConfirmationEmailRequest model)
        {
            SecurityTokenAddRequest securityToken = new SecurityTokenAddRequest();

            securityToken.FirstName    = pb.FirstName;
            securityToken.LastName     = pb.LastName;
            securityToken.Email        = model.Email;
            securityToken.TokenTypeId  = 2;
            securityToken.AspNetUserId = "";

            Guid emailSecurityToken = SecurityTokenService.Insert(securityToken);

            ConfirmationEmailRequest emailRequest = new ConfirmationEmailRequest();

            emailRequest.FirstName     = pb.FirstName;
            emailRequest.LastName      = pb.LastName;
            emailRequest.Email         = model.Email;
            emailRequest.SecurityToken = emailSecurityToken;

            await _emailService.ForgotPassword(emailRequest);

            ItemResponse <Guid> response = new ItemResponse <Guid>();

            response.Item = emailSecurityToken;
            return(response);
        }
Ejemplo n.º 7
0
        //[Route("{guid:Guid}"), HttpPut]
        //public async Task<HttpResponseMessage> ResendConfirmationEmail(Guid guid)
        //{
        //    SecurityToken securityToken = SecurityTokenService.SelectByGuid(guid);

        //    ItemResponse<Guid> response = await SendNewConfirmationEmail(securityToken.FirstName, securityToken.LastName, securityToken.Email, securityToken.AspNetUserId);

        //    return Request.CreateResponse(HttpStatusCode.OK, response);
        //}

        private async Task <SuccessResponse> SendNewConfirmationEmail(string email, string id)
        {
            SecurityTokenAddRequest securityTokenAddRequest = new SecurityTokenAddRequest();

            securityTokenAddRequest.Email        = email;
            securityTokenAddRequest.AspNetUserId = id;

            SecurityToken securityToken = new SecurityToken();

            securityToken.TokenGuid    = SecurityTokenService.Insert(securityTokenAddRequest);
            securityToken.AspNetUserId = id;

            StringBuilder UrlBuilder = new StringBuilder(ConfigurationManager.AppSettings.Get("BaseUrl"));

            UrlBuilder.Append("/account/confirmemail?id=");
            UrlBuilder.Append(securityToken.AspNetUserId);
            UrlBuilder.Append("&token=");
            UrlBuilder.Append(securityToken.TokenGuid);

            await ExternalEmailService.ConfirmRegistration(UrlBuilder.ToString(), email);

            SuccessResponse response = new SuccessResponse();

            return(response);
        }
Ejemplo n.º 8
0
        public async Task <HttpResponseMessage> ResendConfirmationEmail(Guid guid)
        {
            SecurityToken securityToken = SecurityTokenService.SelectByGuid(guid);

            ItemResponse <Guid> response = await SendNewConfirmationEmail(securityToken.FirstName, securityToken.LastName, securityToken.Email, securityToken.AspNetUserId);

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Ejemplo n.º 9
0
        public HttpResponseMessage ResetPassWord(PasswordResetRequest model)
        {
            SecurityToken securityToken = SecurityTokenService.SelectByGuid(model.Guid);

            UserService.ChangePassWord(securityToken.AspNetUserId, model.Password);
            ItemsResponse <bool> response = new ItemsResponse <bool>();

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Ejemplo n.º 10
0
        public STS(SecurityTokenService sts)
        {
            if (sts == null)
            {
                throw new ArgumentNullException("sts");
            }

            _sts = sts;
        }
Ejemplo n.º 11
0
        public async Task ThrowExceptionWhenNoTokenStoredTest()
        {
            // Arrange
            var securityTokenService = new SecurityTokenService(context);

            // Act
            Func <Task <IList <string> > > act = async() => await securityTokenService.GetSavedData(Guid.NewGuid(), string.Empty);

            // Assert
            await act.Should().ThrowAsync <InvalidOperationException>().WithMessage("Sequence contains no elements");
        }
Ejemplo n.º 12
0
        public async Task <HttpResponseMessage> ResendResetPasswordEmail(Guid guid)
        {
            SecurityToken securityToken = SecurityTokenService.SelectByGuid(guid);

            PersonBase pb = new PersonBase();

            pb.FirstName = securityToken.FirstName;
            pb.LastName  = securityToken.LastName;
            pb.Email     = securityToken.Email;

            ConfirmationEmailRequest r = new ConfirmationEmailRequest();

            r.Email = securityToken.Email;

            ItemResponse <Guid> response = await SendResetPasswordEmail(pb, r);

            return(Request.CreateResponse(HttpStatusCode.OK, response));
        }
Ejemplo n.º 13
0
        public async Task ThrowExceptionWhenTokenDoesNotMatchTest()
        {
            // Arrange
            var userId = Guid.NewGuid();
            var securityTokenService = new SecurityTokenService(context);
            await securityTokenService.SaveDataWithTokenAsync(
                new List <string>
            {
                Guid.NewGuid().ToString(),
                Guid.NewGuid().ToString()
            },
                userId);

            // Act
            Func <Task <IList <string> > > act = async() => await securityTokenService.GetSavedData(userId, string.Empty);

            // Assert
            await act.Should().ThrowAsync <GeneratorException>().WithMessage("User Token doesn't match stored one");
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Inserts a new queued message into the database
        /// </summary>
        /// <param name="queuedMessage">The queued message to insert</param>
        /// <param name="cancellationToken">(Optional) A cancellation token through which the
        /// caller can request cancellation of the insert operation</param>
        /// <returns>Returns a task that completes when the insert operation completes</returns>
        protected virtual async Task InsertQueuedMessage(QueuedMessage queuedMessage, CancellationToken cancellationToken = default(CancellationToken))
        {
            var message       = queuedMessage.Message;
            var principal     = queuedMessage.Principal;
            var expires       = message.Headers.Expires;
            var connection    = ConnectionProvider.GetConnection();
            var securityToken = await SecurityTokenService.NullSafeIssue(principal, expires);

            var persistedMessage = message.WithSecurityToken(securityToken);

            if (MessageEncryptionService != null)
            {
                persistedMessage = await MessageEncryptionService.Encrypt(message);
            }
            try
            {
                var headers        = persistedMessage.Headers;
                var commandBuilder = CommandBuilders.NewInsertQueuedMessageCommandBuilder();
                commandBuilder.MessageId   = headers.MessageId;
                commandBuilder.QueueName   = QueueName;
                commandBuilder.Origination = headers.Origination?.ToString();
                commandBuilder.Destination = headers.Destination?.ToString();
                commandBuilder.ReplyTo     = headers.ReplyTo?.ToString();
                commandBuilder.Expires     = headers.Expires;
                commandBuilder.ContentType = headers.ContentType;
                commandBuilder.Headers     = SerializeHeaders(headers);
                commandBuilder.Content     = persistedMessage.Content;

                using (var scope = new TransactionScope(TransactionScopeOption.Required, TransactionScopeAsyncFlowOption.Enabled))
                {
                    using (var command = commandBuilder.BuildDbCommand(connection))
                    {
                        await command.ExecuteNonQueryAsync(cancellationToken);
                    }
                    scope.Complete();
                }
            }
            finally
            {
                ConnectionProvider.ReleaseConnection(connection);
            }
        }
Ejemplo n.º 15
0
        private async Task <SuccessResponse> SendResetPasswordEmail(String email)
        {
            SecurityTokenAddRequest securityTokenAddRequest = new SecurityTokenAddRequest();

            securityTokenAddRequest.Email        = email;
            securityTokenAddRequest.AspNetUserId = UserService.GetUser(email).Id;

            SecurityToken securityToken = new SecurityToken();

            securityToken.TokenGuid    = SecurityTokenService.Insert(securityTokenAddRequest);
            securityToken.AspNetUserId = UserService.GetUser(email).Id;

            StringBuilder UrlBuilder = new StringBuilder(ConfigurationManager.AppSettings.Get("BaseUrl"));

            UrlBuilder.Append("/account/resetpassword/");
            UrlBuilder.Append(securityToken.TokenGuid);

            await ExternalEmailService.ResetPassword(UrlBuilder.ToString(), email);

            SuccessResponse response = new SuccessResponse();

            return(response);
        }
Ejemplo n.º 16
0
        public int Create(AccountUpsertRequest userModel)
        {
            int    userId = 0;
            string salt;
            string passwordHash;

            string password = userModel.Password;

            salt         = _cryptographyService.GenerateRandomString(RAND_LENGTH);
            passwordHash = _cryptographyService.Hash(password, salt, HASH_ITERATION_COUNT);

            _dataProvider.ExecuteNonQuery("dbo.Person_UpsertAccount",
                                          inputParamMapper : delegate(SqlParameterCollection paramCollection)
            {
                paramCollection.AddWithValue("@Id", userModel.Id);
                paramCollection.AddWithValue("@FirstName", userModel.FirstName);
                paramCollection.AddWithValue("@LastName", userModel.LastName);
                paramCollection.AddWithValue("@Email", userModel.Email);
                paramCollection.AddWithValue("@Salt", salt);
                paramCollection.AddWithValue("@PasswordHash", passwordHash);
                paramCollection.AddWithValue("@RoleId", userModel.RoleId);
                //SqlParameter idParameter = new SqlParameter("@Id", SqlDbType.Int);
                //idParameter.Direction = ParameterDirection.Output;
                //paramCollection.Add(idParameter);
            }
                                          //,
                                          //returnParameters: delegate (SqlParameterCollection param)
                                          //{
                                          //    Int32.TryParse(param["@Id"].Value.ToString(), out userId);
                                          //}
                                          );

            //1)creating token
            SecurityTokenService    sts  = new SecurityTokenService(_dataProvider);
            SecurityTokenAddRequest star = new SecurityTokenAddRequest()
            {
                TokenTypeId = 1,
                UserEmail   = userModel.Email
            };

            System.Guid tokenGuid = sts.Insert(star);
            //2)emailing confirmation
            var source  = SiteConfig.BaseUrl;
            var message =
                "<body style='margin: 0; padding: 0; background:#ccc;'><table cellpadding=0 cellspacing=0 style='width: 100%;'><tr><td style='padding: 12px 2%;'><table cellpadding=0 cellspacing=0 style='margin:auto; background: #fff; width: 96%;'><tr><td style='padding: 12px 2%;'><div><h1 style='color:white;background-color:#1E90FF;'>Youth Mentoring Connection</h1></div > <div><h2 style='margin-top: 0;'>Congratulations</h2><p>You've successfully registered. Please confirm your email with Youth Mentoring Connection.To confirm your email click the link below:<br/></br> <span style='text-align:center; margin:0;'><a href="
                + source + "/confirmationPages?guid="
                + tokenGuid + ">Click Here To Confirm Email</a></p><p>...</p></div><div><h4 style='margin-top: 0;'>Sawubona!</h4><p></p></div><div style='border-top: solid 1px #ccc;'><p></p></div></td ></tr ></table ></td ></tr ></table ></body >";

            ConfirmationEmailService ces = new ConfirmationEmailService();
            ConfirmationEmailRequest cer = new ConfirmationEmailRequest()
            {
                From    = "*****@*****.**",
                To      = userModel.Email,
                Subject = "YMC Confirmation",
                Body    = message
            };
            Task <bool> email = ces.Execute(cer);

            return(userId);
            //DB provider call to create user and get us a user id
            //be sure to store both salt and passwordHash
            //DO NOT STORE the original password value that the user passed us
        }
Ejemplo n.º 17
0
 public WSFederationSecurityTokenService()
     : base()
 {
     stsConfiguration     = new CustomSecurityTokenServiceConfiguration();
     securityTokenService = new CustomSecurityTokenService(this.stsConfiguration);
 }
Ejemplo n.º 18
0
 /// <summary>
 /// Determines the principal stored with the queued message
 /// </summary>
 protected async Task <IPrincipal> ResolvePrincipal(IMessageHeaders headers, string senderPrincipal)
 {
     return(await SecurityTokenService.NullSafeValidate(headers.SecurityToken));
 }
Ejemplo n.º 19
0
        private SoapHttpClientAuthenticator CreateAuthenticator(Offer offer)
        {
            DelegationTokenRequest delegationTokenRequest = this.GetDelegationTokenRequest(offer);

            SharingEngine.Tracer.TraceDebug <DelegationTokenRequest>((long)this.GetHashCode(), "Requesting token for: {0}", delegationTokenRequest);
            if (this.adUser == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "adUser is null here");
                throw new ADUserNotFoundException();
            }
            if (this.externalAuthentication == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "externalAuthentication is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("externalAuthentication"));
            }
            SecurityTokenService securityTokenService = this.externalAuthentication.GetSecurityTokenService(this.adUser.OrganizationId);

            if (securityTokenService == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "securityTokenService is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("securityTokenService"));
            }
            Stopwatch      stopwatch = Stopwatch.StartNew();
            bool           flag      = false;
            RequestedToken requestedToken;

            try
            {
                requestedToken = securityTokenService.IssueToken(delegationTokenRequest);
                flag           = true;
            }
            catch (WSTrustException ex)
            {
                SharingEngine.Tracer.TraceError <WSTrustException>((long)this.GetHashCode(), "Unable to request token due exception: {0}", ex);
                throw new FailedCommunicationException(ex, delegationTokenRequest);
            }
            finally
            {
                if (flag)
                {
                    stopwatch.Stop();
                    PerformanceCounters.AverageExternalAuthenticationTokenRequestTime.IncrementBy(stopwatch.ElapsedTicks);
                    PerformanceCounters.AverageExternalAuthenticationTokenRequestTimeBase.Increment();
                    PerformanceCounters.SuccessfulExternalAuthenticationTokenRequests.Increment();
                }
                else
                {
                    PerformanceCounters.FailedExternalAuthenticationTokenRequests.Increment();
                }
            }
            if (requestedToken == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "token is null here");
                throw new InvalidParamException(Strings.ArgumentValidationFailedException("token"));
            }
            if (this.subscription == null)
            {
                SharingEngine.Tracer.TraceError((long)this.GetHashCode(), "subscription is null here");
                throw new SubscriptionNotFoundException();
            }
            XmlElement any = SharingKeyHandler.Encrypt(new SmtpAddress(this.subscription.SharingKey), requestedToken.ProofToken);
            SoapHttpClientAuthenticator soapHttpClientAuthenticator = SoapHttpClientAuthenticator.Create(requestedToken);

            soapHttpClientAuthenticator.AdditionalSoapHeaders.Add(new SharingSecurityHeader(any));
            return(soapHttpClientAuthenticator);
        }
Ejemplo n.º 20
0
        private bool ProcessError(SecurityTokenService secureService, SoapException exception, MSNTicket msnticket, EventHandler onSuccess, EventHandler <ExceptionEventArgs> onError)
        {
            string errFedDirectLogin = @"Direct login to WLID is not allowed for this federated namespace";

            if (exception == null)
            {
                return(false);
            }

            if (secureService.pp == null)
            {
                return(false);
            }

            uint errorCode = uint.Parse(secureService.pp.reqstatus.Remove(0, "0x".Length), NumberStyles.HexNumber);

            if (errorCode == 0x800488ee)
            {
                if (exception.Detail.InnerXml.IndexOf(errFedDirectLogin) != -1)
                {
                    string fedLoginURL  = string.Empty;
                    string fedAuthURL   = string.Empty;
                    string fedBrandName = string.Empty;

                    foreach (extPropertyType extProperty in secureService.pp.extProperties)
                    {
                        switch (extProperty.Name)
                        {
                        case "STSAuthURL":        //STS means Security Token Service.
                            fedLoginURL = extProperty.Value;
                            break;

                        case "AuthURL":
                            fedAuthURL = extProperty.Value;
                            break;

                        case "AllowFedUsersWLIDSignIn":       //Is it allow to login by MSN ? Not all feduser can log in with a WLM client.
                            if (!bool.Parse(extProperty.Value))
                            {
                                return(false);
                            }
                            break;

                        case "FederationBrandName":
                            fedBrandName = extProperty.Value;
                            break;

                        case "IsFederatedNS":
                            if (!bool.Parse(extProperty.Value))
                            {
                                return(false);
                            }
                            break;
                        }
                    }

                    if (fedLoginURL == string.Empty)
                    {
                        return(false);
                    }

                    Uri    fedLoginURI    = new Uri(fedLoginURL);
                    string strFedLoginURI = fedLoginURI.Scheme.ToUpperInvariant() + "://" + fedLoginURI.Host + (fedLoginURI.Scheme.ToLowerInvariant() == "https" ? ":443" : string.Empty) + "/" + fedLoginURI.PathAndQuery;
                    SecurityTokenService fedSecureService = CreateSecurityTokenService(@"http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", strFedLoginURI);
                    fedSecureService.Url = fedLoginURL;

                    RequestSecurityTokenType token = new RequestSecurityTokenType();
                    token.Id          = "RST0";
                    token.RequestType = RequestTypeOpenEnum.httpschemasxmlsoaporgws200502trustIssue;

                    AppliesTo appliesTo = new AppliesTo();
                    appliesTo.EndpointReference               = new EndpointReferenceType();
                    appliesTo.EndpointReference.Address       = new AttributedURIType();
                    appliesTo.EndpointReference.Address.Value = strFedLoginURI.Remove(0, @"HTTPS://".Length);

                    token.AppliesTo = appliesTo;

                    RequestSecurityTokenResponseType response = null;

                    if (onSuccess != null && onError != null)
                    {
                        //Async request.
                        fedSecureService.RequestSecurityTokenCompleted += delegate(object sender, RequestSecurityTokenCompletedEventArgs e)
                        {
                            if (!e.Cancelled)
                            {
                                if (e.Error != null)
                                {
                                    MSNPSharpException sexp = new MSNPSharpException(e.Error.Message + ". See innerexception for detail.", e.Error);
                                    onError(this, new ExceptionEventArgs(sexp));
                                    return;
                                }

                                response = e.Result;

                                if (response.RequestedSecurityToken == null || response.RequestedSecurityToken.Assertion == null)
                                {
                                    return;
                                }

                                AssertionType assertion = response.RequestedSecurityToken.Assertion;
                                secureService = CreateSecurityTokenService(@"http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", @"HTTPS://login.live.com:443//RST2.srf");
                                secureService.Security.Assertion = assertion;

                                if (response.Lifetime != null)
                                {
                                    secureService.Security.Timestamp.Created = response.Lifetime.Created;
                                    secureService.Security.Timestamp.Expires = response.Lifetime.Expires;
                                }

                                Authenticate(secureService, msnticket, onSuccess, onError);
                            }
                        };

                        fedSecureService.RequestSecurityTokenAsync(token, new object());
                        return(true);
                    }
                    else
                    {
                        //Sync request.
                        try
                        {
                            response = fedSecureService.RequestSecurityToken(token);
                        }
                        catch (Exception ex)
                        {
                            MSNPSharpException sexp = new MSNPSharpException(ex.Message + ". See innerexception for detail.", ex);

                            throw sexp;
                        }

                        if (response.RequestedSecurityToken == null)
                        {
                            return(false);
                        }
                        if (response.RequestedSecurityToken.Assertion == null)
                        {
                            return(false);
                        }

                        AssertionType assertion = response.RequestedSecurityToken.Assertion;
                        secureService = CreateSecurityTokenService(@"http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", @"HTTPS://login.live.com:443//RST2.srf");
                        secureService.Security.Assertion = assertion;

                        Authenticate(secureService, msnticket, onSuccess, onError);
                        return(true);
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 21
0
        private void Authenticate(SecurityTokenService securService, MSNTicket msnticket, EventHandler onSuccess, EventHandler <ExceptionEventArgs> onError)
        {
            if (user.Split('@').Length > 1)
            {
                if (user.Split('@')[1].ToLower(CultureInfo.InvariantCulture) == "msn.com")
                {
                    securService.Url = @"https://msnia.login.live.com/RST2.srf";
                }
            }
            else
            {
                AuthenticationException authenticationException = new AuthenticationException("Invalid account. The account must contain @ char");
                if (onError != null && onSuccess != null)
                {
                    onError(this, new ExceptionEventArgs(authenticationException));
                }
                else
                {
                    throw authenticationException;
                }
            }

            RequestMultipleSecurityTokensType mulToken = new RequestMultipleSecurityTokensType();

            mulToken.Id = "RSTS";
            mulToken.RequestSecurityToken = auths.ToArray();

            // ASYNC
            if (onSuccess != null && onError != null)
            {
                securService.RequestMultipleSecurityTokensCompleted += delegate(object sender, RequestMultipleSecurityTokensCompletedEventArgs e)
                {
                    if (!e.Cancelled)
                    {
                        if (e.Error != null)
                        {
                            SoapException sex = e.Error as SoapException;
                            if (sex != null && ProcessError(securService, sex, msnticket, onSuccess, onError))
                            {
                                return;
                            }

                            MSNPSharpException sexp = new MSNPSharpException(e.Error.Message + ". See innerexception for detail.", e.Error);
                            if (securService.pp != null)
                            {
                                sexp.Data["Code"] = securService.pp.reqstatus;  //Error code
                            }
                            onError(this, new ExceptionEventArgs(sexp));
                        }
                        else if (e.Result != null)
                        {
                            GetTickets(e.Result, securService, msnticket);

                            onSuccess(this, EventArgs.Empty);
                        }
                        else
                        {
                            // Is this possible? Answer: No.
                        }
                    }
                };
                securService.RequestMultipleSecurityTokensAsync(mulToken, new object());
            }
            else
            {
                try
                {
                    RequestSecurityTokenResponseType[] result = securService.RequestMultipleSecurityTokens(mulToken);

                    if (result != null)
                    {
                        GetTickets(result, securService, msnticket);
                    }
                }
                catch (SoapException sex)
                {
                    if (ProcessError(securService, sex, msnticket, onSuccess, onError))
                    {
                        return;
                    }

                    throw sex;
                }
                catch (Exception ex)
                {
                    MSNPSharpException sexp = new MSNPSharpException(ex.Message + ". See innerexception for detail.", ex);

                    if (securService.pp != null)
                    {
                        sexp.Data["Code"] = securService.pp.reqstatus;  //Error code
                    }
                    throw sexp;
                }
            }
        }
 private void InitSTS(string domain)
 {
     stsConfiguration     = new CustomSTSConfig(domain);
     securityTokenService = new CustomSTS(stsConfiguration);
 }
Ejemplo n.º 23
0
 public SecurityTokenApiController(SecurityTokenService svc)
 {
     _svc = svc;
 }
 /// <summary>
 /// 
 /// </summary>
 /// <param name="requestMessage"></param>
 /// <param name="principal"></param>
 /// <param name="sts"></param>
 /// <returns></returns>
 public static AccessTokenResponse ProcessAccessTokenRequest(AccessTokenRequest requestMessage, IPrincipal principal, SecurityTokenService sts)
 {
     return ProcessAccessTokenRequest(requestMessage, principal, sts, false);
 }
        /// <summary>
        /// Requests a token from the issuer and builds a response with that token.
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="principal"></param>
        /// <param name="sts"></param>
        /// <param name="withRefreshToken"></param>
        /// <returns></returns>
        public static AccessTokenResponse ProcessAccessTokenRequest(AccessTokenRequest requestMessage, IPrincipal principal, SecurityTokenService sts, Boolean withRefreshToken)
        {
            if (null == requestMessage)
                throw new ArgumentNullException("requestMessage");
            if (null == principal)
                throw new ArgumentNullException("principal");
            if (null == sts)
                throw new ArgumentNullException("sts");

            // Call issuer to create token
            // TODO
            /*var context = new WSTrustSerializationContext(
                sts.SecurityTokenServiceConfiguration.SecurityTokenHandlerCollectionManager,
                sts.SecurityTokenServiceConfiguration.CreateAggregateTokenResolver(),
                sts.SecurityTokenServiceConfiguration.IssuerTokenResolver);*/
            var response = sts.Issue(
                ClaimsPrincipal.CreateFromPrincipal(principal),
                new WrapSerializer().CreateRequest(requestMessage));

            // Create response
            var token = response.RequestedSecurityToken.SecurityToken;
            return WriteToken(token, withRefreshToken);
        }
Ejemplo n.º 26
0
        public EncryptionResults Encrypt(IExchangePrincipal mailboxOwner, IRecipientSession recipientSession, ExternalUserCollection externalUserCollection, ValidRecipient[] recipients, string sender, string containerClass, string folderId, IFrontEndLocator frontEndLocator)
        {
            SharingDataType sharingDataType = SharingDataType.FromContainerClass(containerClass);

            if (sharingDataType == null || !sharingDataType.IsExternallySharable)
            {
                throw new ArgumentOutOfRangeException("containerClass");
            }
            ADUser aduser = DirectoryHelper.ReadADRecipient(mailboxOwner.MailboxInfo.MailboxGuid, mailboxOwner.MailboxInfo.IsArchive, recipientSession) as ADUser;

            if (aduser == null)
            {
                SharedFolderDataEncryption.Tracer.TraceError <SharedFolderDataEncryption, string>((long)this.GetHashCode(), "{0}: The Active Directory user was not found. Sender={1}.", this, sender);
                throw new ObjectNotFoundException(ServerStrings.ADUserNotFound);
            }
            ProxyAddress item = new SmtpProxyAddress(sender, false);

            if (!aduser.EmailAddresses.Contains(item))
            {
                SharedFolderDataEncryption.Tracer.TraceError <SharedFolderDataEncryption, string>((long)this.GetHashCode(), "{0}: The SMTP address was not found in the user AD object for this mailbox. Sender={1}.", this, sender);
                throw new ObjectNotFoundException(ServerStrings.ADUserNotFound);
            }
            SharingPolicy sharingPolicy = DirectoryHelper.ReadSharingPolicy(mailboxOwner.MailboxInfo.MailboxGuid, mailboxOwner.MailboxInfo.IsArchive, recipientSession);

            SharedFolderDataEncryption.Tracer.TraceDebug <SharedFolderDataEncryption, object>((long)this.GetHashCode(), "{0}: Sharing policy to be applied to this user: {1}", this, (sharingPolicy == null) ? "<null>" : sharingPolicy.Id);
            SharingPolicyAction sharingPolicyActions = SharedFolderDataEncryption.GetSharingPolicyActions(sharingDataType.StoreObjectType);

            SharedFolderDataRecipient[] externalIdentities = SharedFolderDataEncryption.GetExternalIdentities(externalUserCollection, recipients);
            List <InvalidRecipient>     list = new List <InvalidRecipient>();
            Dictionary <TokenTarget, List <SharedFolderDataRecipient> > dictionary = new Dictionary <TokenTarget, List <SharedFolderDataRecipient> >(externalIdentities.Length, SharedFolderDataEncryption.TokenTargetComparer);

            for (int i = 0; i < recipients.Length; i++)
            {
                SharedFolderDataRecipient item2          = externalIdentities[i];
                ValidRecipient            validRecipient = recipients[i];
                SmtpAddress smtpAddress = new SmtpAddress(validRecipient.SmtpAddress);
                string      domain      = smtpAddress.Domain;
                if (sharingPolicy == null || !sharingPolicy.IsAllowedForAnySharing(domain, sharingPolicyActions))
                {
                    SharedFolderDataEncryption.Tracer.TraceDebug <string>((long)this.GetHashCode(), "Sharing policy does not allow user to share with domain {0}", domain);
                    list.Add(new InvalidRecipient(validRecipient.SmtpAddress, InvalidRecipientResponseCodeType.SystemPolicyBlocksSharingWithThisRecipient));
                }
                else
                {
                    SmtpAddress smtpAddress2 = new SmtpAddress(validRecipient.SmtpAddressForEncryption);
                    TokenTarget tokenTarget  = TargetUriResolver.Resolve(smtpAddress2.Domain, aduser.OrganizationId);
                    if (tokenTarget == null)
                    {
                        list.Add(new InvalidRecipient(validRecipient.SmtpAddress, InvalidRecipientResponseCodeType.RecipientOrganizationNotFederated));
                    }
                    else
                    {
                        List <SharedFolderDataRecipient> list2;
                        if (!dictionary.TryGetValue(tokenTarget, out list2))
                        {
                            list2 = new List <SharedFolderDataRecipient>(1);
                            dictionary.Add(tokenTarget, list2);
                        }
                        list2.Add(item2);
                    }
                }
            }
            List <EncryptedSharedFolderData> list3 = new List <EncryptedSharedFolderData>(dictionary.Count);
            SharedFolderData sharedFolderData      = new SharedFolderData();

            sharedFolderData.DataType          = sharingDataType.ExternalName;
            sharedFolderData.FolderId          = folderId;
            sharedFolderData.SharingUrl        = this.GetSharingUrl(aduser, frontEndLocator);
            sharedFolderData.FederationUri     = this.externalAuthentication.TokenValidator.TargetUri.ToString();
            sharedFolderData.SenderSmtpAddress = sender;
            DelegationTokenRequest delegationTokenRequest = new DelegationTokenRequest
            {
                FederatedIdentity = aduser.GetFederatedIdentity(),
                EmailAddress      = aduser.GetFederatedSmtpAddress(new SmtpAddress(sender)).ToString(),
                Offer             = Offer.SharingInviteMessage
            };
            SecurityTokenService securityTokenService = this.externalAuthentication.GetSecurityTokenService(aduser.OrganizationId);

            foreach (KeyValuePair <TokenTarget, List <SharedFolderDataRecipient> > keyValuePair in dictionary)
            {
                delegationTokenRequest.Target = keyValuePair.Key;
                sharedFolderData.Recipients   = keyValuePair.Value.ToArray();
                try
                {
                    RequestedToken requestedToken = securityTokenService.IssueToken(delegationTokenRequest);
                    list3.Add(this.Encrypt(requestedToken, sharedFolderData));
                }
                catch (WSTrustException ex)
                {
                    foreach (SharedFolderDataRecipient sharedFolderDataRecipient in sharedFolderData.Recipients)
                    {
                        list.Add(new InvalidRecipient(sharedFolderDataRecipient.SmtpAddress, SharedFolderDataEncryption.GetResponseCodeFromException(ex), ex.ToString()));
                    }
                }
            }
            return(new EncryptionResults(list3.ToArray(), list.ToArray()));
        }
Ejemplo n.º 27
0
        /// <summary>
        /// Authenticate the specified user. By asynchronous or synchronous ways.
        /// </summary>
        /// <param name='msnticket'>
        /// Msnticket.
        /// </param>
        /// <param name='onSuccess'>
        /// Callback when the authentication was passed.
        /// </param>
        /// <param name='onError'>
        /// Callback when the authentication encounts errors.
        /// </param>
        /// <exception cref='AuthenticationException'>
        /// Is thrown when the authentication failed and the request is a synchronous request.
        /// Or the <paramref name="onError"/> callback will be called.
        /// </exception>
        /// <remarks>
        /// The method is asynchronous only when both <paramref name="onSuccess"/> and <paramref name="onError"/> are not null.
        /// Otherwise it will perform a synchronous request.
        /// </remarks>
        public void Authenticate(MSNTicket msnticket, EventHandler onSuccess, EventHandler <ExceptionEventArgs> onError)
        {
            SecurityTokenService securService = CreateSecurityTokenService(@"http://schemas.xmlsoap.org/ws/2005/02/trust/RST/Issue", @"HTTPS://login.live.com:443//RST2.srf");

            Authenticate(securService, msnticket, onSuccess, onError);
        }
Ejemplo n.º 28
0
        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);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Handles the click event on the logon button.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event arguments.</param>
        private void _logonButton_Click(object sender, EventArgs e)
        {
            // Get the user provider.
            var userProvider = this.Container.Resolve<IUserProvider>();

            // Get the principal object for the current user.
            IPrincipal principal;
            try
            {
                principal = userProvider.Logon(this._loginTextBox.Text, this._passwordTextBox.Text);
            }
            catch (SecurityException)
            {
                return;
            }

            // Create the sign in request.
            var signInRequestMessage =
                (SignInRequestMessage)WSFederationMessage.CreateFromUri(this.Request.Url);

            // Create the security token service.
            var securityTokenService =
                new SecurityTokenService(new SecurityTokenServiceConfiguration());

            // Send the sign request to the security token service and get a sign in response.
            var signInResponseMessage =
                FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(
                    signInRequestMessage, principal, securityTokenService);

            // Redirect based on the sign in response.
            FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(
                signInResponseMessage, this.Response);
        }
Ejemplo n.º 30
0
        protected virtual bool TryGetExchangeRpcUrlFromAutodiscoverSettings(SmtpAddress remoteIdentity, SecurityTokenService securityTokenService, DelegationTokenRequest autoDiscoveryTokenRequest, Uri autoDiscoveryEndpoint, out Uri exchangeRpcUrl)
        {
            exchangeRpcUrl = null;
            FedOrgCredentials credentials = new FedOrgCredentials(autoDiscoveryTokenRequest, securityTokenService);
            bool result;

            using (AutoDiscoverUserSettingsClient autoDiscoverUserSettingsClient = AutoDiscoverUserSettingsClient.CreateInstance(DirectorySessionFactory.Default.CreateTopologyConfigurationSession(ConsistencyMode.IgnoreInvalid, this.storeSession.MailboxOwner.MailboxInfo.OrganizationId.ToADSessionSettings(), 250, "TryGetExchangeRpcUrlFromAutodiscoverSettings", "f:\\15.00.1497\\sources\\dev\\data\\src\\storage\\ExchangePrincipal\\RemoteMailboxProperties.cs"), credentials, remoteIdentity, autoDiscoveryEndpoint, RemoteMailboxProperties.AutodiscoveryRequestedSettings))
            {
                autoDiscoverUserSettingsClient.AnchorMailbox = this.storeSession.MailboxOwner.MailboxInfo.PrimarySmtpAddress.ToString();
                UserSettings  userSettings  = autoDiscoverUserSettingsClient.Discover();
                StringSetting stringSetting = userSettings.GetSetting(RemoteMailboxProperties.AutodiscoveryRequestedSettings[0]) as StringSetting;
                result = (stringSetting != null && Uri.TryCreate(stringSetting.Value, UriKind.Absolute, out exchangeRpcUrl));
            }
            return(result);
        }
        private static ExternalAuthentication.FederationTrustResults TryCreateSecurityTokenService(FederationTrust federationTrust, WebProxy webProxy)
        {
            if (!ExternalAuthentication.IsRequiredPropertyAvailable(federationTrust.TokenIssuerUri, "TokenIssuerUri"))
            {
                return(new ExternalAuthentication.FederationTrustResults
                {
                    FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.MisconfiguredFederationTrust,
                    SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.MissingTokenIssuerUri
                });
            }
            if (!ExternalAuthentication.IsRequiredPropertyAvailable(federationTrust.TokenIssuerEpr, "TokenIssuerEpr"))
            {
                return(new ExternalAuthentication.FederationTrustResults
                {
                    FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.MisconfiguredFederationTrust,
                    SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.MissingTokenIssuerEpr
                });
            }
            if (!ExternalAuthentication.IsRequiredPropertyAvailable(federationTrust.ApplicationUri, "ApplicationUri"))
            {
                return(new ExternalAuthentication.FederationTrustResults
                {
                    FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.MisconfiguredFederationTrust,
                    SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.MissingApplicationUri
                });
            }
            if (!ExternalAuthentication.IsRequiredPropertyAvailable(federationTrust.TokenIssuerCertificate, "TokenIssuerCertificate"))
            {
                return(new ExternalAuthentication.FederationTrustResults
                {
                    FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.MisconfiguredFederationTrust,
                    SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.MissingTokenIssuerCertificate
                });
            }
            X509Certificate2[] tokenSignatureCertificates = (federationTrust.TokenIssuerPrevCertificate != null) ? new X509Certificate2[]
            {
                federationTrust.TokenIssuerCertificate,
                federationTrust.TokenIssuerPrevCertificate
            } : new X509Certificate2[]
            {
                federationTrust.TokenIssuerCertificate
            };
            if (!ExternalAuthentication.HasAtLeastOneValidCertificate(tokenSignatureCertificates, federationTrust.Id, "TokenIssuerCertificate and TokenIssuerPrevCertificate"))
            {
                return(new ExternalAuthentication.FederationTrustResults
                {
                    FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.InvalidTokenIssuerCertificate,
                    SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.NoSubCode
                });
            }
            if (!ExternalAuthentication.IsRequiredPropertyAvailable(federationTrust.OrgPrivCertificate, "OrgPrivCertificate"))
            {
                return(new ExternalAuthentication.FederationTrustResults
                {
                    FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.MisconfiguredFederationTrust,
                    SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.MissingOrgPrivCertificate
                });
            }
            X509Store x509Store = new X509Store(StoreName.My, StoreLocation.LocalMachine);

            x509Store.Open(OpenFlags.ReadOnly);
            X509Certificate2 certificate;

            X509Certificate2[] tokenDecryptionCertificates;
            try
            {
                ExternalAuthentication.ExternalAuthenticationSubFailureType externalAuthenticationSubFailureType;
                certificate = ExternalAuthentication.GetCertificate(x509Store, federationTrust.OrgPrivCertificate, federationTrust.Id, "OrgPrivCertificate", true, out externalAuthenticationSubFailureType);
                if (certificate == null)
                {
                    ExternalAuthentication.ConfigurationTracer.TraceError <string>(0L, "Federation trust is misconfigured. Unable to find certificate corresponding to OrgPrivCertificate={0}", federationTrust.OrgPrivCertificate);
                    return(new ExternalAuthentication.FederationTrustResults
                    {
                        FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.MisconfiguredFederationTrust,
                        SubFailureType = externalAuthenticationSubFailureType
                    });
                }
                X509Certificate2 x509Certificate = null;
                if (!string.IsNullOrEmpty(federationTrust.OrgPrevPrivCertificate))
                {
                    x509Certificate = ExternalAuthentication.GetCertificate(x509Store, federationTrust.OrgPrevPrivCertificate, federationTrust.Id, "OrgPrevPrivCertificate", false, out externalAuthenticationSubFailureType);
                }
                tokenDecryptionCertificates = ((x509Certificate != null) ? new X509Certificate2[]
                {
                    certificate,
                    x509Certificate
                } : new X509Certificate2[]
                {
                    certificate
                });
            }
            finally
            {
                x509Store.Close();
            }
            SecurityTokenService securityTokenService = new SecurityTokenService(federationTrust.TokenIssuerEpr, webProxy, certificate, federationTrust.TokenIssuerUri, federationTrust.PolicyReferenceUri, federationTrust.ApplicationUri.OriginalString);

            ExternalAuthentication.ConfigurationTracer.TraceDebug(0L, "New instance of SecurityTokenService successfully built.");
            return(new ExternalAuthentication.FederationTrustResults
            {
                FailureType = ExternalAuthentication.ExternalAuthenticationFailureType.NoFailure,
                SubFailureType = ExternalAuthentication.ExternalAuthenticationSubFailureType.NoFailure,
                SecurityTokenService = securityTokenService,
                TokenSignatureCertificates = tokenSignatureCertificates,
                TokenDecryptionCertificates = tokenDecryptionCertificates
            });
        }
        /// <summary>
        /// Requests a token from the issuer and builds a response with that token.
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="principal"></param>
        /// <param name="sts"></param>
        /// <param name="withRefreshToken"></param>
        /// <returns></returns>
        public static AccessTokenResponse ProcessAccessTokenRequest(AccessTokenRequest requestMessage, IPrincipal principal, SecurityTokenService sts, Boolean withRefreshToken)
        {
            if (null == requestMessage)
                throw new ArgumentNullException("requestMessage");
            if (null == principal)
                throw new ArgumentNullException("principal");
            if (null == sts)
                throw new ArgumentNullException("sts");

            // Call issuer to create token
            var response = sts.Issue(
                ClaimsPrincipal.CreateFromPrincipal(principal),
                new WrapSerializer().CreateRequest(requestMessage));

            // Create response
            var token = response.RequestedSecurityToken.SecurityToken;
            return WriteToken(token, withRefreshToken);
        }
Ejemplo n.º 33
0
        // Token: 0x060003B7 RID: 951 RVA: 0x0001721C File Offset: 0x0001541C
        private void ExecuteCommand(IIdentity callerIdentity, CallContext callContext)
        {
            ADRecipient adrecipient = HttpContext.Current.Items["CallerRecipient"] as ADRecipient;

            if (adrecipient == null && (Common.IsPartnerHostedOnly || VariantConfiguration.InvariantNoFlightingSnapshot.Autodiscover.NoCrossForestDiscover.Enabled))
            {
                string identityNameForTrace = Common.GetIdentityNameForTrace(callerIdentity);
                ExTraceGlobals.FrameworkTracer.TraceError <string>(0L, "ExecuteCommand -- IRecipientSession.FindBySid user for {0} returned null.", identityNameForTrace);
                callContext.Response.ErrorCode    = ErrorCode.InvalidUser;
                callContext.Response.ErrorMessage = string.Format(Strings.InvalidUser, identityNameForTrace);
                return;
            }
            PartnerInfo partnerInfo  = null;
            string      targetTenant = null;
            bool        flag         = false;
            string      text         = null;

            byte[] binarySecret = null;
            GetUserSettingsCommandBase getUserSettingsCommandBase;

            if (VariantConfiguration.InvariantNoFlightingSnapshot.Autodiscover.ParseBinarySecretHeader.Enabled && AutodiscoverRequestMessage.HasBinarySecretHeader(out text))
            {
                PerformanceCounters.UpdatePartnerTokenRequests(callContext.UserAgent);
                bool flag2 = false;
                if (!string.IsNullOrEmpty(text))
                {
                    try
                    {
                        binarySecret = Convert.FromBase64String(text);
                        flag2        = true;
                    }
                    catch (FormatException)
                    {
                        ExTraceGlobals.FrameworkTracer.TraceDebug <string>((long)this.GetHashCode(), "[GetUserSettingsRequestMessage::ExecuteCommand] the binary secret header {0} has invalid format", text);
                    }
                }
                if (!flag2)
                {
                    PerformanceCounters.UpdatePartnerTokenRequestsFailed(callContext.UserAgent);
                    callContext.Response.ErrorCode    = ErrorCode.InvalidRequest;
                    callContext.Response.ErrorMessage = Strings.InvalidBinarySecretHeader;
                    return;
                }
                if (!this.TryGetMailboxAccessPartnerInfo(callContext, adrecipient, out partnerInfo, out targetTenant))
                {
                    ExTraceGlobals.FrameworkTracer.TraceDebug((long)this.GetHashCode(), "[GetUserSettingsRequestMessage::ExecuteCommand] TryGetMailboxAccessPartnerInfo returns false.");
                    PerformanceCounters.UpdatePartnerTokenRequestsFailed(callContext.UserAgent);
                    callContext.Response.ErrorCode    = ErrorCode.InvalidRequest;
                    callContext.Response.ErrorMessage = Strings.InvalidPartnerTokenRequest;
                    return;
                }
                flag = true;
                ExTraceGlobals.FrameworkTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "GetUserSettingsForPartner created for the '{0}'. The caller is FPO partner.", adrecipient);
                getUserSettingsCommandBase = new GetUserSettingsForPartner(callerIdentity.GetSecurityIdentifier(), callContext);
            }
            else if (adrecipient == null)
            {
                ExTraceGlobals.FrameworkTracer.TraceDebug <string>((long)this.GetHashCode(), "GetUserSettingsForUserWithUnscopedCaller created for '{0}'.", Common.GetIdentityNameForTrace(callerIdentity));
                getUserSettingsCommandBase = new GetUserSettingsForUserWithUnscopedCaller(callerIdentity.GetSecurityIdentifier(), callContext);
            }
            else if (ExchangeRunspaceConfiguration.IsAllowedOrganizationForPartnerAccounts(adrecipient.OrganizationId))
            {
                ExTraceGlobals.FrameworkTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "GetUserSettingsForPartner created for '{0}'.", adrecipient);
                getUserSettingsCommandBase = new GetUserSettingsForPartner(callerIdentity.GetSecurityIdentifier(), callContext);
            }
            else
            {
                ExTraceGlobals.FrameworkTracer.TraceDebug <ADRecipient>((long)this.GetHashCode(), "GetUserSettingsForUser created for '{0}'.", adrecipient);
                getUserSettingsCommandBase = new GetUserSettingsForUser(adrecipient, callerIdentity.GetSecurityIdentifier(), callContext);
            }
            getUserSettingsCommandBase.Execute();
            if (flag)
            {
                UserResponse userResponse = callContext.Response.UserResponses[0];
                if (userResponse.ErrorCode == ErrorCode.NoError || userResponse.ErrorCode == ErrorCode.RedirectUrl)
                {
                    string        assertionId = SecurityTokenService.CreateSamlAssertionId();
                    MessageHeader header      = MessageHeader.CreateHeader("PartnerToken", "http://schemas.microsoft.com/exchange/2010/Autodiscover", partnerInfo.CreateSamlToken(assertionId, targetTenant, binarySecret, GetUserSettingsRequestMessage.tokenLifetime.Value));
                    MessageHeader header2     = MessageHeader.CreateHeader("PartnerTokenReference", "http://schemas.microsoft.com/exchange/2010/Autodiscover", PartnerInfo.GetTokenReference(assertionId));
                    OperationContext.Current.OutgoingMessageHeaders.Add(header);
                    OperationContext.Current.OutgoingMessageHeaders.Add(header2);
                    return;
                }
                PerformanceCounters.UpdatePartnerTokenRequestsFailed(callContext.UserAgent);
                ExTraceGlobals.FrameworkTracer.TraceDebug <ErrorCode, string>((long)this.GetHashCode(), "No partner token header added since the user response error code is {0}, error message is '{1}'", userResponse.ErrorCode, userResponse.ErrorMessage);
            }
        }
Ejemplo n.º 34
0
        private void GetTickets(RequestSecurityTokenResponseType[] result, SecurityTokenService securService, MSNTicket msnticket)
        {
            if (securService.pp != null)
            {
                if (securService.pp.credProperties != null)
                {
                    foreach (credPropertyType credproperty in securService.pp.credProperties)
                    {
                        if (credproperty.Name == "MainBrandID")
                        {
                            msnticket.MainBrandID = credproperty.Value;
                        }
                        if (credproperty.Name == "CID" && !String.IsNullOrEmpty(credproperty.Value))
                        {
                            msnticket.OwnerCID = long.Parse(credproperty.Value, NumberStyles.HexNumber);
                        }
                    }
                }
                if (securService.pp.extProperties != null)
                {
                    foreach (extPropertyType extproperty in securService.pp.extProperties)
                    {
                        if (extproperty.Name == "CID" && !String.IsNullOrEmpty(extproperty.Value))
                        {
                            msnticket.OwnerCID = long.Parse(extproperty.Value, NumberStyles.HexNumber);
                        }
                    }
                }
            }

            foreach (RequestSecurityTokenResponseType token in result)
            {
                SSOTicketType ticketype = SSOTicketType.None;
                switch (token.AppliesTo.EndpointReference.Address.Value)
                {
                case "contacts.msn.com":
                    ticketype = SSOTicketType.Contact;
                    break;

                case "messengerclear.live.com":
                    ticketype = SSOTicketType.Clear;
                    break;

                case "storage.msn.com":
                    ticketype = SSOTicketType.Storage;
                    break;

                case "sup.live.com":
                    ticketype = SSOTicketType.WhatsUp;
                    break;

                case "directory.services.live.com":
                    ticketype = SSOTicketType.Directory;
                    break;

                case "rpstauth.live.com":
                    ticketype = SSOTicketType.RPST;
                    break;
                }

                SSOTicket ssoticket = new SSOTicket(ticketype);

                if (token.AppliesTo != null)
                {
                    ssoticket.Domain = token.AppliesTo.EndpointReference.Address.Value;
                }

                if (token.RequestedSecurityToken.BinarySecurityToken != null)
                {
                    ssoticket.Ticket = token.RequestedSecurityToken.BinarySecurityToken.Value;
                }

                if (token.RequestedProofToken != null && token.RequestedProofToken.BinarySecret != null)
                {
                    ssoticket.BinarySecret = token.RequestedProofToken.BinarySecret.Value;
                }

                if (token.Lifetime != null)
                {
                    ssoticket.Created = XmlConvert.ToDateTime(token.Lifetime.Created.Value, "yyyy-MM-ddTHH:mm:ssZ");
                    ssoticket.Expires = XmlConvert.ToDateTime(token.Lifetime.Expires.Value, "yyyy-MM-ddTHH:mm:ssZ");
                }

                lock (msnticket.SSOTickets)
                {
                    msnticket.SSOTickets[ticketype] = ssoticket;
                }
            }
        }