예제 #1
0
        static void Main(string[] args) {

            string idpAddress = "https://idp.contoso.com/SecurityTokenService/Issue.svc/mixed/username";
            string fedAddress = "https://sts.contoso.com/adfs/services/trust/13/IssuedTokenMixedSymmetricBasic256";
            string svcAddress = "https://internalcrm.contoso.com";

            var idpBinding = new UserNameWSTrustBinding() {
                SecurityMode = SecurityMode.TransportWithMessageCredential
            };
            var fedBinding = new IssuedTokenWSTrustBinding(idpBinding, new EndpointAddress(idpAddress)) {
                SecurityMode = SecurityMode.TransportWithMessageCredential,
                //KeyType = SecurityKeyType.SymmetricKey
            };
            var channelFactory = new WSTrustChannelFactory(fedBinding, fedAddress);
            channelFactory.Credentials.UserName.UserName = "******";
            channelFactory.Credentials.UserName.Password = "******";
            var request = new RequestSecurityToken {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(svcAddress),
                //TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11,
                //TokenType = SecurityTokenTypes.Saml,
            };
            var token = channelFactory.CreateChannel().Issue(request);
            //return token;
        }
예제 #2
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;
        }
예제 #3
0
        private static SecurityToken GetToken()
        {
            string stsEndpoint = "https://win-beju5ai4tp7.pbdev.codit.eu/adfs/services/trust/2005/windowstransport";
            // Windows authentication over transport security
            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                stsEndpoint);
            factory.TrustVersion = TrustVersion.WSTrustFeb2005;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress("https://localhost:8732/ClaimsEnumeratorService/"),
                KeyType = KeyTypes.Symmetric
            };

            var channel = factory.CreateChannel();
            SecurityToken tk = channel.Issue(rst);

            Console.WriteLine(tk.Id);
            foreach (var key in tk.SecurityKeys)
            {
                Console.WriteLine(key.KeySize.ToString());
            }
            Console.WriteLine(tk.ValidFrom);
            Console.WriteLine(tk.ValidTo);

            return tk;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestMessage"></param>
        /// <param name="config"></param>
        /// <param name="withRefreshToken"></param>
        /// <returns></returns>
        public static AccessTokenResponse ProcessAccessTokenRequest(AccessTokenRequest requestMessage, SecurityTokenServiceConfiguration config, Boolean withRefreshToken)
        {
            ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;

            // Call issuer to create token
            WSTrustChannelFactory factory = new WSTrustChannelFactory("issuer");
            // TODO: factory.Credentials.UserName.UserName = requestMessage.Name ?? requestMessage.ClientId;
            // TODO: factory.Credentials.UserName.Password = requestMessage.Password ?? requestMessage.ClientSecret;
            WSTrustChannel issuer = factory.CreateChannel() as WSTrustChannel;
            RequestSecurityToken rst = new RequestSecurityToken(WSTrust13Constants.RequestTypes.Issue);
            rst.AppliesTo = new EndpointAddress("https://wrap.client");
            rst.KeyType = WSTrust13Constants.KeyTypes.Bearer;

            RequestSecurityTokenResponse response = null;
            issuer.Issue(rst, out response);

            WSTrustSerializationContext context = new WSTrustSerializationContext(
                config.SecurityTokenHandlerCollectionManager,
                config.CreateAggregateTokenResolver(),
                config.IssuerTokenResolver);

            // Create response
            var token = response.RequestedSecurityToken.SecurityToken;
            if (null == token)
            {
                using (XmlReader reader = new XmlNodeReader(response.RequestedSecurityToken.SecurityTokenXml))
                {
                    token = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.ReadToken(reader);
                }
                token = ConvertToSimpleWebToken(token, response);
            }

            // Write token
            return WriteToken(token, withRefreshToken);
        }
예제 #5
0
    static void Main(String[] arguments)
    {
        if (2 != arguments.Length)
        {
            ShowUsage();
            return;
        }
        String userName = arguments[0];
        String password = arguments[1];

        var serviceAddress = "http://127.0.0.1:450/TimeService.svc";

        var factory = new WSTrustChannelFactory("issuer");
        factory.Credentials.UserName.UserName = userName;
        factory.Credentials.UserName.Password = password;
        var channel = factory.CreateChannel() as WSTrustChannel;
        var rst = new RequestSecurityToken("http://schemas.microsoft.com/idfx/requesttype/issue");

        rst.AppliesTo = new EndpointAddress(serviceAddress);

        RequestSecurityTokenResponse rstr = null;

        Console.WriteLine("Before issue");
        var token = channel.Issue(rst, out rstr);

        Console.WriteLine("After issue");
    }
        private static string GetWindowsToken(string windowsAuthSiteEndPoint, string realm)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + TenantApiUri.WindowsAuthSite));
            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(realm),
                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;
        }
        public bool ValidateUser(string userId, string password, out SessionSecurityToken sessionToken)
        {
            // authenticate with WS-Trust endpoint
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress("https://localhost/ActiveSTS/SecurityTokenService.svc"));

            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UserName.UserName = userId;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress("https://localhost/stsclient/"),
                KeyType = KeyTypes.Bearer,
                TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml11TokenProfile11,
            };

            var channel = factory.CreateChannel();

            var genericToken = channel.Issue(rst) as System.IdentityModel.Tokens.GenericXmlSecurityToken;

            // parse token
            var handlers = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
            var token = handlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));
            var identity = handlers.ValidateToken(token).First();

            // create session token
            sessionToken = new SessionSecurityToken(ClaimsPrincipal.CreateFromIdentity(identity));
            return true;
        }
        private static string RequestIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                "CN=Client");

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = _acsBaseAddress
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;

            return token.TokenXml.OuterXml;
        }
        private static RequestSecurityTokenResponse RequestToken(RequestSecurityToken rst)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(idp));
            factory.Credentials.ClientCertificate.Certificate = X509Certificates.GetCertificateFromStore("CN=Client");

            RequestSecurityTokenResponse rstr;
            var token = factory.CreateChannel().Issue(rst, out rstr);

            return rstr;
        }
        public static IWSTrustChannelContract CreateMixedUserNameClient(string userName, string password, string endpointAddress)
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(endpointAddress));
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = userName;
            factory.Credentials.UserName.Password = password;

            return factory.CreateChannel();
        }
        private static IWSTrustChannelContract CreateWSTrustChannel(EndpointAddress stsAddress, Binding binding, ClientCredentials credentials)
        {
            var factory = new WSTrustChannelFactory(
                binding,
                stsAddress);

            var creds = factory.Endpoint.Behaviors.Find<ClientCredentials>();
            factory.Endpoint.Behaviors.Remove(creds);
            factory.Endpoint.Behaviors.Add(credentials);

            return factory.CreateChannel();
        }
예제 #12
0
        public static SecurityToken GetIssuedToken(Uri audience, X509Certificate2 clientCertificate, X509Certificate2 stsCertificate, Uri endpoint, SecurityToken bootstrapSecurityToken)
        {
            WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(SecureTokenServiceBindings.GetIssuedTokenBindingNonSSL(), new EndpointAddress(endpoint, EndpointIdentity.CreateDnsIdentity("DANID A/S - DanID Test")));
            trustChannelFactory.Credentials.ServiceCertificate.DefaultCertificate = stsCertificate;
            trustChannelFactory.Credentials.ClientCertificate.Certificate = clientCertificate;
            trustChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            trustChannelFactory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;

            trustChannelFactory.TrustVersion = TrustVersion.WSTrust13;
            var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
            var rst = RequestSecurityToken(bootstrapSecurityToken, clientCertificate, audience, new List<RequestClaim>());
            var response = channel.Issue(rst);
            return response;
        }
        public static IWSTrustChannelContract CreateMixedCertificateClient(string subjectName, string endpointAddress)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(endpointAddress));
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                subjectName);

            return factory.CreateChannel();
        }
예제 #14
0
        public static IWSTrustChannelContract CreateMixedCertificateClient(string subjectName, string endpointAddress)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(endpointAddress));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindBySubjectDistinguishedName,
                subjectName);

            return(factory.CreateChannel());
        }
        private static IWSTrustChannelContract CreateStsChannel(string username, string password, EndpointAddress stsEndpointAddress)
        {
            var factory = new WSTrustChannelFactory(
                new IdentifyUsernameEndpointBinding(),
                stsEndpointAddress);

            factory.TrustVersion = TrustVersion.WSTrust13;

            if (factory.Credentials != null)
            {
                factory.Credentials.UserName.UserName = username;
                factory.Credentials.UserName.Password = password;
            }

            return(factory.CreateChannel());
        }
        public static void tokenTest()
        {
            string relyingPartyId         = "https://party.mycomp.com";
            WSTrustChannelFactory factory = null;

            try
            {
                // use a UserName Trust Binding for username authentication
                factory = new WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    new EndpointAddress("https://adfs.mycomp.com/adfs/services/trust/13/usernamemixed"));
                factory.TrustVersion = TrustVersion.WSTrust13;
                factory.Credentials.UserName.UserName = "******";
                factory.Credentials.UserName.Password = "******";
                var rst = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(relyingPartyId),
                    KeyType     = KeyTypes.Bearer
                };
                IWSTrustChannelContract channel      = factory.CreateChannel();
                GenericXmlSecurityToken genericToken = channel.Issue(rst) as GenericXmlSecurityToken; //MessageSecurityException -> PW falsch
                var _handler    = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                var tokenString = genericToken.ToTokenXmlString();
                var samlToken2  = _handler.ReadToken(new XmlTextReader(new StringReader(tokenString)));
                ValidateSamlToken(samlToken2);
                X509Certificate2 certificate = null;
                X509Store        store       = new X509Store(StoreName.My, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);
                certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "thumb", false)[0];
                var jwt = ConvertSamlToJwt(samlToken2, "https://party.mycomp.com", certificate);
            }
            finally
            {
                if (factory != null)
                {
                    try
                    {
                        factory.Close();
                    }
                    catch (CommunicationObjectFaultedException)
                    {
                        factory.Abort();
                    }
                }
            }
        }
예제 #17
0
        /// <summary>
        /// Creates a security token for the service layer.
        /// </summary>
        /// <returns></returns>
        private static SecurityToken CreateSecurityToken(TimeSpan?lifeTime, string user, string password)
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(WsTrustAddress))
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            if (factory.Credentials == null)
            {
                throw new Exception(ErrBadFactory);
            }

            // the identity authorized to 'act as' the current principal
            factory.Credentials.UserName.UserName = user;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = new EndpointReference(ServiceHostAddress),
                //ActAs = new SecurityTokenElement(bootstrap) //may want to look at using actas in the future.
            };

            if (lifeTime != null)
            {
                Log.Debug("Token lifetime config value found. Setting service token lifetime to {0}", lifeTime);
                rst.Lifetime = new Lifetime(null, DateTime.Now.Add(lifeTime.Value));
            }
            try
            {
                Log.Debug("Creating channel to sts to request ActAs Token. Address:{0}", WsTrustAddress);
                IWSTrustChannelContract channel = factory.CreateChannel();
                Log.Debug("Asking STS to issue ActAs Token. Address:{0}", WsTrustAddress);
                //ask the STS to issue a token for the service
                SecurityToken delegationToken = channel.Issue(rst);
                return(delegationToken);
            }
            catch (Exception ex)
            {
                string msg = "Cannot create service security token.";
                Log.Error("{0} Ex:{1}", msg, ex.GetBaseException().Message);
                throw new Exception(msg);
            }
        }
예제 #18
0
        /// <summary>
        /// Issues the token
        /// Mostly copied from Service References
        /// </summary>
        private GenericXmlSecurityToken IssueToken()
        {
            _logger.WriteDebug("Issue Token");
            var issuerEndpoint = FindIssuerEndpoint();

            var requestSecurityToken = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new EndpointReference(_infoShareWSAppliesTo.Value.AbsoluteUri),
                KeyType     = System.IdentityModel.Protocols.WSTrust.KeyTypes.Symmetric
            };

            using (var factory = new WSTrustChannelFactory((WS2007HttpBinding)issuerEndpoint.Binding, issuerEndpoint.Address))
            {
                ApplyCredentials(factory.Credentials);
                ApplyTimeout(factory.Endpoint, _connectionParameters.IssueTimeout);

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

                WSTrustChannel channel = null;
                try
                {
                    _logger.WriteDebug($"Issue Token for AppliesTo[{requestSecurityToken.AppliesTo.Uri}]");
                    channel = (WSTrustChannel)factory.CreateChannel();
                    RequestSecurityTokenResponse requestSecurityTokenResponse;
                    return(channel.Issue(requestSecurityToken, out requestSecurityTokenResponse) as GenericXmlSecurityToken);
                }
                catch
                {
                    // Fallback to 10.0.X and 11.0.X configuration using relying party per url like /InfoShareWS/API25/Application.svc
                    requestSecurityToken.AppliesTo = new EndpointReference(_serviceUriByServiceName[Application25].AbsoluteUri);
                    _logger.WriteDebug($"Issue Token for AppliesTo[{requestSecurityToken.AppliesTo.Uri}] as fallback on 10.0.x/11.0.x");
                    RequestSecurityTokenResponse requestSecurityTokenResponse;
                    return(channel.Issue(requestSecurityToken, out requestSecurityTokenResponse) as GenericXmlSecurityToken);
                }
                finally
                {
                    if (channel != null)
                    {
                        channel.Abort();
                    }
                    factory.Abort();
                }
            }
        }
예제 #19
0
        private SecurityToken GetSecurityTokenDirectFromLocalSts()
        {
            if (trustChannelFactory == null)
            {
                var endpointidentifier = EndpointIdentity.CreateDnsIdentity(ConfigurationManager.AppSettings["LocalHostStsServiceCertficateName"]);
                var epa     = new Uri(ConfigurationManager.AppSettings["UriIdpStsAddress"]);
                var address = new EndpointAddress(epa, endpointidentifier, new AddressHeaderCollection());
                var binding = new WS2007HttpBinding
                {
                    Security =
                    {
                        Mode    = SecurityMode.Message,
                        Message =
                        {
                            ClientCredentialType       = MessageCredentialType.UserName,
                            EstablishSecurityContext   = false,
                            NegotiateServiceCredential = true
                        }
                    }
                };

                var channelFactory = new WSTrustChannelFactory(binding, address)
                {
                    TrustVersion = TrustVersion.WSTrust13
                };
                if (channelFactory.Credentials != null)
                {
                    channelFactory.Credentials.UserName.UserName        = "******"; //single space as local sts not using
                    channelFactory.Credentials.UserName.Password        = "******"; //single space as local sts not using
                    channelFactory.Credentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;
                }

                trustChannelFactory = channelFactory;
            }

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new System.IdentityModel.Protocols.WSTrust.EndpointReference(ConfigurationManager.AppSettings["UriRpAppliesTo"])
            };

            var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
            RequestSecurityTokenResponse rstr;
            var token = channel.Issue(rst, out rstr);

            return(token);
        }
        /// <summary>
        /// Gets the membership token.
        /// </summary>
        /// <param name="authSiteEndPoint">The auth site end point.</param>
        /// <param name="userName">Name of the user.</param>
        /// <param name="password">The password.</param>
        /// <param name="certificateValidation">The certificate validation is enabled by default. users can disable this manually.</param>
        /// <returns>string token from the membership site</returns>
        private static string GetMembershipTokenHelper(string authSiteEndPoint, string userName, string password, CertificateValidation certificateValidation = CertificateValidation.Enable)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + "/wstrust/issue/usernamemixed"));

            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

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

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

            ////This line is only if we're using self-signed certs in the installation
            if (certificateValidation == CertificateValidation.Disable)
            {
                trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication()
                {
                    CertificateValidationMode = X509CertificateValidationMode.None
                };
            }

            trustChannelFactory.Credentials.SupportInteractive = false;
            trustChannelFactory.Credentials.UserName.UserName  = userName;
            trustChannelFactory.Credentials.UserName.Password  = password;

            var channel = trustChannelFactory.CreateChannel();
            var rst     = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
                TokenType = "urn:ietf:params:oauth:token-type:jwt",
                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);
        }
예제 #21
0
        public SecurityToken GetSecurityToken()
        {
            //service identifier whitin the ADFS server where I want to access, must be configured as RP in ADFS
            //this is the same value we configure on server side for the parameter audienceUris
            EndpointReference serviceAddress = new EndpointReference(@"http://testWCFService.gianlucb.local");

            //who gives me the token
            string stsAddress;

            //ignores certificates error
            ServicePointManager.ServerCertificateValidationCallback = (x, y, z, w) => true;

            //USERNAME
            stsAddress = @"https://sts.gianlucb.local/adfs/services/trust/13/usernamemixed";
            WS2007HttpBinding stsBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            stsBinding.Security.Transport.ClientCredentialType   = HttpClientCredentialType.Ntlm;
            stsBinding.Security.Message.ClientCredentialType     = MessageCredentialType.UserName;
            stsBinding.Security.Message.EstablishSecurityContext = false;

            WSTrustChannelFactory trustChannelFactory = new WSTrustChannelFactory(stsBinding, stsAddress);

            trustChannelFactory.Credentials.SupportInteractive = false;
            trustChannelFactory.Credentials.UserName.Password  = "******";
            trustChannelFactory.Credentials.UserName.UserName  = "******";

            //---------------------

            //connection
            WSTrustChannel channel = (WSTrustChannel)trustChannelFactory.CreateChannel();

            RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Issue);

            rst.AppliesTo = serviceAddress;
            rst.KeyType   = KeyTypes.Symmetric;

            RequestSecurityTokenResponse rstr = null;
            SecurityToken token            = channel.Issue(rst, out rstr);
            var           xmlSecurityToken = token as GenericXmlSecurityToken;

            Trace.WriteLine("Received the token:");
            Trace.WriteLine(xmlSecurityToken.TokenXml.InnerXml);

            return(token);
        }
예제 #22
0
        public SecurityToken GetToken()
        {
            // Need this because the server has a self-signed certificate that doesn't pass validation
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;

            var factory = new WSTrustChannelFactory(
                new UserNameWsTrustBinding(),
                StsWsTrustEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            factory.Credentials.UserName.UserName = UserName;
            factory.Credentials.UserName.Password = Password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                TokenType   = "urn:oasis:names:tc:SAML:2.0:assertion",
                AppliesTo   = new EndpointReference(Realm)
            };

            var genericToken = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            var tokenXml     = genericToken.TokenXml.OuterXml;

            var tokenHandlers = SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
            var config        = tokenHandlers.Configuration;

            config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(Realm));
            config.CertificateValidator = X509CertificateValidator.None;
            var registry = new ConfigurationBasedIssuerNameRegistry();

            registry.AddTrustedIssuer("CB317A2E635B47310D50A67C7B40081F7B4BD280", "http://platformservices.spikesco.com/devsts");
            config.IssuerNameRegistry = registry;
            var token    = tokenHandlers.ReadToken(new XmlTextReader(new StringReader(tokenXml)));
            var identity = tokenHandlers.ValidateToken(token);

            Thread.CurrentPrincipal = new ClaimsPrincipal(identity);

            TokenHelpers.TokenHelpers.Print(tokenXml);
            TokenHelpers.TokenHelpers.PrintCurrentPrincipal();

            return(token);
        }
예제 #23
0
        private static string GetADFSToken(string windowsAuthSiteEndPoint, string userName, string Password)
        {
            try
            {
                var identityProviderEndpoint = new EndpointAddress(new Uri(windowsAuthSiteEndPoint + "/adfs/services/trust/13/usernamemixed"));
                var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
                identityProviderBinding.Security.Message.EstablishSecurityContext = false;
                identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
                identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

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

                trustChannelFactory.Credentials.SupportInteractive = false;
                trustChannelFactory.Credentials.UserName.UserName = userName;
                trustChannelFactory.Credentials.UserName.Password = Password;
                var channel = trustChannelFactory.CreateChannel();
                var rst = new RequestSecurityToken(RequestTypes.Issue)
                {
                    AppliesTo = new EndpointReference("http://azureservices/TenantSite"),
                    TokenType = "urn:ietf:params:oauth:token-type:jwt",
                    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;
            }
            catch (Exception ex)
            {
                using (EventLog eventLog = new EventLog("Application"))
                {
                    eventLog.Source = "Application";
                    eventLog.WriteEntry("ADFS HealthCheck: " + (object)ex, EventLogEntryType.Error, 1111, (short)1);
                }
                return ex.ToString();
            }
        }
        private static SecurityToken RequestIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Symmetric,
                AppliesTo = new EndpointAddress("https://" + Constants.WebHost + "/webservicesecurity/")
            };

            return factory.CreateChannel().Issue(rst);
        }
예제 #25
0
        private static SecurityToken RequestToken()
        {
            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                new EndpointAddress("https://adfs.leastprivilege.vm/adfs/services/trust/13/windowstransport"));
            factory.TrustVersion = TrustVersion.WSTrust13;

            var channel = factory.CreateChannel();

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = new EndpointReference("https://adfs.leastprivilege.vm/adfsapp/")
            };

            return channel.Issue(rst);
        }
예제 #26
0
        /// <summary>
        /// Issues the token
        /// Mostly copied from Service References
        /// </summary>
        public void IssueToken()
        {
            var requestSecurityToken = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new EndpointReference(uris["Application25"].AbsoluteUri),
                KeyType     = System.IdentityModel.Protocols.WSTrust.KeyTypes.Symmetric,
            };

            requestSecurityToken.TokenType = SamlSecurityTokenHandler.Assertion;
            //This should have worked directly but I don't know why it doesn't.
            //using (var factory = new WSTrustChannelFactory(this.issuerServiceEndpoint))
            using (var factory = new WSTrustChannelFactory((WS2007HttpBinding)this.issuerServiceEndpoint.Binding, this.issuerServiceEndpoint.Address))
            {
                ApplyCredentials(factory.Credentials);

                //Apply the connection timeout to the token issue process
                ApplyTimeout(factory.Endpoint, IssueTimeout);

                factory.TrustVersion = TrustVersion.WSTrust13;
                factory.Credentials.SupportInteractive = false;
                WSTrustChannel channel = null;

                try
                {
                    channel = (WSTrustChannel)factory.CreateChannel();
                    RequestSecurityTokenResponse requestSecurityTokenResponse;
                    this.issuedToken = channel.Issue(requestSecurityToken, out requestSecurityTokenResponse) as GenericXmlSecurityToken;
                }
                catch (Exception ex)
                {
                    throw;
                }
                finally
                {
                    if (channel != null)
                    {
                        channel.Abort();
                    }

                    factory.Abort();
                }
            }
        }
    /// <summary>
    /// Requests a security token from the ADFS server
    /// </summary>
    /// <param name="username">The username</param>
    /// <param name="password">The password</param>
    /// <param name="endpoint">The ADFS endpoint</param>
    /// <returns></returns>
    public GenericXmlSecurityToken RequestToken(string username, SecureString password, string endpoint)
    {
        WSTrustChannelFactory factory = new WSTrustChannelFactory(
            new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
            new EndpointAddress(adfsUserNameMixedEndpoint));

        factory.TrustVersion = TrustVersion.WSTrust13;
        factory.Credentials.UserName.UserName = username;
        factory.Credentials.UserName.Password = new System.Net.NetworkCredential(string.Empty, password).Password;
        RequestSecurityToken token = new RequestSecurityToken
        {
            RequestType = RequestTypes.Issue,
            AppliesTo   = new EndpointReference(endpoint),
            KeyType     = KeyTypes.Bearer
        };
        IWSTrustChannelContract channel = factory.CreateChannel();

        return(channel.Issue(token) as GenericXmlSecurityToken);
    }
예제 #28
0
        private static SecurityToken RequestSamlToken()
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(adfsEndpoint));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = new EndpointReference(realm)
            };

            return(factory.CreateChannel().Issue(rst));
        }
        private static SecurityToken RequestSymmetricEncryptedToken(X509Certificate2 decryptionCert)
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(idp));

            factory.Credentials.ClientCertificate.Certificate = X509Certificates.GetCertificateFromStore("CN=Client");

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo   = new EndpointAddress(encryptedRP),
                KeyType     = KeyTypes.Symmetric
            };

            var genericToken = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            var token        = genericToken.ToSecurityToken(decryptionCert);

            return(token);
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                /* TokenType = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11, */
                AppliesTo = new EndpointAddress(Constants.Realm)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            return token.TokenXml.OuterXml;
        }
예제 #31
0
        /// <summary>
        /// Returns Generic XML Security Token from ADFS to generated FedAuth
        /// </summary>
        /// <param name="kerberosMixed">ADFS Endpoint for Kerberos Mixed Authentication</param>
        /// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
        /// <returns></returns>
        private GenericXmlSecurityToken RequestToken(Uri kerberosMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;

            using (var factory = new WSTrustChannelFactory(new KerberosWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(kerberosMixed)))
            {
                factory.TrustVersion = TrustVersion.WSTrust13;
                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(relyingPartyIdentifier),
                    KeyType     = KeyTypes.Bearer
                };

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return(genericToken);
        }
        private static SecurityToken RequestBearerClearTextToken()
        {
            var factory = new WSTrustChannelFactory(
                new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(idp));
            factory.Credentials.ClientCertificate.Certificate = X509Certificates.GetCertificateFromStore("CN=Client");

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(clearTextRP),
                KeyType = KeyTypes.Bearer,
            };

            

            var genericToken = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            var token = genericToken.ToSecurityToken();
            
            return token;
        }
        private static string GetSTSToken(Uri requestUri, string endPoint, string realm)
        {
            var binding = new WS2007HttpBinding(SecurityMode.Transport);
            var factory = new WSTrustChannelFactory(binding, endPoint)
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            var endPointReference = new EndpointReference(realm);
            var requestToken      = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = endPointReference
            };

            var channel       = factory.CreateChannel();
            var responseToken = channel.Issue(requestToken) as GenericXmlSecurityToken;

            return(responseToken?.TokenXml.OuterXml);
        }
예제 #34
0
        private static IWSTrustChannelContract GenerateStsCertificateClientChannel(X509Certificate2 clientCertificate)
        {
            var stsAddress = new EndpointAddress(new Uri(ConfigVariables.StsEndpoint), EndpointIdentity.CreateDnsIdentity(ConfigVariables.StsCertificateAlias));
            var binding    = new MutualCertificateWithMessageSecurityBinding(null);
            var factory    = new WSTrustChannelFactory(binding, stsAddress);

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.ClientCertificate.Certificate = clientCertificate;
            var certificate = CertificateLoader.LoadCertificate(
                ConfigVariables.StsCertificateStoreName,
                ConfigVariables.StsCertificateStoreLocation,
                ConfigVariables.StsCertificateThumbprint);

            factory.Credentials.ServiceCertificate.ScopedCertificates.Add(stsAddress.Uri, certificate);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            // Disable revocation checking (do not use in production)
            // Should be uncommented if you intent to call DemoService locally.
            //factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck;
            factory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign;
            return(factory.CreateChannel());
        }
예제 #35
0
        private static SecurityToken RequestSecurityToken()
        {
            "Requesting identity token".ConsoleYellow();


            var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), _idsrvAddress);

            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = new EndpointReference(_serviceAddress.AbsoluteUri + "/bearer")
            };

            return(factory.CreateChannel().Issue(rst));
        }
        public GenericXmlSecurityToken RequestToken(string issuer, string appliesTo, RecordsManagerCredentials credentials)
        {
            var binding = (issuer.ToLower().StartsWith("https")) ? this.GetHttpsBinding() : this.GetHttpBinding();

            var address = new EndpointAddress(issuer);

            var factory = new WSTrustChannelFactory(binding, address);
            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.Windows.ClientCredential = credentials.GetCredential();

            var channel = factory.CreateChannel();

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointAddress(appliesTo)
            };

            RequestSecurityTokenResponse rstr = null;

            return channel.Issue(rst, out rstr) as GenericXmlSecurityToken;
        }
예제 #37
0
        protected virtual async Task <TokenResponse> IssueTokenForRstAsync(WSTrustChannelFactory factory, RequestSecurityToken rst)
        {
            var channel = factory.CreateChannel();

            var taskCompletionSource = new TaskCompletionSource <TokenResponse>();

            channel.BeginIssue(rst, asyncResult =>
            {
                try
                {
                    RequestSecurityTokenResponse rstr2;
                    var token = channel.EndIssue(asyncResult, out rstr2);
                    taskCompletionSource.SetResult(new TokenResponse(token, rstr2));
                }
                catch (Exception ex)
                {
                    taskCompletionSource.SetException(ex);
                }
            }, null);
            return(await taskCompletionSource.Task.ConfigureAwait(false));
        }
예제 #38
0
        private static SecurityToken ConvertToToken(string xml)
        {
            WS2007FederationHttpBinding binding = new WS2007FederationHttpBinding(WSFederationHttpSecurityMode.TransportWithMessageCredential,
                                                                                  false);
            WSTrustChannelFactory factory = new WSTrustChannelFactory(binding, new EndpointAddress("https://null-EndPoint"));

            factory.TrustVersion = TrustVersion.WSTrustFeb2005;

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

            RequestSecurityTokenResponse response = trustChannel.WSTrustResponseSerializer.CreateInstance();

            response.RequestedSecurityToken = new RequestedSecurityToken(LoadXml(xml).DocumentElement);
            response.IsFinal = true;

            RequestSecurityToken requestToken = new RequestSecurityToken(WSTrustFeb2005Constants.RequestTypes.Issue);

            requestToken.KeyType = WSTrustFeb2005Constants.KeyTypes.Symmetric;

            return(trustChannel.GetTokenFromResponse(requestToken, response));
        }
예제 #39
0
        private static SecurityToken GetStsToken(int tokenLifeTimeMinutes)
        {
            WS2007HttpBinding binding = new WS2007HttpBinding();

            binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
            binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
            binding.Security.Message.EstablishSecurityContext = false;
            binding.Security.Message.AlgorithmSuite           = SecurityAlgorithmSuite.Basic256Sha256;
            string endPoint = "S007SecurityTokenServiceEndpointV3";

            var factory = new WSTrustChannelFactory(endPoint);

            factory.Credentials.ClientCertificate.Certificate = GetClientCertificateFromKeystore();

            // Instantiate and invoke the client to get the security token
            factory.Credentials.SupportInteractive = false;

            var appliesTo = ConfigurationManager.AppSettings["appliesTo"];
            var rst       = new RequestSecurityToken
            {
                Claims =
                {
                    new RequestClaim("http://vanguard.ebusiness.gov.au/2008/06/identity/claims/credentialtype", false)
                    ,                                                                                           new RequestClaim("http://vanguard.ebusiness.gov.au/2008/06/identity/claims/abn", false)
                },
                AppliesTo     = new EndpointReference(appliesTo),
                Lifetime      = new Lifetime(DateTime.UtcNow, DateTime.UtcNow.AddMinutes(tokenLifeTimeMinutes)),
                RequestType   = RequestTypes.Issue,
                KeyType       = KeyTypes.Symmetric,
                KeySizeInBits = 256,
                TokenType     = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV1.1"
            };

            // Instantiate and invoke the client to get the security token
            var client = (WSTrustChannel)factory.CreateChannel();

            SecurityToken response = client.Issue(rst);

            return(response);
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new WindowsWSTrustBinding(SecurityMode.Transport),
                _idpEndpoint);

            factory.TrustVersion = TrustVersion.WSTrust13;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                TokenType   = TokenTypes.Saml2TokenProfile11,
                AppliesTo   = new EndpointReference(Constants.Realm)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;

            return(token.TokenXml.OuterXml);
        }
예제 #41
0
        public static SecurityToken GetToken(string endpointUri, string username, string password, string realm)
        {
            // use WSTrust and SSL Transport Mode with security credentials being sent with the message.
            var endpoint = new EndpointAddress(endpointUri);
            var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), endpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            // Symmetric key request.
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(realm),
                KeyType = KeyTypes.Symmetric
            };

            // Token will be encrypted with ADFS Token Signing cert.
            var channel = factory.CreateChannel();
            return channel.Issue(rst);
        }
        private static SecurityToken GetSamlToken(string realm, string stsEndpoint, ClientCredentials clientCredentials)
        {
            using (var factory = new WSTrustChannelFactory(
                       new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                       new EndpointAddress(new Uri(stsEndpoint))))
            {
                factory.Credentials.UserName.UserName = clientCredentials.UserName.UserName;
                factory.Credentials.UserName.Password = clientCredentials.UserName.Password;
                factory.TrustVersion = TrustVersion.WSTrust13;

                WSTrustChannel channel = null;

                try
                {
                    var rst = new RequestSecurityToken
                    {
                        RequestType = WSTrust13Constants.RequestTypes.Issue,
                        AppliesTo   = new EndpointAddress(realm),
                        KeyType     = KeyTypes.Bearer,
                    };

                    channel = (WSTrustChannel)factory.CreateChannel();

                    RequestSecurityTokenResponse response;
                    var token = channel.Issue(rst, out response);

                    return(token);
                }
                finally
                {
                    if (channel != null)
                    {
                        channel.Abort();
                    }

                    factory.Abort();
                }
            }
        }
        public string GetTenantToken(string authSiteEndPoint, string userName, string password, bool validateCertificate, string realm)
        {
            var identityProviderEndpoint = new EndpointAddress(new Uri(authSiteEndPoint + TenantApiUri.AspNetAuthSite));

            var identityProviderBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
            identityProviderBinding.Security.Message.EstablishSecurityContext = false;
            identityProviderBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;
            identityProviderBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None;

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

            if (!validateCertificate)
            {
                trustChannelFactory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication() { CertificateValidationMode = X509CertificateValidationMode.None };
            }
            trustChannelFactory.Credentials.SupportInteractive = false;
            trustChannelFactory.Credentials.UserName.UserName = userName;
            trustChannelFactory.Credentials.UserName.Password = password;

            var channel = trustChannelFactory.CreateChannel();
            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointReference(realm),
                TokenType = "urn:ietf:params:oauth:token-type:jwt",
                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;
        }
        public GenericXmlSecurityToken RequestToken(string issuer, string appliesTo, RecordsManagerCredentials credentials)
        {
            var binding = (issuer.ToLower().StartsWith("https")) ? this.GetHttpsBinding() : this.GetHttpBinding();

            var address = new EndpointAddress(issuer);

            var factory = new WSTrustChannelFactory(binding, address);

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.Windows.ClientCredential = credentials.GetCredential();

            var channel = factory.CreateChannel();

            var rst = new RequestSecurityToken(RequestTypes.Issue)
            {
                AppliesTo = new EndpointAddress(appliesTo)
            };

            RequestSecurityTokenResponse rstr = null;

            return(channel.Issue(rst, out rstr) as GenericXmlSecurityToken);
        }
        public GenericXmlSecurityToken RequestToken(string username, string password, string relyingPartyId)
        {
            var factory = new WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                     new EndpointAddress(this.ADFSUserNameMixedEndpoint));

            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(relyingPartyId),
                KeyType = KeyTypes.Bearer
            };
            IWSTrustChannelContract channel = factory.CreateChannel();
            GenericXmlSecurityToken genericToken = channel.Issue(rst) as GenericXmlSecurityToken;

            return genericToken;
        }
        /// <summary>
        /// Returns Generic XML Security Token from ADFS to generated FedAuth
        /// </summary>
        /// <param name="serialNumber">Serial Number of Certificate from CurrentUSer > My Certificate</param>
        /// <param name="certificateMixed">ADFS Endpoint for Certificate Mixed Authentication</param>
        /// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
        /// <returns></returns>
        private GenericXmlSecurityToken RequestToken(string serialNumber, Uri certificateMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;
            using (var factory = new WSTrustChannelFactory(new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(certificateMixed)))
            {
                
                factory.TrustVersion = TrustVersion.WSTrust13;
                // Hookup the user and password 
                factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySerialNumber, serialNumber);
                
                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo = new EndpointReference(relyingPartyIdentifier),
                    KeyType = KeyTypes.Bearer
                };

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return genericToken;
        }
예제 #47
0
        /// <summary>
        /// Returns Generic XML Security Token from ADFS to generated FedAuth
        /// </summary>
        /// <param name="serialNumber">Serial Number of Certificate from CurrentUSer > My Certificate</param>
        /// <param name="certificateMixed">ADFS Endpoint for Certificate Mixed Authentication</param>
        /// <param name="relyingPartyIdentifier">Identifier of the ADFS relying party that we're hitting</param>
        /// <returns></returns>
        private GenericXmlSecurityToken RequestToken(string serialNumber, Uri certificateMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;

            using (var factory = new WSTrustChannelFactory(new CertificateWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(certificateMixed)))
            {
                factory.TrustVersion = TrustVersion.WSTrust13;
                // Hookup the user and password
                factory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySerialNumber, serialNumber);

                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(relyingPartyIdentifier),
                    KeyType     = KeyTypes.Bearer
                };

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return(genericToken);
        }
        private static string GetSamlToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                Constants.IdSrv.WSTrustEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                TokenType = TokenTypes.Saml2TokenProfile11,
                AppliesTo = new EndpointReference(Constants.Realm)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;
            return token.TokenXml.OuterXml;
        }
예제 #49
0
        private GenericXmlSecurityToken RequestToken(string userName, string passWord, Uri userNameMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;
            using (var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(userNameMixed)))
            {
                factory.TrustVersion = TrustVersion.WSTrust13;
                // Hookup the user and password 
                factory.Credentials.UserName.UserName = userName;
                factory.Credentials.UserName.Password = passWord;

                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo = new EndpointReference(relyingPartyIdentifier),
                    KeyType = KeyTypes.Bearer
                };

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return genericToken;
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);
            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = new EndpointReference(_acsBaseAddress.AbsoluteUri)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;

            return token.TokenXml.OuterXml;
        }
예제 #51
0
        public string Authenticate(string username, string password)
        {
            // Need this because the server has a self-signed certificate that doesn't pass validation
            ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, errors) => true;

            var factory = new WSTrustChannelFactory(
                new UserNameWsTrustBinding(),
                StsWsTrustEndpoint)
            {
                TrustVersion = TrustVersion.WSTrust13
            };

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                TokenType   = "urn:ietf:params:oauth:token-type:jwt",
                AppliesTo   = new EndpointReference(Realm)
            };

            var securityToken = factory.CreateChannel().Issue(rst);
            var genericToken  = securityToken as GenericXmlSecurityToken;
            var tokenXml      = genericToken.TokenXml.OuterXml;
            var handler       = new JwtSecurityTokenHandler();
            var token         = handler.ReadToken(new XmlTextReader(new StringReader(tokenXml)));

            var jwtToken = (JwtSecurityToken)token;

            SetPrincipal(jwtToken);
            var tokenStr = handler.WriteToken(jwtToken);

            tokenStr += jwtToken.EncodedSignature;
            return(tokenStr);
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                TokenType   = Microsoft.IdentityModel.Tokens.SecurityTokenTypes.Saml2TokenProfile11,
                AppliesTo   = new EndpointAddress(Constants.Realm)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;

            return(token.TokenXml.OuterXml);
        }
예제 #53
0
        private GenericXmlSecurityToken RequestToken(string userName, string passWord, Uri userNameMixed, string relyingPartyIdentifier)
        {
            GenericXmlSecurityToken genericToken = null;

            using (var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(userNameMixed)))
            {
                factory.TrustVersion = TrustVersion.WSTrust13;
                // Hookup the user and password
                factory.Credentials.UserName.UserName = userName;
                factory.Credentials.UserName.Password = passWord;

                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(relyingPartyIdentifier),
                    KeyType     = KeyTypes.Bearer
                };

                IWSTrustChannelContract channel = factory.CreateChannel();
                genericToken = channel.Issue(requestSecurityToken) as GenericXmlSecurityToken;
                factory.Close();
            }
            return(genericToken);
        }
        private static string GetIdentityToken()
        {
            "Requesting identity token".ConsoleYellow();

            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                _idpEndpoint);

            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType     = KeyTypes.Bearer,
                AppliesTo   = new EndpointReference(_acsBaseAddress.AbsoluteUri)
            };

            var token = factory.CreateChannel().Issue(rst) as GenericXmlSecurityToken;

            return(token.TokenXml.OuterXml);
        }
        private static string 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;

            // Proof key
            var proofKey = Convert.ToBase64String(response.RequestedProofToken.ProtectedKey.GetKeyBytes());

            return(token.TokenXml.OuterXml);
        }
예제 #56
0
        public bool Logoff(string userName, string password, SecurityToken sessionToken, string securityServerURL)
        {
            using (WSTrustChannelFactory factory = GetTrustChannelFactory(securityServerURL))
            {
                if (factory.Credentials == null)
                {
                    throw new Exception("Credentails are null");
                }
                factory.Credentials.UserName.UserName  = userName;
                factory.Credentials.UserName.Password  = password;
                factory.Credentials.SupportInteractive = false;

                RequestSecurityToken rst = new RequestSecurityToken(RequestTypes.Cancel)
                {
                    CancelTarget = new SecurityTokenElement(sessionToken)
                };

                IWSTrustChannelContract channel = factory.CreateChannel();

                RequestSecurityTokenResponse response = channel.Cancel(rst);

                return(response.RequestedTokenCancelled);
            }
        }
        private static SecurityToken RequestSamlToken()
        {
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(adfsEndpoint));
            factory.TrustVersion = TrustVersion.WSTrust13;

            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                AppliesTo = new EndpointReference(realm)
            };

            return factory.CreateChannel().Issue(rst);
        }
예제 #58
0
        private WSTrustChannel CreateChannel()
        {

            var stsBinding = CreateStsBinding();
            UpdateStsSettingsFromEnvironment();
            var trustChannelFactory = new WSTrustChannelFactory(stsBinding, ServiceSettings.StsAddress)
                                          {
                                              TrustVersion =
                                                  TrustVersion
                                                  .WSTrust13
                                          };

            IncreaseTimeout(trustChannelFactory);
            trustChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            if (UserName.IsNullOrWhiteSpace())
                trustChannelFactory.Credentials.Windows.ClientCredential = Credential;
            else
            {
                trustChannelFactory.Credentials.UserName.UserName = UserName;
                trustChannelFactory.Credentials.UserName.Password = Password;
            }
            trustChannelFactory.Endpoint.Behaviors.Add(new MustUnderstandBehavior(false));
            var channel = (WSTrustChannel)trustChannelFactory.CreateChannel();
            return channel;
        }
        private SecurityToken GetActAsToken(BootstrapContext context)
        {
            string stsAddress = "https://identity.thinktecture.com/idsrvsample/issue/wstrust/mixed/username";
            string realm = FederatedAuthentication.FederationConfiguration.WsFederationConfiguration.Realm;
            
            var factory = new WSTrustChannelFactory(
                new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                new EndpointAddress(stsAddress));
            factory.TrustVersion = TrustVersion.WSTrust13;

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

            var rst = new RequestSecurityToken
            {
                AppliesTo = new EndpointReference(realm),

                RequestType = RequestTypes.Issue,
                KeyType = KeyTypes.Bearer,
                ActAs = new SecurityTokenElement(context.SecurityToken)
            };

            var channel = factory.CreateChannel();
            var delegationToken = channel.Issue(rst);

            return delegationToken;
        }
        private static SecurityToken IssueTokenWithUserNamePassword(string username, string password, string issuerUri, string appliesTo, out RequestSecurityTokenResponse RSTR, string keyType = KeyTypes.Bearer)
        {
            if (String.IsNullOrWhiteSpace(issuerUri)) throw new ArgumentNullException("issuerUri");
            if (String.IsNullOrWhiteSpace(appliesTo)) throw new ArgumentNullException("appliesTo");

            Binding binding = null;
            var WsHttpBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);

            // Avoid the WS-SecureConversation piece
            WsHttpBinding.Security.Message.EstablishSecurityContext = false;
            WsHttpBinding.Security.Message.NegotiateServiceCredential = false;
            WsHttpBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

            // Set our binding variable
            binding = WsHttpBinding;

            // Define the STS endpoint
            EndpointAddress endpoint = new EndpointAddress(new Uri(issuerUri));

            var factory = new WSTrustChannelFactory(binding, endpoint) { TrustVersion = TrustVersion.WSTrust13 };

            // Here is where we set the credentials (goes into the SOAP security header)
            factory.Credentials.SupportInteractive = false; // Avoid that CardSpace popup...
            factory.Credentials.UserName.UserName = username;
            factory.Credentials.UserName.Password = password;

            SecurityTokenElement OnBehalfOfElement = new SecurityTokenElement(new UserNameSecurityToken("pbell", "2Federate"));
            SecurityTokenElement ActAsElement = new SecurityTokenElement(new UserNameSecurityToken("mpavlich", "2Federate"));

            // Now we define the Request for Security Token (RST)
            RequestSecurityToken RST = new RequestSecurityToken()
            {
                //identifiy who this token is for
                AppliesTo = new EndpointReference(appliesTo),
                //identify what type of request this is (Issue or Validate)
                RequestType = RequestTypes.Issue,
                //set the keytype (symmetric, asymmetric (pub key) or bearer)
                KeyType = keyType
            };

            // Create the WS-Trust channel
            IWSTrustChannelContract channel = factory.CreateChannel();

            // Send the Issue RST request
            SecurityToken token = channel.Issue(RST, out RSTR);

            return token;
        }