public async Task<SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = await CreateSubjectAsync(validationResult);

            // create token for user
            var token = CreateSecurityToken(validationResult, outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm),
                Context = validationResult.SignInRequestMessage.Context,
                ReplyTo = validationResult.ReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();
            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();
            
            var responseMessage = new SignInResponseMessage(
                new Uri(validationResult.ReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return responseMessage;
        }
Beispiel #2
0
        internal bool Logoff(string userName, string password, SecurityToken sessionToken)
        {
            using (WSTrustChannelFactory factory = GetTrustChannelFactory())
            {
                //// Set up credentials
                if (factory.Credentials == null)
                {
                    throw new Exception("Credentails are null");
                }
                factory.Credentials.UserName.UserName  = userName;
                factory.Credentials.UserName.Password  = password;
                factory.Credentials.SupportInteractive = false;

                // Create a "request for token" SOAP message.
                // We want the security server to Issue us with a token
                RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Cancel);
                // the token we want to cancel
                rst.CancelTarget = new SecurityTokenElement(sessionToken);


                // Create the communicaiton channel
                IWSTrustChannelContract channel = factory.CreateChannel();

                // Cancel token
                // ReSharper disable once UnusedVariable
                RequestSecurityTokenResponse response = channel.Cancel(rst);
                return(response.RequestedTokenCancelled);
            }
        }
Beispiel #3
0
        private SecurityToken GetActAsToken()
        {
            // Retrieve the token that was saved during initial user login
            BootstrapContext bootstrapContext = ClaimsPrincipal.Current.Identities.First().BootstrapContext as BootstrapContext;

            // Use the Thinktecture-implementation of the UserNameWSBinding to setup the channel factory to ADFS
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);
            var factory = new WSTrustChannelFactory(binding, new EndpointAddress("https://[ADFS]/adfs/services/trust/13/usernamemixed"));

            // For demo purposes, we're authenticating to ADFS using a user name and password representing the web application
            // If the web server is domain-joined, you can use Windows Authentication instead
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            factory.TrustVersion = TrustVersion.WSTrust13;

            // Setup the request details to ask for a token for the backend service, acting as the logged in user
            var request = new RequestSecurityToken();

            request.RequestType = Thinktecture.IdentityModel.Constants.WSTrust13Constants.RequestTypes.Issue;
            request.AppliesTo   = new EndpointReference("https://[BackendService]/Service.svc");
            request.ActAs       = new SecurityTokenElement(bootstrapContext.SecurityToken);

            // Create the channel
            var channel = factory.CreateChannel();
            RequestSecurityTokenResponse response = null;
            SecurityToken delegatedToken          = channel.Issue(request, out response);

            // Return the acquired token
            return(delegatedToken);
        }
        protected virtual void OnLoggedIn(RequestSecurityTokenResponse requestSecurityTokenResponse)
        {
            if (requestSecurityTokenResponse == null)
            {
                Mvx.TaggedTrace(MvxTraceLevel.Error, "DefaultIdentityProviderCollectionViewModel", "Got an empty response from IdentityProvider");
                if (LoginError != null)
                {
                    LoginError(this, new LoginErrorEventArgs {
                        Message = "Got an empty response from IdentityProvider, try logging in again."
                    });
                }
                return;
            }

            var tokenStore   = Mvx.Resolve <ISimpleWebTokenStore>();
            var tokenFactory = Mvx.Resolve <ISimpleWebToken>();

            var token = tokenFactory.CreateTokenFromRaw(requestSecurityTokenResponse.SecurityToken);

            tokenStore.SimpleWebToken = token;

            if (!CanGoBack)
            {
                ShowProgressAfterLogin = true;
            }

            RaisePropertyChanged(() => IsLoggedIn);
            RaisePropertyChanged(() => LoggedInProvider);

            if (tokenStore.IsValid() && CanGoBack)
            {
                NavigateBackCommand.Execute(null);
            }
        }
        private void SignInWebBrowserControl_Navigating(object sender, NavigatingEventArgs e)
        {
            if (e.Uri == new Uri("https://break_here"))
            {
                e.Cancel = true;

                var acsReply = this.BrowserSigninControl.SaveToString();

                Regex tagRegex       = CreateRegexForHtmlTag("BinarySecurityToken");
                var   acsBinaryToken = tagRegex.Match(acsReply).Groups[1].Value;
                var   acsTokenBytes  = Convert.FromBase64String(acsBinaryToken);
                var   acsToken       = System.Text.Encoding.UTF8.GetString(acsTokenBytes, 0, acsTokenBytes.Length);

                tagRegex = CreateRegexForHtmlTag("Expires");
                var expires = DateTime.Parse(tagRegex.Match(acsReply).Groups[1].Value);

                tagRegex = CreateRegexForHtmlTag("TokenType");
                var tokenType = tagRegex.Match(acsReply).Groups[1].Value;

                if (null != RequestSecurityTokenResponseCompleted)
                {
                    var rstr = new RequestSecurityTokenResponse();
                    rstr.TokenString = acsToken;
                    rstr.Expiration  = expires;
                    rstr.TokenType   = tokenType;
                    RequestSecurityTokenResponseCompleted(this, new RequestSecurityTokenResponseCompletedEventArgs(rstr, null));
                }
            }

            lock (_setBrowserVisibleLock)
            {
                _setBrowserVisible = false;
                ShowProgressBar(null);
            }
        }
        public static PeerHashToken CreateHashTokenFrom(Message message)
        {
            PeerHashToken invalid = PeerHashToken.Invalid;
            RequestSecurityTokenResponse response = RequestSecurityTokenResponse.CreateFrom(message.GetReaderAtBodyContents(), MessageSecurityVersion.Default, new PeerSecurityTokenSerializer());

            if (string.Compare(response.TokenType, "http://schemas.microsoft.com/net/2006/05/peer/peerhashtoken", StringComparison.OrdinalIgnoreCase) == 0)
            {
                XmlElement requestSecurityTokenResponseXml = response.RequestSecurityTokenResponseXml;
                if (requestSecurityTokenResponseXml == null)
                {
                    return(invalid);
                }
                foreach (XmlElement element2 in requestSecurityTokenResponseXml.ChildNodes)
                {
                    if (PeerRequestSecurityToken.CompareWithNS(element2.LocalName, element2.NamespaceURI, "Status", "http://schemas.xmlsoap.org/ws/2005/02/trust"))
                    {
                        if (element2.ChildNodes.Count == 1)
                        {
                            XmlElement element = element2.ChildNodes[0] as XmlElement;
                            if (PeerRequestSecurityToken.CompareWithNS(element.LocalName, element.NamespaceURI, "Code", "http://schemas.xmlsoap.org/ws/2005/02/trust") && (string.Compare(XmlHelper.ReadTextElementAsTrimmedString(element), "http://schemas.xmlsoap.org/ws/2005/02/trust/status/valid", StringComparison.OrdinalIgnoreCase) != 0))
                            {
                                return(invalid);
                            }
                        }
                    }
                    else if (PeerRequestSecurityToken.CompareWithNS(element2.LocalName, element2.NamespaceURI, "RequestedSecurityToken", "http://schemas.xmlsoap.org/ws/2005/02/trust"))
                    {
                        return(PeerHashToken.CreateFrom(element2));
                    }
                }
            }
            return(invalid);
        }
Beispiel #7
0
        public XmlElement RenewTicket(X509Certificate2 sessionCert, XmlElement previousTicket)
        {
            //make the request
            var request = new RequestSecurityTokenRequest()
            {
                RequestSecurityToken = new RequestSecurityTokenType()
                {
                    Context     = "urn:uuid:" + Guid.NewGuid().ToString(),
                    TokenType   = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1",
                    RequestType = RequestTypeEnum.httpdocsoasisopenorgwssxwstrust200512Renew,
                    RenewTarget = new RenewTargetType()
                    {
                        SecurityTokenReference = new SecurityTokenReferenceType()
                        {
                            Embedded = new EmbeddedType()
                            {
                                Any = previousTicket
                            }
                        }
                    }
                }
            };

            RequestSecurityTokenResponse step1 = base.Channel.RequestSecurityToken(request);

            return(Complete(sessionCert, step1));
        }
 public CreateCoordinationContextResponse(Message message, Microsoft.Transactions.Wsat.Protocol.ProtocolVersion protocolVersion) : this(protocolVersion)
 {
     if (message.IsEmpty)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidMessageException(Microsoft.Transactions.SR.GetString("InvalidMessageBody")));
     }
     XmlDictionaryReader readerAtBodyContents = message.GetReaderAtBodyContents();
     using (readerAtBodyContents)
     {
         this.ReadFrom(readerAtBodyContents);
         try
         {
             message.ReadFromBodyContentsToEnd(readerAtBodyContents);
         }
         catch (XmlException exception)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidMessageException(Microsoft.Transactions.SR.GetString("InvalidMessageBody"), exception));
         }
     }
     try
     {
         this.IssuedToken = CoordinationServiceSecurity.GetIssuedToken(message, this.CoordinationContext.Identifier, protocolVersion);
     }
     catch (XmlException exception2)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidMessageException(exception2.Message, exception2));
     }
 }
Beispiel #9
0
        public void LogIn(string url, Action <RequestSecurityTokenResponse> onLoggedIn, Action assumeCancelled, string identityProviderName = null)
        {
            var appContext = Mvx.Resolve <IMvxAndroidGlobals>().ApplicationContext;

            CookieSyncManager.CreateInstance(appContext);

            var manager = CookieManager.Instance;

            if (manager != null)
            {
                manager.SetAcceptCookie(true);
            }

            _onLoggedIn        = onLoggedIn;
            _assumeCancelled   = assumeCancelled;
            _messageHub        = Mvx.Resolve <IMvxMessenger>();
            _subscriptionToken = _messageHub.Subscribe <RequestTokenMessage>(message =>
            {
                _response = message.TokenResponse;
            });

            var intent = new Intent(appContext, typeof(AccessControlWebAuthActivity));

            intent.PutExtra("cheesebaron.mvxplugins.azureaccesscontrol.droid.Url", url);

            StartActivityForResult(LoginIdentityRequestCode, intent);
        }
        public static void CreateIssuedToken(Guid transactionId, string coordinationContextId, ProtocolVersion protocolVersion, out RequestSecurityTokenResponse issuedToken, out string sctId)
        {
            sctId = CoordinationContext.CreateNativeIdentifier(Guid.NewGuid());
            byte[] key = DeriveIssuedTokenKey(transactionId, sctId);
            DateTime utcNow = DateTime.UtcNow;
            SecurityContextSecurityToken token = new SecurityContextSecurityToken(new UniqueId(sctId), key, utcNow, utcNow + TimeSpan.FromDays(36500.0));
            BinarySecretSecurityToken token2 = new BinarySecretSecurityToken(key);
            SecurityStandardsManager standardsManager = CreateStandardsManager(protocolVersion);
            RequestSecurityTokenResponse response = new RequestSecurityTokenResponse(standardsManager) {
                TokenType = standardsManager.SecureConversationDriver.TokenTypeUri,
                RequestedUnattachedReference = SecurityContextSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.External),
                RequestedAttachedReference = SecurityContextSecurityTokenParameters.CreateKeyIdentifierClause(token, SecurityTokenReferenceStyle.Internal),
                RequestedSecurityToken = token,
                RequestedProofToken = token2
            };
            DataContractSerializer serializer = IdentifierElementSerializer(protocolVersion);
            ProtocolVersionHelper.AssertProtocolVersion(protocolVersion, typeof(CoordinationServiceSecurity), "CreateIssuedToken");
            switch (protocolVersion)
            {
                case ProtocolVersion.Version10:
                    response.SetAppliesTo<IdentifierElement10>(new IdentifierElement10(coordinationContextId), serializer);
                    break;

                case ProtocolVersion.Version11:
                    response.SetAppliesTo<IdentifierElement11>(new IdentifierElement11(coordinationContextId), serializer);
                    break;
            }
            response.MakeReadOnly();
            if (DebugTrace.Verbose)
            {
                DebugTrace.Trace(TraceLevel.Verbose, "Created issued token with id {0} for transaction {1}", sctId, transactionId);
            }
            issuedToken = response;
        }
        public void LogIn(
            string url, Action<RequestSecurityTokenResponse> onLoggedIn, Action assumeCancelled,
            string identityProviderName = null)
        {
            var root = Application.Current.RootVisual as Frame;

            _messageHub = Mvx.Resolve<IMvxMessenger>();
            _subscriptionToken = _messageHub.Subscribe<RequestTokenMessage>(message =>
            {
                _response = message.TokenResponse;

                if (_response != null)
                {
                    onLoggedIn(_response);
                }
                else
                {
                    assumeCancelled();
                }

                if (root == null) return;
                if (root.CanGoBack)
                    root.GoBack();
            });

            if (root != null)
            {
                root.Navigate(
                    new Uri(
                        string.Format(
                            "/Cheesebaron.MvxPlugins.AzureAccessControl.WindowsPhone;component/Views/AccessControlWebAuthView.xaml?url={0}&name={1}",
                            WebUtility.UrlEncode(url), WebUtility.UrlEncode(identityProviderName)),
                        UriKind.Relative));
            }
        }
Beispiel #12
0
        private void SignInWebBrowserControl_ScriptNotify(object sender, NotifyEventArgs e)
        {
            RequestSecurityTokenResponse rstr = null;
            Exception exception = null;

            try
            {
                ShowProgressBar("Signing In");

                rstr = RequestSecurityTokenResponse.FromJSON(e.Value);

                if (null == rstr)
                {
                    DisplayErrorMessage("Failed reading RSTR");
                    exception = new InvalidOperationException("Failed to get a valid RequestSecurityTokenResponse");
                }

                if (null != _rstrStore)
                {
                    _rstrStore.RequestSecurityTokenResponse = rstr;
                }
            }
            catch (Exception ex)
            {
                DisplayErrorMessageFromException(ex);
                exception = ex;
            }

            if (null != RequestSecurityTokenResponseCompleted)
            {
                RequestSecurityTokenResponseCompleted(this, new RequestSecurityTokenResponseCompletedEventArgs(rstr, exception));
            }
        }
        public SignInResponseMessage Generate(SignInRequestMessage request, WindowsPrincipal windowsPrincipal)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = SubjectGenerator.Create(windowsPrincipal, _options);

            // create token for user
            var token = CreateSecurityToken(outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(_options.IdpRealm),
                Context   = request.Context,
                ReplyTo   = _options.IdpReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var mgr = SecurityTokenHandlerCollectionManager.CreateEmptySecurityTokenHandlerCollectionManager();

            mgr[SecurityTokenHandlerCollectionManager.Usage.Default] = CreateSupportedSecurityTokenHandler();

            var responseMessage = new SignInResponseMessage(
                new Uri(_options.IdpReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext(mgr));

            return(responseMessage);
        }
        private static string GetWindowsTokenHelper(string windowsAuthSiteEndPoint)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/wstrust/issue/windowstransport"));
            var identityProviderBinding  = new WS2007HttpBinding(SecurityMode.Transport);

            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType     = MessageCredentialType.None;
            identityProviderBinding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.Windows;

            var trustChannelFactory = new WSTrustChannelFactory(identityProviderBinding, identityProviderEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13,
            };

            trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
            {
                CertificateValidationMode = X509CertificateValidationMode.None
            };
            var channel = trustChannelFactory.CreateChannel();

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://azureservices/AdminSite"),
                KeyType   = KeyTypes.Bearer,
            };

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token = null;

            token = channel.Issue(rst, out rstr);
            var tokenString = (token as GenericXmlSecurityToken).TokenXml.InnerText;
            var jwtString   = Encoding.UTF8.GetString(Convert.FromBase64String(tokenString));

            return(jwtString);
        }
Beispiel #15
0
        internal static SecurityToken ComputeProofKey(RequestSecurityToken rst, RequestSecurityTokenResponse rstr)
        {
            if (rstr.Entropy == null)
            {
                throw new NotSupportedException("RSTR entropy is null");
            }
            if (rst.Entropy == null)
            {
                throw new NotSupportedException("RST entropy is null");
            }

            int?keySizeInBits = rst.KeySizeInBits;
            int num           = keySizeInBits.HasValue ? keySizeInBits.GetValueOrDefault() : 0x400;

            if (rstr.KeySizeInBits.HasValue)
            {
                num = rstr.KeySizeInBits.Value;
            }

            return(new BinarySecretSecurityToken(
                       KeyGenerator.ComputeCombinedKey(
                           rst.Entropy.GetKeyBytes(),
                           rstr.Entropy.GetKeyBytes(),
                           num)));
        }
Beispiel #16
0
        /// <summary>
        /// Turns a RST/ProofKey pair into a GenericXmlSecurityToken.
        /// </summary>
        /// <param name="rstr">The RSTR.</param>
        /// <param name="proofKey">The ProofKey.</param>
        /// <returns>A GenericXmlSecurityToken</returns>
        public static GenericXmlSecurityToken ToGenericXmlSecurityToken(this RequestSecurityTokenResponse rstr, SecurityToken proofKey)
        {
            DateTime?created = null;
            DateTime?expires = null;

            if (rstr.Lifetime != null)
            {
                created = rstr.Lifetime.Created;
                expires = rstr.Lifetime.Expires;
                if (!created.HasValue)
                {
                    created = new DateTime?(DateTime.UtcNow);
                }
                if (!expires.HasValue)
                {
                    expires = new DateTime?(DateTime.UtcNow.AddHours(10.0));
                }
            }
            else
            {
                created = new DateTime?(DateTime.UtcNow);
                expires = new DateTime?(DateTime.UtcNow.AddHours(10.0));
            }

            return(new GenericXmlSecurityToken(
                       ExtractTokenXml(rstr),
                       proofKey,
                       created.Value,
                       expires.Value,
                       rstr.RequestedAttachedReference,
                       rstr.RequestedUnattachedReference,
                       new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>())));
        }
Beispiel #17
0
        private XmlElement Complete(X509Certificate2 sessionCert, RequestSecurityTokenResponse response)
        {
            //we expect SignChallenge, which we need to return as SignChallengeResponse using the body cert/key.
            if (response.RequestSecurityTokenResponse1.SignChallenge == null)
            {
                throw new InvalidOperationException("eHealth WS-Trust service didn't return sign challenge response");
            }
            response.RequestSecurityTokenResponse1.SignChallengeResponse = response.RequestSecurityTokenResponse1.SignChallenge;
            response.RequestSecurityTokenResponse1.SignChallenge         = null;

            //create a secondary channel to send the challenge
            ChannelFactory <IWsTrustPortFixed> channelFactory = new ChannelFactory <IWsTrustPortFixed>(base.Endpoint.Binding, base.Endpoint.Address);

            channelFactory.Credentials.ClientCertificate.Certificate = sessionCert;
            IWsTrustPortFixed secondary = channelFactory.CreateChannel();

            //send the (signed) Challenge, get the reponse as message to not break the internal signature
            Message responseMsg = secondary.Challenge(response);

            if (responseMsg.IsFault)
            {
                throw new FaultException(MessageFault.CreateFault(responseMsg, 10240), responseMsg.Headers.Action);
            }
            var responseBody = new XmlDocument();

            responseBody.PreserveWhitespace = true;
            responseBody.Load(responseMsg.GetReaderAtBodyContents());

            //better to check if correcty wrapped, but for now we do not care.

            return((XmlElement)responseBody.GetElementsByTagName("Assertion", "urn:oasis:names:tc:SAML:1.0:assertion")[0]);
        }
Beispiel #18
0
        public virtual void ApplyTo(RequestSecurityTokenResponse response)
        {
            if (TokenType != null)
            {
                response.TokenType = TokenType;
            }

            if (TokenElement != null)
            {
                response.RequestedSecurityToken = new RequestedSecurityToken(TokenElement)
                {
                    SecurityToken = Token
                };
            }
            else if (Token != null)
            {
                response.RequestedSecurityToken = new RequestedSecurityToken(Token);
            }

            if (AttachedReference != null)
            {
                response.AttachedReference = AttachedReference;
            }

            if (UnattachedReference != null)
            {
                response.UnattachedReference = UnattachedReference;
            }

            if (IssuedAt != null && Expires != null)
            {
                response.Lifetime = new Lifetime(IssuedAt, Expires);
            }
        }
Beispiel #19
0
        private static string GetTokenFromAdfs20()
        {
            var binding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var address = new EndpointAddress(
                new Uri(@"https://yourserver.com/adfs/services/trust/13/usernamemixed"));

            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******";

            WSTrustChannel channel = (WSTrustChannel)factory.CreateChannel();

            var request = new RequestSecurityToken(System.IdentityModel.Protocols.WSTrust.RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("https://relyingparty"),
                KeyType   = KeyTypes.Bearer
            };

            RequestSecurityTokenResponse response = null;
            var token = channel.Issue(request, out response) as GenericXmlSecurityToken;

            return(token.TokenXml.OuterXml);
        }
Beispiel #20
0
        private bool ShouldStartLoad(UIWebView webView, NSUrlRequest request, UIWebViewNavigationType navigationType)
        {
            if (Url != null && request.Url.Equals(Url))
            {
                return(true);
            }

            Url = request.Url;

            if (Url.Scheme.Equals("acs"))
            {
                var b = new StringBuilder(Uri.UnescapeDataString(request.Url.ToString()));
                b.Replace("acs://settoken?token=", string.Empty);

                var token = RequestSecurityTokenResponse.FromJSON(b.ToString());
                _messageHub.Publish(new RequestTokenMessage(this)
                {
                    TokenResponse = token
                });

                DismissViewController(true, null);
            }

            NSUrlConnection.FromRequest(request, new LoginConnectionDelegate(this));

            return(false);
        }
Beispiel #21
0
            private SecurityToken GetTokenFromSts(out RequestSecurityTokenResponse rstr)
            {
                int           num = 3;
                SecurityToken result;

                while (true)
                {
                    try
                    {
                        if (this.username == null && this.password == null)
                        {
                            result = this.GetLoggedInUserToken(out rstr);
                            break;
                        }
                        result = this.GetImpersonatedUserToken(out rstr);
                        break;
                    }
                    catch (TimeoutException)
                    {
                        if (--num == 0)
                        {
                            throw;
                        }
                    }
                    catch (ServerTooBusyException)
                    {
                        if (--num == 0)
                        {
                            throw;
                        }
                    }
                }
                return(result);
            }
Beispiel #22
0
        private static Tuple <string, byte[]> GetToken()
        {
            var binding = new WS2007HttpBinding(SecurityMode.Message);

            binding.Security.Message.ClientCredentialType       = MessageCredentialType.UserName;
            binding.Security.Message.NegotiateServiceCredential = true;
            binding.Security.Message.EstablishSecurityContext   = false;

            var address = new EndpointAddress(new Uri(@"http://localhost:6000/MySTS"),
                                              new DnsEndpointIdentity("MySTS"));

            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode =
                X509CertificateValidationMode.None;
            factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            factory.Credentials.UserName.UserName = "******";
            factory.Credentials.UserName.Password = "******"; // got to be same as user name in our example

            WSTrustChannel channel = (WSTrustChannel)factory.CreateChannel();

            var request = new RequestSecurityToken(System.IdentityModel.Protocols.WSTrust.RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://my-server.com")
            };

            RequestSecurityTokenResponse response = null;
            var token = channel.Issue(request, out response) as GenericXmlSecurityToken;

            var proofKey = response.RequestedProofToken.ProtectedKey.GetKeyBytes();

            return(new Tuple <string, byte[]>(token.TokenXml.OuterXml, proofKey));
        }
Beispiel #23
0
        public string GetToken(string idpEndpoint, string rstsRealm)
        {
            var binding = new WindowsWSTrustBinding(SecurityMode.TransportWithMessageCredential);

            var factory = new System.ServiceModel.Security.WSTrustChannelFactory(binding, new EndpointAddress(new Uri(idpEndpoint)));

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;

            var rst = new System.IdentityModel.Protocols.WSTrust.RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new System.IdentityModel.Protocols.WSTrust.EndpointReference(rstsRealm),
                KeyType     = KeyTypes.Bearer,
                TokenType   = "urn:oasis:names:tc:SAML:1.0:assertion" // "urn:oasis:names:tc:SAML:2.0:assertion"
            };

            var channel = factory.CreateChannel();
            RequestSecurityTokenResponse response = null;

            try {
                var securityToken = channel.Issue(rst, out response);
                return(Serialize(response));
            }catch
            {
                var x = response;
            }
            return(null);
        }
Beispiel #24
0
        /// <summary>
        /// Reads the 'wresult' and returns the embeded security token.
        /// </summary>
        /// <returns>the 'SecurityToken'.</returns>
        public virtual string GetToken()
        {
            if (Wresult == null)
            {
                IdentityModelEventSource.Logger.WriteWarning(string.Format(CultureInfo.InvariantCulture, LogMessages.IDX10000, "wresult"));
                return(null);
            }

            using (StringReader sr = new StringReader(Wresult))
            {
                XmlReader xmlReader = XmlReader.Create(sr);
                xmlReader.MoveToContent();

                WSTrustResponseSerializer serializer = new WSTrust13ResponseSerializer();
                if (serializer.CanRead(xmlReader))
                {
                    RequestSecurityTokenResponse response = serializer.ReadXml(xmlReader, new WSTrustSerializationContext());
                    return(response.RequestedSecurityToken.SecurityTokenXml.OuterXml);
                }

                serializer = new WSTrustFeb2005ResponseSerializer();
                if (serializer.CanRead(xmlReader))
                {
                    RequestSecurityTokenResponse response = serializer.ReadXml(xmlReader, new WSTrustSerializationContext());
                    return(response.RequestedSecurityToken.SecurityTokenXml.OuterXml);
                }
            }

            return(null);
        }
        private TransactionContext CreateTransactionContext()
        {
            Microsoft.Transactions.Bridge.EnlistmentOptions enlistmentOptions = this.enlistment.EnlistmentOptions;
            string remoteTransactionId  = this.enlistment.RemoteTransactionId;
            Guid   localTransactionId   = this.enlistment.LocalTransactionId;
            CoordinationContext context = new CoordinationContext(this.state.ProtocolVersion)
            {
                Expires            = (enlistmentOptions.Expires == TimeSpan.MaxValue) ? uint.MaxValue : ((uint)((int)enlistmentOptions.Expires.TotalMilliseconds)),
                Identifier         = remoteTransactionId,
                LocalTransactionId = localTransactionId,
                IsolationLevel     = enlistmentOptions.IsoLevel,
                IsolationFlags     = enlistmentOptions.IsolationFlags,
                Description        = enlistmentOptions.Description
            };
            string contextId = CoordinationContext.IsNativeIdentifier(remoteTransactionId, localTransactionId) ? null : remoteTransactionId;
            string sctId     = null;
            RequestSecurityTokenResponse issuedToken = null;

            if (this.state.Config.PortConfiguration.SupportingTokensEnabled)
            {
                CoordinationServiceSecurity.CreateIssuedToken(localTransactionId, remoteTransactionId, this.state.ProtocolVersion, out issuedToken, out sctId);
            }
            AddressHeader refParam = new WsatRegistrationHeader(localTransactionId, contextId, sctId);

            context.RegistrationService = this.state.RegistrationCoordinatorListener.CreateEndpointReference(refParam);
            return(new TransactionContext(context, issuedToken));
        }
        public GenericXmlSecurityToken DeserializeTokenFromRstr(RequestSecurityTokenResponse rstr)
        {
            SecurityToken proofKey = null;
            DateTime?     created  = null;
            DateTime?     expires  = null;

            if (rstr.Lifetime != null)
            {
                created = rstr.Lifetime.Created;
                expires = rstr.Lifetime.Expires;
            }
            if (!created.HasValue)
            {
                throw new Exception("Created unspecified");
            }
            if (!expires.HasValue)
            {
                throw new Exception("Expires unspecified");
            }

            GenericXmlSecurityToken securityToken = new GenericXmlSecurityToken(
                rstr.RequestedSecurityToken.SecurityTokenXml,
                proofKey,
                created.Value,
                expires.Value,
                rstr.RequestedAttachedReference,
                rstr.RequestedUnattachedReference,
                new ReadOnlyCollection <IAuthorizationPolicy>(new List <IAuthorizationPolicy>())
                );

            return(securityToken);
        }
Beispiel #27
0
        /// <summary>
        /// Call the STS to get an appropriate token for a request and build a response.
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <returns>The <see cref="SignInResponseMessage"/></returns>
        private SignInResponseMessage ProcessSignInRequest(SignInRequestMessage requestMessage)
        {
            // Ensure that the requestMessage has the required wtrealm parameter
            if (String.IsNullOrEmpty(requestMessage.Realm))
            {
                throw new InvalidOperationException("Missing realm");
            }

            SecurityTokenServiceConfiguration stsconfig = new SecurityTokenServiceConfiguration("PassiveFlowSTS");

            // Create our STS backend
            SecurityTokenService sts = new CustomSecurityTokenService(stsconfig);

            // Create the WS-Federation serializer to process the request and create the response
            WSFederationSerializer federationSerializer = new WSFederationSerializer();

            // Create RST from the request
            RequestSecurityToken request = federationSerializer.CreateRequest(requestMessage, new WSTrustSerializationContext());

            // Get RSTR from our STS backend
            RequestSecurityTokenResponse response = sts.Issue((ClaimsPrincipal)Thread.CurrentPrincipal, request);

            // Create Response message from the RSTR
            return(new SignInResponseMessage(new Uri(response.ReplyTo),
                                             federationSerializer.GetResponseAsString(response, new WSTrustSerializationContext())));
        }
        public async Task <SignInResponseMessage> GenerateResponseAsync(SignInValidationResult validationResult)
        {
            Logger.Info("Creating WS-Federation signin response");

            // create subject
            var outgoingSubject = await CreateSubjectAsync(validationResult);

            // create token for user
            var token = CreateSecurityToken(validationResult, outgoingSubject);

            // return response
            var rstr = new RequestSecurityTokenResponse
            {
                AppliesTo = new EndpointReference(validationResult.RelyingParty.Realm),
                Context   = validationResult.SignInRequestMessage.Context,
                ReplyTo   = validationResult.ReplyUrl,
                RequestedSecurityToken = new RequestedSecurityToken(token)
            };

            var serializer = new WSFederationSerializer(
                new WSTrust13RequestSerializer(),
                new WSTrust13ResponseSerializer());

            var responseMessage = new SignInResponseMessage(
                new Uri(validationResult.ReplyUrl),
                rstr,
                serializer,
                new WSTrustSerializationContext());

            return(responseMessage);
        }
        /// <summary>
        /// Reads the 'wresult' and returns the embeded security token.
        /// </summary>
        /// <returns>the 'SecurityToken'.</returns>
        public virtual string GetToken()
        {
            if (Wresult == null)
            {
                return(null);
            }

            using (StringReader sr = new StringReader(Wresult))
            {
                XmlReader xmlReader = XmlReader.Create(sr);
                xmlReader.MoveToContent();

                WSTrustResponseSerializer serializer = new WSTrust13ResponseSerializer();
                if (serializer.CanRead(xmlReader))
                {
                    RequestSecurityTokenResponse response = serializer.ReadXml(xmlReader, new WSTrustSerializationContext());
                    return(response.RequestedSecurityToken.SecurityTokenXml.OuterXml);
                }

                serializer = new WSTrustFeb2005ResponseSerializer();
                if (serializer.CanRead(xmlReader))
                {
                    RequestSecurityTokenResponse response = serializer.ReadXml(xmlReader, new WSTrustSerializationContext());
                    return(response.RequestedSecurityToken.SecurityTokenXml.OuterXml);
                }
            }

            return(null);
        }
        private async void SignInWebBrowserControlScriptNotify(object sender, NotifyEventArgs e)
        {
            BrowserSignInControl.ScriptNotify -= SignInWebBrowserControlScriptNotify;
            GdProgress.Visibility              = Visibility.Visible;
            try
            {
                var rswt = await RequestSecurityTokenResponse.FromJSONAsync(e.Value);

                _messageHub.Publish(rswt == null
                    ? new RequestTokenMessage(this)
                {
                    TokenResponse = null
                }
                    : new RequestTokenMessage(this)
                {
                    TokenResponse = rswt
                });
            }
            catch (Exception)
            {
                _timeoutTimer.Stop();
                _messageHub.Publish(new RequestTokenMessage(this)
                {
                    TokenResponse = null
                });
            }
        }
        protected override void OnActivityResult(int requestCode, Result resultCode, Intent data)
        {
            // We've got a result from the webactivity
            if (WEB_AUTH_ACTIVITY == requestCode && Result.Ok == resultCode)
            {
                var requestSecurityTokenResponse = data.GetStringExtra("monodroid.watoolkit.library.login.RequestSecurityTokenResponse");
                // Lets try parse it!
                var token = RequestSecurityTokenResponse.FromJSON(requestSecurityTokenResponse);
                RequestSecurityTokenResponseStore.Instance.RequestSecurityTokenResponse = token;

                if (Parent == null)
                {
                    SetResult(Result.Ok);
                }
                else
                {
                    Parent.SetResult(Result.Ok);
                }
                Finish();
            }
            // Something bad happened (or we pressed back!) and we did not get the Token :-/
            else if (WEB_AUTH_ACTIVITY == requestCode && Result.Canceled == resultCode)
            {
                ShowAlertDialog("An error occured!", "Could not retrieve security token, please try again");
            }
        }
 public CreateCoordinationContext(Message message, Microsoft.Transactions.Wsat.Protocol.ProtocolVersion protocolVersion) : this(protocolVersion)
 {
     if (message.IsEmpty)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidMessageException(Microsoft.Transactions.SR.GetString("InvalidMessageBody")));
     }
     XmlDictionaryReader readerAtBodyContents = message.GetReaderAtBodyContents();
     using (readerAtBodyContents)
     {
         this.ReadFrom(readerAtBodyContents);
         try
         {
             message.ReadFromBodyContentsToEnd(readerAtBodyContents);
         }
         catch (XmlException exception)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidMessageException(Microsoft.Transactions.SR.GetString("InvalidMessageBody"), exception));
         }
     }
     if (this.CurrentContext != null)
     {
         try
         {
             this.IssuedToken = CoordinationServiceSecurity.GetIssuedToken(message, this.CurrentContext.Identifier, protocolVersion);
         }
         catch (XmlException exception2)
         {
             throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidMessageException(exception2.Message, exception2));
         }
     }
 }
 public static void AddIssuedToken(Message message, RequestSecurityTokenResponse rstr)
 {
     TransactionFlowProperty.Ensure(message).IssuedTokens.Add(rstr);
     if (DebugTrace.Verbose)
     {
         DebugTrace.Trace(TraceLevel.Verbose, "Added issued token to message");
     }
 }
 public CreateCoordinationContextResponse(Microsoft.Transactions.Wsat.Protocol.ProtocolVersion protocolVersion)
 {
     this.CoordinationContext = null;
     this.IssuedToken = null;
     this.protocolVersion = protocolVersion;
     this.coordinationStrings = CoordinationStrings.Version(protocolVersion);
     this.coordinationXmlDictionaryStrings = CoordinationXmlDictionaryStrings.Version(protocolVersion);
 }
 public WsatTransactionInfo(WsatProxy wsatProxy,
                            CoordinationContext context,
                            RequestSecurityTokenResponse issuedToken)
 {
     this.wsatProxy   = wsatProxy;
     this.context     = context;
     this.issuedToken = issuedToken;
 }
 public WsatTransactionInfo(WsatProxy wsatProxy, 
                            CoordinationContext context,
                            RequestSecurityTokenResponse issuedToken)
 {
     this.wsatProxy = wsatProxy;
     this.context = context;
     this.issuedToken = issuedToken;
 }
 public static void AddIssuedToken(Message message, RequestSecurityTokenResponse rstr)
 {
     TransactionFlowProperty.Ensure(message).IssuedTokens.Add(rstr);
     if (DebugTrace.Verbose)
     {
         DebugTrace.Trace(TraceLevel.Verbose, "Added issued token to message");
     }
 }
 public CoordinatorEnlistment(ProtocolState state, TransactionContextManager contextManager, CoordinationContext context, RequestSecurityTokenResponse rstr) : base(state)
 {
     base.ourContextManager = contextManager;
     this.superiorContext = context;
     this.superiorRstr = rstr;
     this.ConfigureEnlistment(context);
     base.stateMachine = new CoordinatorStateMachine(this);
     base.stateMachine.ChangeState(state.States.CoordinatorInitializing);
 }
        /// <summary>
        /// Requests a token desribed by an RST.
        /// </summary>
        /// <param name="stsAddress">The STS address.</param>
        /// <param name="binding">The binding.</param>
        /// <param name="credentials">The credentials.</param>
        /// <param name="rst">The RST.</param>
        /// <param name="rstr">The RSTR.</param>
        /// <returns>A SecurityToken</returns>
        public static SecurityToken Issue(EndpointAddress stsAddress, Binding binding, ClientCredentials credentials, RequestSecurityToken rst, out RequestSecurityTokenResponse rstr)
        {
            var channel = CreateWSTrustChannel(
                stsAddress,
                binding,
                credentials);

            var token = channel.Issue(rst, out rstr);
            return token;
        }
 public Register(Microsoft.Transactions.Wsat.Protocol.ProtocolVersion protocolVersion)
 {
     this.Protocol = ControlProtocol.None;
     this.ParticipantProtocolService = null;
     this.Loopback = Guid.Empty;
     this.SupportingToken = null;
     this.protocolVersion = protocolVersion;
     this.coordinationStrings = CoordinationStrings.Version(protocolVersion);
     this.coordinationXmlDictionaryStrings = CoordinationXmlDictionaryStrings.Version(protocolVersion);
 }
 public IssuedTokensHeader(RequestSecurityTokenResponse tokenIssuance, SecurityStandardsManager standardsManager)
     : base()
 {
     if (tokenIssuance == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("tokenIssuance");
     }
     Collection<RequestSecurityTokenResponse> coll = new Collection<RequestSecurityTokenResponse>();
     coll.Add(tokenIssuance);
     Initialize(coll, standardsManager);
 }
 public void MarshalAsCoordinationContext(Transaction transaction, out CoordinationContext context, out RequestSecurityTokenResponse issuedToken)
 {
     uint num;
     IsolationFlags flags;
     string str2;
     WsatExtendedInformation information;
     string str3;
     Guid distributedIdentifier = transaction.TransactionInformation.DistributedIdentifier;
     string contextId = null;
     context = new CoordinationContext(this.protocolVersion);
     OleTxTransactionFormatter.GetTransactionAttributes(transaction, out num, out flags, out str2);
     context.IsolationFlags = flags;
     context.Description = str2;
     if (TransactionCache<Transaction, WsatExtendedInformation>.Find(transaction, out information))
     {
         context.Expires = information.Timeout;
         if (!string.IsNullOrEmpty(information.Identifier))
         {
             context.Identifier = information.Identifier;
             contextId = information.Identifier;
         }
     }
     else
     {
         context.Expires = num;
         if (context.Expires == 0)
         {
             context.Expires = (uint) TimeoutHelper.ToMilliseconds(this.wsatConfig.MaxTimeout);
         }
     }
     if (context.Identifier == null)
     {
         context.Identifier = CoordinationContext.CreateNativeIdentifier(distributedIdentifier);
         contextId = null;
     }
     if (!this.wsatConfig.IssuedTokensEnabled)
     {
         str3 = null;
         issuedToken = null;
     }
     else
     {
         CoordinationServiceSecurity.CreateIssuedToken(distributedIdentifier, context.Identifier, this.protocolVersion, out issuedToken, out str3);
     }
     AddressHeader refParam = new WsatRegistrationHeader(distributedIdentifier, contextId, str3);
     context.RegistrationService = this.wsatConfig.CreateRegistrationService(refParam, this.protocolVersion);
     context.IsolationLevel = transaction.IsolationLevel;
     context.LocalTransactionId = distributedIdentifier;
     if (this.wsatConfig.OleTxUpgradeEnabled)
     {
         context.PropagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction);
     }
 }
 public static void AddSupportingToken(Message message, RequestSecurityTokenResponse rstr)
 {
     GenericXmlSecurityToken token = rstr.GetIssuedToken(null, null, SecurityKeyEntropyMode.ServerEntropy, null, null, null);
     SecurityMessageProperty property = new SecurityMessageProperty();
     SupportingTokenSpecification item = new SupportingTokenSpecification(token, new List<IAuthorizationPolicy>().AsReadOnly(), SecurityTokenAttachmentMode.Endorsing, SecurityContextSecurityTokenParameters);
     property.OutgoingSupportingTokens.Add(item);
     message.Properties.Security = property;
     if (DebugTrace.Verbose)
     {
         DebugTrace.Trace(TraceLevel.Verbose, "Attached supporting token {0} to register message", rstr.Context);
     }
 }
 public CreateCoordinationContext(Microsoft.Transactions.Wsat.Protocol.ProtocolVersion protocolVersion)
 {
     this.expiration = 0;
     this.expiresPresent = false;
     this.CurrentContext = null;
     this.IssuedToken = null;
     this.IsolationLevel = System.Transactions.IsolationLevel.Serializable;
     this.protocolVersion = protocolVersion;
     this.coordinationXmlDictionaryStrings = CoordinationXmlDictionaryStrings.Version(protocolVersion);
     this.atomicTransactionXmlDictionaryStrings = AtomicTransactionXmlDictionaryStrings.Version(protocolVersion);
     this.atomicTransactionStrings = AtomicTransactionStrings.Version(protocolVersion);
     this.coordinationStrings = CoordinationStrings.Version(protocolVersion);
 }
        public void LogIn(string url, Action<RequestSecurityTokenResponse> onLoggedIn, Action assumeCancelled, string identityProviderName = null)
        {
            _onLoggedIn = onLoggedIn;
            _assumeCancelled = assumeCancelled;
            _messageHub = Mvx.Resolve<IMvxMessenger>();
            _subscriptionToken = _messageHub.Subscribe<RequestTokenMessage>(message =>
            {
                _response = message.TokenResponse;
            });

            var intent = new Intent(Mvx.Resolve<IMvxAndroidGlobals>()
                .ApplicationContext, typeof(AccessControlWebAuthActivity));
            intent.PutExtra("cheesebaron.mvxplugins.azureaccesscontrol.droid.Url", url);

            StartActivityForResult(LoginIdentityRequestCode, intent);
        }
 public IssuedTokensHeader(RequestSecurityTokenResponse tokenIssuance, MessageSecurityVersion version, SecurityTokenSerializer tokenSerializer)
     : this(tokenIssuance, new SecurityStandardsManager(version, tokenSerializer))
 {
 }
        /// <summary>
        /// Checks the authentication.
        /// </summary>
        /// <param name="claimsPrincipal">The claims principal.</param>
        public void CheckAuthentication( IClaimsPrincipal claimsPrincipal )
        {
            var bootStrapToken = ( from ident in claimsPrincipal.Identities
                                             where ident.BootstrapToken != null && ident.BootstrapToken is SamlSecurityToken
                                             select ident.BootstrapToken ).FirstOrDefault ();

            var responseSerializer = new WSTrust13ResponseSerializer ();
            var requestSecurityTokenResponse = new RequestSecurityTokenResponse
                {
                    AppliesTo = new EndpointAddress ( "https://localhost/Rem.Web" ),
                    Context = "passive",
                    Lifetime = new Lifetime ( bootStrapToken.ValidFrom, bootStrapToken.ValidTo ),
                    RequestedSecurityToken = new RequestedSecurityToken ( bootStrapToken ),
                    TokenType = Saml2SecurityTokenHandler.TokenProfile11ValueType,
                    RequestType = WSTrust13Constants.RequestTypes.Issue,
                    KeyType = WSTrust13Constants.KeyTypes.Bearer
                };

            string content;
            using ( var swriter = new StringWriter () )
            {
                using ( var xmlWriter = XmlWriter.Create ( swriter ) )
                {
                    responseSerializer.WriteXml (
                        requestSecurityTokenResponse,
                        xmlWriter,
                        new WSTrustSerializationContext () );
                    xmlWriter.Flush ();
                    swriter.Flush ();
                    var xmlString = swriter.ToString ().Replace ( "<?xml version=\"1.0\" encoding=\"utf-16\"?>", "" );
                    content = string.Format (
                        "wa=wsignin1.0&wresult={0}&wctx=rm%3D0%26id%3Dpassive%26ru%3D%252fRem.Web%252f",
                        HttpContext.Current.Server.UrlEncode ( xmlString ) );
                }
            }
            var currentHttpRequest = HttpContext.Current.Request;

            var cookieContainer = new CookieContainer ();
            //foreach (string cookieName in currentHttpRequest.Cookies)
            //{
            //    var httpcookie = currentHttpRequest.Cookies[cookieName];
            //    var cookie = new Cookie(cookieName, httpcookie.Value, httpcookie.Path, httpcookie.Domain ?? "localhost");
            //    cookieContainer.Add(cookie);
            //}

            var appSettingsConfiguration = new AppSettingsConfiguration ();
            var remWebApplicationAddress = appSettingsConfiguration.GetProperty ( "RemWebApplicationAddress" );
            var request = ( HttpWebRequest )WebRequest.CreateDefault ( new Uri ( remWebApplicationAddress ) );
            request.Method = currentHttpRequest.HttpMethod;
            request.CookieContainer = cookieContainer;
            request.ContentType = currentHttpRequest.ContentType;
            request.Accept = string.Empty;
            foreach ( var acceptType in currentHttpRequest.AcceptTypes )
            {
                request.Accept += acceptType;
                if ( acceptType != currentHttpRequest.AcceptTypes.Last () )
                {
                    request.Accept += ", ";
                }
            }
            request.ContentLength = content.Length;
            request.Referer = currentHttpRequest.UrlReferrer.AbsoluteUri.Replace ( "Rem.Mvc", "Rem.Web" );
            request.AllowAutoRedirect = false;
            using ( var streamWriter = new StreamWriter ( request.GetRequestStream () ) )
            {
                streamWriter.Write ( content );
            }
            try
            {
                var response = ( HttpWebResponse )request.GetResponse ();
                while ( response.StatusCode == HttpStatusCode.Found )
                {
                    response.Close ();
                    var location = response.Headers["Location"];
                    if ( !location.StartsWith ( "http" ) )
                    {
                        location = string.Format ( "{0}://{1}", request.RequestUri.Scheme, request.RequestUri.Host ) + location;
                    }
                    request = GetNewRequest ( location, cookieContainer );

                    response = ( HttpWebResponse )request.GetResponse ();
                }
                if ( response.StatusCode != HttpStatusCode.OK )
                {
                    throw new Exception ( "Failed authentication." );
                }
                var cookieStringBuilder = new StringBuilder ();
                foreach ( Cookie cookie in cookieContainer.GetCookies ( new Uri ( "https://localhost" ) ) )
                {
                    if ( cookie.Name.StartsWith ( "FedAuth" ) )
                    {
                        HttpContext.Current.Response.Cookies.Add ( new HttpCookie ( "Server" + cookie.Name, cookie.Value ) );
                        cookieStringBuilder.Append ( cookie.Value );
                    }
                    if ( cookie.Name == "ASP.NET_SessionId" )
                    {
                        HttpContext.Current.Response.Cookies.Add ( new HttpCookie ( cookie.Name, cookie.Value ) );
                    }
                }
            }
            catch ( Exception e )
            {
                throw;
            }
        }
Beispiel #48
0
        private string SerializeResponse(RequestSecurityTokenResponse response)
        {
            var serializer = new WSTrust13ResponseSerializer();
            var context = new WSTrustSerializationContext(FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlerCollectionManager);
            var sb = new StringBuilder(128);

            using (var writer = XmlWriter.Create(new StringWriter(sb)))
            {
                serializer.WriteXml(response, writer, context);
                return sb.ToString();
            }
        }
        protected virtual void OnLoggedIn(RequestSecurityTokenResponse requestSecurityTokenResponse)
        {
            if (requestSecurityTokenResponse == null)
            {
                Mvx.TaggedTrace(MvxTraceLevel.Error, "DefaultIdentityProviderCollectionViewModel", "Got an empty response from IdentityProvider");
                return;
            }
            
            var simpleWebToken = Mvx.Resolve<ISimpleWebToken>().CreateTokenFromRaw(requestSecurityTokenResponse.SecurityToken);
            _simpleWebTokenStore.SimpleWebToken = simpleWebToken;

            RaisePropertyChanged("IsLoggedIn");
            RaisePropertyChanged("LoggedInProvider");

            if (IsLoggedIn)
                NavigateBackCommand.Execute(null);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="response"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public String GetResponseAsString(RequestSecurityTokenResponse response, WSTrustSerializationContext context)
        {
            if (null == response)
                throw new ArgumentNullException("response");
            if (null == context)
                throw new ArgumentNullException("context");

            StringBuilder sb = new StringBuilder();
            using (StringWriter stringWriter = new StringWriter(sb, CultureInfo.InvariantCulture))
            {
                using (XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter))
                {
                    responseSerializer.WriteXml(response, xmlWriter, context);
                }
            }
            return sb.ToString();
        }
        private static SecurityToken ConvertToSimpleWebToken(SecurityToken token, RequestSecurityTokenResponse response)
        {
            ClaimsIdentityCollection claims = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.ValidateToken(token);

            var values = new Dictionary<String, String>();
            foreach (var claim in claims[0].Claims)
                values[claim.ClaimType] = claim.Value;
            values[WrapConstants.SimpleWebTokenParameters.Issuer] = "issuer";
            values[WrapConstants.SimpleWebTokenParameters.Audience] = response.AppliesTo.Uri.ToString();

            var config = SimpleWebTokenConfigurationSection.Instance;
            return new SimpleWebToken(values, token.ValidTo, new Sha256SigningCredentials(config.GetKey()));
        }
 //=======================================================================================
 public WsatTransactionInfo CreateTransactionInfo(CoordinationContext context,
                                                  RequestSecurityTokenResponse issuedToken)
 {
     return new WsatTransactionInfo(this.wsatProxy, context, issuedToken);
 }
        //=======================================================================================
        // The demand is not added now (in 4.5), to avoid a breaking change. To be considered in the next version.
        /*
        // We demand full trust because we use CoordinationContext and CoordinationServiceSecurity from a non-APTCA assembly.
        // The CoordinationContext constructor can call Environment.FailFast and it's recommended to not let partially trusted callers to bring down the process.
        // WSATs are not supported in partial trust, so customers should not be broken by this demand.
        [PermissionSet(SecurityAction.Demand, Unrestricted = true)]
        */
        public void MarshalAsCoordinationContext(Transaction transaction,
                                                 out CoordinationContext context,
                                                 out RequestSecurityTokenResponse issuedToken)
        {
            Guid transactionId = transaction.TransactionInformation.DistributedIdentifier;
            string nonNativeContextId = null;

            context = new CoordinationContext(this.protocolVersion);

            // Get timeout, description and isolation flags
            uint timeout;
            IsolationFlags isoFlags;
            string description;
            OleTxTransactionFormatter.GetTransactionAttributes(transaction,
                                                               out timeout,
                                                               out isoFlags,
                                                               out description);
            context.IsolationFlags = isoFlags;
            context.Description = description;

            // If we can, use cached extended information
            // Note - it may be worth using outgoing contexts more than once.
            // We'll let performance profiling decide that question
            WsatExtendedInformation info;
            if (WsatExtendedInformationCache.Find(transaction, out info))
            {
                context.Expires = info.Timeout;

                // The extended info cache only contains an identifier when it's non-native
                if (!string.IsNullOrEmpty(info.Identifier))
                {
                    context.Identifier = info.Identifier;
                    nonNativeContextId = info.Identifier;
                }
            }
            else
            {
                context.Expires = timeout;
                if (context.Expires == 0)
                {
                    // If the timeout is zero, there are two possibilities:
                    // 1) This is a root transaction with an infinite timeout.
                    // 2) This is a subordinate transaction whose timeout was not flowed.
                    // We have no mechanism for distinguishing between the two cases.
                    //
                    // We could always return zero here, instead of using the local max timeout.
                    // The problem is that the 2004/08 WS-C spec does not specify the meaning
                    // of a zero expires field. While we accept zero to mean "as large as possible"
                    // it would be risky to expect others to do the same.  So we only propagate
                    // zero in the expires field if the local max timeout has been disabled.
                    //
                    // This is MB 34596: how can we flow the real timeout?
                    context.Expires = (uint)TimeoutHelper.ToMilliseconds(this.wsatConfig.MaxTimeout);
                }
            }

            if (context.Identifier == null)
            {
                context.Identifier = CoordinationContext.CreateNativeIdentifier(transactionId);
                nonNativeContextId = null;
            }

            string tokenId;
            if (!this.wsatConfig.IssuedTokensEnabled)
            {
                tokenId = null;
                issuedToken = null;
            }
            else
            {
                CoordinationServiceSecurity.CreateIssuedToken(transactionId,
                                                              context.Identifier,
                                                              this.protocolVersion,
                                                              out issuedToken,
                                                              out tokenId);
            }

            AddressHeader refParam = new WsatRegistrationHeader(transactionId, nonNativeContextId, tokenId);
            context.RegistrationService = wsatConfig.CreateRegistrationService(refParam, this.protocolVersion);
            context.IsolationLevel = transaction.IsolationLevel;
            context.LocalTransactionId = transactionId;

            if (this.wsatConfig.OleTxUpgradeEnabled)
            {
                context.PropagationToken = TransactionInterop.GetTransmitterPropagationToken(transaction);
            }
        }
 public TransactionContext(Microsoft.Transactions.Wsat.Messaging.CoordinationContext context, RequestSecurityTokenResponse issuedToken)
 {
     this.context = context;
     this.issuedToken = issuedToken;
 }
        /// <summary>
        /// Get Claims Principal from incoming response.
        /// </summary>
        /// <param name="rstr"></param>
        /// <returns></returns>
        private static IClaimsPrincipal GetClaimsIdentity(RequestSecurityTokenResponse rstr)
        {
            var rstrXml = rstr.RequestedSecurityToken.SecurityTokenXml;

            if (rstrXml.OwnerDocument != null)
            {
                var xnm = new XmlNamespaceManager(rstrXml.OwnerDocument.NameTable);

                xnm.AddNamespace(Microsoft.IdentityModel.Tokens.Saml2.Saml2Constants.Prefix, Microsoft.IdentityModel.Tokens.Saml2.Saml2Constants.Namespace);
            }

            XNamespace ast = "urn:oasis:names:tc:SAML:2.0:assertion";
            var xElement = ToXElement(rstrXml);

            var xElement1 = xElement.Element(ast + "Assertion");
            if (xElement1 != null)
            {
                var attributeStatement1 = xElement1.Element(ast + "AttributeStatement");
                if (attributeStatement1 != null)
                {
                    var attributes1 = attributeStatement1.Elements(ast + "Attribute");
                    IClaimsIdentity claimsIdentity1 = new ClaimsIdentity();
                    foreach (var element in attributes1)
                    {
                        var claimType = element.Attribute("NameFormat") + "/" + element.Attribute("Name");
                        var value = element.Value;

                        var xAttribute = element.Attribute("Name");
                        if (xAttribute != null && xAttribute.Value == "urn:FirstName")
                            claimsIdentity1.Claims.Add(new Claim(ClaimTypes.Name, element.Value));
                        claimsIdentity1.Claims.Add(new Claim(claimType, value));
                    }
                    var claimsIdentitycol = new ClaimsIdentityCollection(new[] { claimsIdentity1 });
                    return ClaimsPrincipal.CreateFromIdentities(claimsIdentitycol);
                }
            }
            return null;
        }
        protected virtual void OnLoggedIn(RequestSecurityTokenResponse requestSecurityTokenResponse)
        {
            if (requestSecurityTokenResponse == null)
            {
                Mvx.TaggedTrace(MvxTraceLevel.Error, "DefaultIdentityProviderCollectionViewModel", "Got an empty response from IdentityProvider");
                return;
            }

            RaisePropertyChanged("IsLoggedIn");
            RaisePropertyChanged("LoggedInProvider");

            if (IsLoggedIn)
                NavigateBackCommand.Execute(null);
        }
        internal static SecurityToken ComputeProofKey(RequestSecurityToken rst, RequestSecurityTokenResponse rstr)
        {
            if (rstr.Entropy == null)
            {
                throw new NotSupportedException("RSTR entropy is null");
            }
            if (rst.Entropy == null)
            {
                throw new NotSupportedException("RST entropy is null");
            }

            int? keySizeInBits = rst.KeySizeInBits;
            int num = keySizeInBits.HasValue ? keySizeInBits.GetValueOrDefault() : 0x400;
            if (rstr.KeySizeInBits.HasValue)
            {
                num = rstr.KeySizeInBits.Value;
            }

            return new BinarySecretSecurityToken(
                KeyGenerator.ComputeCombinedKey(
                    rst.Entropy.GetKeyBytes(),
                    rstr.Entropy.GetKeyBytes(),
                    num));
        }
        private static XmlElement ExtractTokenXml(RequestSecurityTokenResponse rstr)
        {
            if (rstr.RequestedSecurityToken.SecurityToken != null)
            {
                var xmlString = rstr.RequestedSecurityToken.SecurityToken.ToTokenXmlString();
                return XElement.Parse(xmlString).ToXmlElement();
            }
            if (rstr.RequestedSecurityToken.SecurityTokenXml != null)
            {
                return rstr.RequestedSecurityToken.SecurityTokenXml;
            }

            return null;
        }
        protected virtual void OnLoggedIn(RequestSecurityTokenResponse requestSecurityTokenResponse)
        {
            if (requestSecurityTokenResponse == null)
            {
                Mvx.TaggedTrace(MvxTraceLevel.Error, "DefaultIdentityProviderCollectionViewModel", "Got an empty response from IdentityProvider");
                if (LoginError != null)
                    LoginError(this, new LoginErrorEventArgs { Message = "Got an empty response from IdentityProvider, try logging in again."});
                return;
            }

            var tokenStore = Mvx.Resolve<ISimpleWebTokenStore>();
            var tokenFactory = Mvx.Resolve<ISimpleWebToken>();

            var token = tokenFactory.CreateTokenFromRaw(requestSecurityTokenResponse.SecurityToken);
            tokenStore.SimpleWebToken = token;

            if (!CanGoBack || _forceShowProgressAfterLogin)
                ShowProgressAfterLogin = true;

            RaisePropertyChanged(() => IsLoggedIn);
            RaisePropertyChanged(() => LoggedInProvider);

            _messenger.Publish(new LoggedInMessage(this));
        }
        public ActionResult IssueResponse()
        {
            if (Request.Form.HasKeys())
            {
                if (Request.Form["SAMLResponse"] != null)
                {
                    var samlResponse = Request.Form["SAMLResponse"];
                    var responseDecoded = Encoding.UTF8.GetString(Convert.FromBase64String(HttpUtility.HtmlDecode(samlResponse)));

                    Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken token;

                    using (var sr = new StringReader(responseDecoded))
                    {
                        using (var reader = XmlReader.Create(sr))
                        {
                            reader.ReadToFollowing("Assertion", "urn:oasis:names:tc:SAML:2.0:assertion");
                            var coll = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                            token = (Microsoft.IdentityModel.Tokens.Saml2.Saml2SecurityToken)coll.ReadToken(reader.ReadSubtree());
                        }
                    }

                    var realm = token.Assertion.Conditions.AudienceRestrictions[0].Audiences[0].ToString();
                    var issuer = token.Assertion.Issuer.Value;

                    var rstr = new RequestSecurityTokenResponse
                    {
                        TokenType = Constants.TokenKeys.TokenType,
                        RequestType = Constants.TokenKeys.RequestType,
                        KeyType = Constants.TokenKeys.KeyType,
                        Lifetime = new Lifetime(token.Assertion.IssueInstant, token.Assertion.Conditions.NotOnOrAfter),
                        AppliesTo = new System.ServiceModel.EndpointAddress(new Uri(realm)),
                        RequestedSecurityToken = new RequestedSecurityToken(GetElement(responseDecoded))
                    };

                    var principal = GetClaimsIdentity(rstr);
                    if (principal != null)
                    {
                        var claimsPrinciple = ClaimsPrincipal.CreateFromPrincipal(principal);
                        var requestMessage = new SignInRequestMessage(new Uri("http://foo"), realm);
                        var ipc = new SamlTokenServiceConfiguration(issuer);
                        SecurityTokenService identityProvider = new SamlTokenService(ipc);
                        var responseMessage = Microsoft.IdentityModel.Web.FederatedPassiveSecurityTokenServiceOperations.ProcessSignInRequest(requestMessage, claimsPrinciple, identityProvider);
                        Microsoft.IdentityModel.Web.FederatedPassiveSecurityTokenServiceOperations.ProcessSignInResponse(responseMessage, System.Web.HttpContext.Current.Response);
                    }
                }
            }
            return View("Error");
        }