//https://leastprivilege.com/2010/10/28/wif-adfs-2-and-wcfpart-6-chaining-multiple-token-services/
        //https://msdn.microsoft.com/en-us/library/ee517297.aspx

        public SecurityToken GetToken(string idpEndpoint, string rstsRealm, string userName, string password)
        {
           
           var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);

            var factory = new System.ServiceModel.Security.WSTrustChannelFactory(binding, new EndpointAddress(new Uri(idpEndpoint)));
            
            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UserName.UserName = userName;
            factory.Credentials.UserName.Password = password;

            
            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:2.0:assertion"
            };

            var channel = factory.CreateChannel();
            var securityToken = channel.Issue(rst);
            return securityToken;
        }
        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;
        
        }
        protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
        {
            ValidateAppliesTo(request.AppliesTo);

            var scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials);

            if (!string.IsNullOrEmpty(ConfigurationManager.AppSettings["EncryptionCertificate"]))
            {
                // Important note on setting the encrypting credentials.
                // In a production deployment, you would need to select a certificate that is specific to the RP that is requesting the token.
                // You can examine the 'request' to obtain information to determine the certificate to use.

                var encryptingCertificate = GetCertificate(ConfigurationManager.AppSettings["EncryptionCertificate"]);
                var encryptingCredentials = new X509EncryptingCredentials(encryptingCertificate);
                scope.EncryptingCredentials = encryptingCredentials;
            }
            else
            {
                // If there is no encryption certificate specified, the STS will not perform encryption.
                // This will succeed for tokens that are created without keys (BearerTokens) or asymmetric keys.
                scope.TokenEncryptionRequired = false;
            }

            scope.ReplyToAddress = request.ReplyTo;

            return scope;
        }
        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;
        }
        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;
        }
示例#6
0
        //https://leastprivilege.com/2010/10/28/wif-adfs-2-and-wcfpart-6-chaining-multiple-token-services/
        //https://msdn.microsoft.com/en-us/library/ee517297.aspx

        public SecurityToken GetToken(string idpEndpoint, string rstsRealm, string userName, string password)
        {
            var binding = new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential);

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

            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;
            factory.Credentials.UserName.UserName  = userName;
            factory.Credentials.UserName.Password  = password;


            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:2.0:assertion"
            };

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

            return(securityToken);
        }
示例#7
0
        public bool TryIssueToken(EndpointReference appliesTo, ClaimsPrincipal principal, string tokenType,
            out SecurityToken token)
        {
            token = null;

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

            try
            {
                var rstr = _sts.Issue(principal, rst);
                token = rstr.RequestedSecurityToken.SecurityToken;
                return true;
            }
            catch (Exception e)
            {
                Tracing.Error("Failed to issue token. An exception occurred. " + e);
                return false;
            }
        }
 protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
 {
     ClaimsIdentity sourceIdentity = principal.Identities.First();
     ClaimsIdentity destinationIndentity = new ClaimsIdentity("Sample");
     CopyClaim(sourceIdentity, destinationIndentity);
     return destinationIndentity;
 }
示例#9
0
        /// <summary>
        /// Begins the async call of the Issue request.
        /// </summary>
        /// <param name="principal">The <see cref="ClaimsPrincipal"/> to issue a token for.</param>
        /// <param name="request">The security token request which includes request message as well as other client
        /// related information such as authorization context.</param>
        /// <param name="callback">The async call back.</param>
        /// <param name="state">The state object.</param>
        /// <returns>The async result.</returns>
        public virtual IAsyncResult BeginIssue(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }
            _principal = principal;
            _request   = request;

            //
            // Step 1: Validate the rst: check if this STS is capable of handling this
            // rst
            //
            ValidateRequest(request);

            //
            //



            FederatedAsyncState asyncState = new FederatedAsyncState(request, principal, new TypedAsyncResult <RSTR>(callback, state));

            BeginGetScope(principal, request, OnGetScopeComplete, asyncState);

            return(asyncState.Result);
        }
示例#10
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 override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            var outputIdentity = new ClaimsIdentity();
            IEnumerable<Claim> outputClaims;

            if (this.scopeModel.UseClaimsPolicyEngine)
            {
                IClaimsPolicyEvaluator evaluator = new ClaimsPolicyEvaluator(PolicyStoreFactory.Instance);
                outputClaims = evaluator.Evaluate(new Uri(scope.AppliesToAddress), ((ClaimsIdentity)principal.Identity).Claims);
            }
            else
            {
                outputClaims = ((ClaimsIdentity)principal.Identity).Claims;
            }

            outputIdentity.AddClaims(outputClaims);
            if (outputIdentity.Name == null && outputIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier) != null)
                outputIdentity.AddClaim(new Claim(ClaimTypes.Name, outputIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier).Value));

            var isPersistent =
                ((ClaimsIdentity)principal.Identity).Claims.SingleOrDefault(c => c.Type == ClaimTypes.IsPersistent);
            if (isPersistent != null)
            {
                outputIdentity.AddClaim(new Claim(ClaimTypes.IsPersistent, isPersistent.Value));
            }

            return outputIdentity;
        }
        protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
        {
            // Validate the AppliesTo address
            ValidateAppliesTo( request.AppliesTo );

            // Create the scope using the request AppliesTo address and the RP identity
            Scope scope = new Scope( request.AppliesTo.Uri.AbsoluteUri, _signingCreds );

            if (Uri.IsWellFormedUriString(request.ReplyTo, UriKind.Absolute))
            {
                if (request.AppliesTo.Uri.Host != new Uri(request.ReplyTo).Host)
                    scope.ReplyToAddress = request.AppliesTo.Uri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.ReplyTo;
            }
            else
            {
                Uri resultUri = null;
                if (Uri.TryCreate(request.AppliesTo.Uri, request.ReplyTo, out resultUri))
                    scope.ReplyToAddress = resultUri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.AppliesTo.Uri.ToString() ;
            }

            // Note: In this sample app only a single RP identity is shown, which is localhost, and the certificate of that RP is
            // populated as _encryptingCreds
            // If you have multiple RPs for the STS you would select the certificate that is specific to
            // the RP that requests the token and then use that for _encryptingCreds
            scope.EncryptingCredentials = _encryptingCreds;

            return scope;
        }
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (principal == null)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            // check github
            string ak = principal.FindFirst(Constants.CLAIM_TYPE_GITHUB_AK).Value;
            string openid = Utility.GetOpenId(ak);

            // check account
            ADAccountInfo info = AccountHelper.GetHelper().GetAccount(openid);

            if (info == null)
            {
                throw new InvalidRequestException("wrong github login or not binded, cannot login.");
            }

            var claims = new[]
            {
                new Claim(Constants.CLAIM_TYPE_PRIMARY_SID, info.primarysid),
                new Claim(System.IdentityModel.Claims.ClaimTypes.Upn, info.upnUpper),
                new Claim(System.IdentityModel.Claims.ClaimTypes.Upn, info.upnLower),
                new Claim(System.IdentityModel.Claims.ClaimTypes.Name, info.name),
            };

            var id = new ClaimsIdentity(claims);

            return id;
        }
        protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
        {
            ValidateAppliesTo(request.AppliesTo);

            var scope = new Scope(request.AppliesTo.Uri.AbsoluteUri, SecurityTokenServiceConfiguration.SigningCredentials);

            if (Uri.IsWellFormedUriString(request.ReplyTo, UriKind.Absolute))
            {
                if (request.AppliesTo.Uri.Host != new Uri(request.ReplyTo).Host)
                    scope.ReplyToAddress = request.AppliesTo.Uri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.ReplyTo;
            }
            else
            {
                Uri resultUri = null;
                if (Uri.TryCreate(request.AppliesTo.Uri, request.ReplyTo, out resultUri))
                    scope.ReplyToAddress = resultUri.AbsoluteUri;
                else
                    scope.ReplyToAddress = request.AppliesTo.Uri.ToString();
            }

            scope.TokenEncryptionRequired = false;
            scope.SymmetricKeyEncryptionRequired = false;

            return scope;
        }
        /// <summary>
        /// Analyzes the token request
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="request">The request.</param>
        /// <returns>A PolicyScope that describes the relying party and policy options</returns>
        protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken rst)
        {
            if (rst.AppliesTo == null)
            {
                Tracing.Error(string.Format("token request from {0} - but no realm specified.",
                    principal.Identity.Name));

                throw new Exception();
                //throw new MissingAppliesToException();
            }

            Tracing.Information(string.Format("Starting token request from {0} for {1}",
                principal.Identity.Name,
                rst.AppliesTo.Uri.AbsoluteUri));

            Tracing.Information("Authentication method: " + principal.Identities.First().FindFirst(ClaimTypes.AuthenticationMethod).Value);

            // analyze request
            var request = new Request(GlobalConfiguration);
            var details = request.Analyze(rst, principal);

            // validate against policy
            request.Validate(details);

            // create scope
            var scope = new RequestDetailsScope(
                details, 
                SecurityTokenServiceConfiguration.SigningCredentials, 
                GlobalConfiguration.RequireEncryption);

            return scope;
        }
示例#16
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);
        }
        public void Validate_NoRealm()
        {
            var rst = new RequestSecurityToken { RequestType = RequestTypes.Issue };
            var details = request.Analyze(rst, _alice);

            // unknown realm
            request.Validate();
        }
        /// <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;
        }
 protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
 {
     return new Scope(
         request.AppliesTo.Uri.AbsoluteUri,
         this.SecurityTokenServiceConfiguration.SigningCredentials)
         {
             ReplyToAddress = request.ReplyTo,
             TokenEncryptionRequired = false
         };
 }
        private static RequestSecurityToken CreateBearerRst(EndpointAddress appliesTo)
        {
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointReference(appliesTo.Uri.AbsoluteUri),
                KeyType = KeyTypes.Bearer
            };

            return rst;
        }
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var config = ClaimsConfiguration.ConfigurationFactory();
            var realm = request.AppliesTo.Uri.AbsoluteUri;
            var claims = new List<Claim>();

            claims.AddRange(GetClaimsForRealm("common", config));
            claims.AddRange(GetClaimsForRealm(realm,config));

            return new ClaimsIdentity(claims);
        }
            /// <summary>
            /// Copy constructor.
            /// </summary>
            /// <param name="federatedAsyncState">The input FederatedAsyncState instance.</param>
            /// <exception cref="ArgumentNullException">The input 'FederatedAsyncState' is null.</exception>
            public FederatedAsyncState(FederatedAsyncState federatedAsyncState)
            {
                if (null == federatedAsyncState)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("FederatedAsyncState");
                }

                _request = federatedAsyncState.Request;
                _claimsPrincipal = federatedAsyncState.ClaimsPrincipal;
                _securityTokenHandler = federatedAsyncState.SecurityTokenHandler;
                _result = federatedAsyncState.Result;
            }
示例#23
0
            /// <summary>
            /// Copy constructor.
            /// </summary>
            /// <param name="federatedAsyncState">The input FederatedAsyncState instance.</param>
            /// <exception cref="ArgumentNullException">The input 'FederatedAsyncState' is null.</exception>
            public FederatedAsyncState(FederatedAsyncState federatedAsyncState)
            {
                if (null == federatedAsyncState)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("FederatedAsyncState");
                }

                _request              = federatedAsyncState.Request;
                _claimsPrincipal      = federatedAsyncState.ClaimsPrincipal;
                _securityTokenHandler = federatedAsyncState.SecurityTokenHandler;
                _result = federatedAsyncState.Result;
            }
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var claims = new[]
                {
                    new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name),
                    new Claim(System.IdentityModel.Claims.ClaimTypes.NameIdentifier, principal.Identity.Name),
                };

            var identity = new ClaimsIdentity(claims);

            return identity;
        }
 protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
 {
     var scope = new Scope(request.AppliesTo.Uri.AbsoluteUri,
         this.SecurityTokenServiceConfiguration.SigningCredentials)
                 {
                     TokenEncryptionRequired = false
                 };
     scope.ReplyToAddress = string.IsNullOrWhiteSpace(request.ReplyTo)
         ? scope.AppliesToAddress
         : scope.ReplyToAddress;
     return scope;
 }
        public RequestDetails Analyze(RequestSecurityToken rst, ClaimsPrincipal principal)
        {
            if (rst == null)
            {
                throw new ArgumentNullException("rst");
            }

            if (principal == null)
            {
                throw new ArgumentNullException("principal");
            }

            Tracing.Information("Starting PolicyOptions creation");

            var clientIdentity = AnalyzeClientIdentity(principal);

            var details = new RequestDetails
            {
                ClientIdentity = clientIdentity,
                IsActive = false,
                Realm = null,
                IsKnownRealm = false,
                UsesSsl = false,
                UsesEncryption = false,
                ReplyToAddress = null,
                ReplyToAddressIsWithinRealm = false,
                IsReplyToFromConfiguration = false,
                EncryptingCertificate = null,
                ClaimsRequested = false,
                RequestClaims = null,
                Request = null,
                IsActAsRequest = false,
                RelyingPartyRegistration = null
            };

            AnalyzeRst(rst, details);
            AnalyzeTokenType(rst, details);
            AnalyzeKeyType(rst);
            AnalyzeRealm(rst, details);
            AnalyzeOperationContext(details);
            AnalyzeDelegation(rst, details);
            AnalyzeRelyingParty(details);
            AnalyzeEncryption(details);
            AnalyzeReplyTo(details);
            AnalyzeSsl(details);
            AnalyzeRequestClaims(details);

            Tracing.Information("PolicyOptions creation done.");

            _details = details;
            return details;
        }
        /// <summary>
        /// Override of the base class that reads a child element inside the RST
        /// </summary>
        /// <param name="reader">Reader pointing at an element to read inside the RST.</param>
        /// <param name="rst">The RequestSecurityToken element that is being populated from the reader.</param>
        /// <param name="context">Current Serialization context.</param>
        /// <exception cref="ArgumentNullException">Either reader or rst or context parameter is null.</exception>
        /// <exception cref="WSTrustSerializationException">Unable to deserialize the current parameter.</exception>
        public override void ReadXmlElement(XmlReader reader, RequestSecurityToken rst, WSTrustSerializationContext context)
        {
            if (reader == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("reader");
            }

            if (rst == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst");
            }

            if (context == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("context");
            }

            // special case SecondaryParameters, they cannot be embeded as per WS-Trust 1.3
            if (reader.IsStartElement(WSTrust13Constants.ElementNames.SecondaryParameters, WSTrust13Constants.NamespaceURI))
            {
                rst.SecondaryParameters = this.ReadSecondaryParameters(reader, context);
                return;
            }

            if (reader.IsStartElement(WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI))
            {
                rst.KeyWrapAlgorithm = reader.ReadElementContentAsString();
                if (!UriUtil.CanCreateValidUri(rst.KeyWrapAlgorithm, UriKind.Absolute))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3135, WSTrust13Constants.ElementNames.KeyWrapAlgorithm, WSTrust13Constants.NamespaceURI, rst.KeyWrapAlgorithm)));
                }

                return;
            }

            if (reader.IsStartElement(WSTrust13Constants.ElementNames.ValidateTarget, WSTrust13Constants.NamespaceURI))
            {
                if (!reader.IsEmptyElement)
                {
                    rst.ValidateTarget = new SecurityTokenElement(WSTrustSerializationHelper.ReadInnerXml(reader), context.SecurityTokenHandlers);
                }

                if (rst.ValidateTarget == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new WSTrustSerializationException(SR.GetString(SR.ID3221)));
                }

                return;
            }

            WSTrustSerializationHelper.ReadRSTXml(reader, rst, context, WSTrustConstantsAdapter.Trust13);
        }
示例#28
0
        /// <summary>
        /// Validates the RequestSecurityToken encapsulated by this SecurityTokenService instance.
        /// </summary>
        protected virtual void ValidateRequest(RST request)
        {
            // currently we only support RST/RSTR pattern
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2051)));
            }

            // STS only support Issue for now
            if (request.RequestType != null && request.RequestType != RequestTypes.Issue)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2052)));
            }

            // key type must be one of the known types
            if (request.KeyType != null && !IsKnownType(request.KeyType))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2053)));
            }

            // if key type is bearer key, we should fault if the KeySize element is present and its value is not equal to zero.
            if (StringComparer.Ordinal.Equals(request.KeyType, KeyTypes.Bearer) && request.KeySizeInBits.HasValue && (request.KeySizeInBits.Value != 0))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2050)));
            }

            // token type must be supported for this STS
            if (GetSecurityTokenHandler(request.TokenType) == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new UnsupportedTokenTypeBadRequestException(request.TokenType));
            }

            request.KeyType = (string.IsNullOrEmpty(request.KeyType)) ? KeyTypes.Symmetric : request.KeyType;

            if (StringComparer.Ordinal.Equals(request.KeyType, KeyTypes.Symmetric))
            {
                //
                // Check if the key size is within certain limit to prevent Dos attack
                //
                if (request.KeySizeInBits.HasValue)
                {
                    if (request.KeySizeInBits.Value > _securityTokenServiceConfiguration.DefaultMaxSymmetricKeySizeInBits)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID2056, request.KeySizeInBits.Value, _securityTokenServiceConfiguration.DefaultMaxSymmetricKeySizeInBits)));
                    }
                }
                else
                {
                    request.KeySizeInBits = _securityTokenServiceConfiguration.DefaultSymmetricKeySizeInBits;
                }
            }
        }
 protected override Scope GetScope(ClaimsPrincipal principal, RequestSecurityToken request)
 {
     var scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials)
     {
         ReplyToAddress = request.ReplyTo,
         TokenEncryptionRequired = false,
     };
     if (_encryptingCredentials != null)
     {
         scope.EncryptingCredentials = _encryptingCredentials;
     }
     return scope;
 }
        protected override ClaimsIdentity GetOutputClaimsIdentity( ClaimsPrincipal principal, RequestSecurityToken request, Scope scope )
        {
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();
            outgoingIdentity.AddClaims(principal.Claims);

            List<Role> roles = (List<Role>)HttpContext.Current.Session["User_Roles_" + principal.Identity.Name];

            RBACHelper rbacHelper = new RBACHelper();
            Permission[] permissions = rbacHelper.GetUserPermissions(Factory.Session(Factory.User(principal.Identity.Name), roles.ToArray()));

            outgoingIdentity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/permissions", Serialize(permissions)));

            return outgoingIdentity;
        }
        protected override Scope GetScope(ClaimsPrincipal claimsPrincipal, RequestSecurityToken requestSecurityToken)
        {
            if (requestSecurityToken.AppliesTo == null)
            {
                throw new InvalidRequestException("Request for security token does not have a realm.");
            }
            var scope = new Scope(requestSecurityToken.AppliesTo.Uri.AbsoluteUri,
                this.securityTokenServiceConfiguration.SigningCredentials)
                {TokenEncryptionRequired = false,
                    ReplyToAddress = requestSecurityToken.AppliesTo.Uri.AbsoluteUri};

            requestSecurityToken.TokenType = SamlTwoTokenType;

            return scope;
        }
        /// <summary>
        /// Validates the RequestSecurityToken object that has been deserialized.
        /// </summary>
        /// <param name="requestSecurityToken">The RequestSecurityToken object to Validate.</param>
        /// <exception cref="InvalidOperationException">An Issue Request for an Asymmetric Key did not specify UseKey.</exception>
        public virtual void Validate(RequestSecurityToken requestSecurityToken)
        {
            if (requestSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("rst");
            }

            // Validate the RequestSecurityToken required parameters.
            if ((StringComparer.Ordinal.Equals(requestSecurityToken.RequestType, RequestTypes.Issue) || requestSecurityToken.RequestType == null) &&
                 StringComparer.Ordinal.Equals(requestSecurityToken.KeyType, KeyTypes.Asymmetric) &&
                 ((requestSecurityToken.UseKey == null) || (requestSecurityToken.UseKey.SecurityKeyIdentifier == null && requestSecurityToken.UseKey.Token == null)))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID3091)));
            }
        }
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var claims = new[]
                {
                    new System.Security.Claims.Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name),
                    new System.Security.Claims.Claim(System.IdentityModel.Claims.ClaimTypes.NameIdentifier, principal.Identity.Name),
                    new System.Security.Claims.Claim(System.IdentityModel.Claims.ClaimTypes.PostalCode, "92110"),
                    new System.Security.Claims.Claim(System.IdentityModel.Claims.ClaimTypes.Country, "France"),
                    new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Role, "Admin"),
                };

            var identity = new ClaimsIdentity(claims);

            return identity;
        }
            /// <summary>
            /// Constructs a FederatedAsyncState instance with token request, principal, and the async result.
            /// </summary>
            /// <param name="request">The token request instance.</param>
            /// <param name="principal">The identity of the token requestor.</param>
            /// <param name="result">The async result.</param>
            /// <exception cref="ArgumentNullException">When the given request or async result is null.</exception>
            public FederatedAsyncState(RST request, ClaimsPrincipal principal, IAsyncResult result)
            {
                if (null == request)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
                }

                if (null == result)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
                }

                _request = request;
                _claimsPrincipal = principal;
                _result = result;
            }
示例#35
0
            /// <summary>
            /// Constructs a FederatedAsyncState instance with token request, principal, and the async result.
            /// </summary>
            /// <param name="request">The token request instance.</param>
            /// <param name="principal">The identity of the token requestor.</param>
            /// <param name="result">The async result.</param>
            /// <exception cref="ArgumentNullException">When the given request or async result is null.</exception>
            public FederatedAsyncState(RST request, ClaimsPrincipal principal, IAsyncResult result)
            {
                if (null == request)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
                }

                if (null == result)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
                }

                _request         = request;
                _claimsPrincipal = principal;
                _result          = result;
            }
示例#36
0
        /// <summary>
        /// Creates an instance of a <see cref="SecurityTokenDescriptor"/>.
        /// </summary>
        /// <param name="request">The incoming token request.</param>
        /// <param name="scope">The <see cref="Scope"/> object returned from <see cref="SecurityTokenService.GetScope"/>.</param>
        /// <returns>The <see cref="SecurityTokenDescriptor"/>.</returns>
        /// <remarks>Invoked during token issuance after <see cref="SecurityTokenService.GetScope"/>.</remarks>
        protected virtual SecurityTokenDescriptor CreateSecurityTokenDescriptor(RST request, Scope scope)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }

            if (scope == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("scope");
            }

            SecurityTokenDescriptor d = new SecurityTokenDescriptor();

            d.AppliesToAddress   = scope.AppliesToAddress;
            d.ReplyToAddress     = scope.ReplyToAddress;
            d.SigningCredentials = scope.SigningCredentials;
            if (null == d.SigningCredentials)
            {
                d.SigningCredentials = this.SecurityTokenServiceConfiguration.SigningCredentials;
            }



            //
            // The encrypting credentials specified on the Scope object
            // are invariant relative to a specific RP. Allowing the STS to
            // cache the Scope for each RP.
            // Our default implementation will generate the symmetric bulk
            // encryption key on the fly.
            //
            if (scope.EncryptingCredentials != null &&
                scope.EncryptingCredentials.SecurityKey is AsymmetricSecurityKey
                )
            {
                if ((request.EncryptionAlgorithm == null || request.EncryptionAlgorithm == SecurityAlgorithms.Aes256Encryption) &&
                    (request.SecondaryParameters == null || request.SecondaryParameters.EncryptionAlgorithm == null || request.SecondaryParameters.EncryptionAlgorithm == SecurityAlgorithms.Aes256Encryption)
                    )
                {
                    d.EncryptingCredentials = new EncryptedKeyEncryptingCredentials(scope.EncryptingCredentials, 256, SecurityAlgorithms.Aes256Encryption);
                }
            }

            return(d);
        }
示例#37
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();
            }
        }
        /// <summary>
        /// Constructor for the WSTrustRequestBodyWriter.
        /// </summary>
        /// <param name="requestSecurityToken">The RequestSecurityToken object to be serialized in the outgoing Message.</param>
        /// <param name="serializer">Serializer is responsible for writting the requestSecurityToken into a XmlDictionaryWritter.</param>
        /// <param name="serializationContext">Context for the serialization.</param>
        /// <exception cref="ArgumentNullException">The 'requestSecurityToken' is null.</exception>
        /// <exception cref="ArgumentNullException">The 'serializer' is null.</exception>
        /// <exception cref="ArgumentNullException">The 'serializationContext' is null.</exception>
        public WSTrustRequestBodyWriter(System.IdentityModel.Protocols.WSTrust.RequestSecurityToken requestSecurityToken, WSTrustRequestSerializer serializer, WSTrustSerializationContext serializationContext)
            : base(true)
        {
            if (requestSecurityToken == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("requestSecurityToken");
            }

            if (serializer == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializer");
            }

            if (serializationContext == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serializationContext");
            }

            _requestSecurityToken = requestSecurityToken;
            _serializer           = serializer;
            _serializationContext = serializationContext;
        }
示例#39
0
        /// <summary>
        /// Creates the RSTR and finally read the information from TokenDescriptor and apply
        /// those to the RSTR.
        /// </summary>
        /// <param name="request">The RST from the request.</param>
        /// <param name="tokenDescriptor">The token descriptor which contains the information for the issued token.</param>
        /// <returns>The RSTR for the response, null if the token descriptor is null.</returns>
        protected virtual RSTR GetResponse(RST request, SecurityTokenDescriptor tokenDescriptor)
        {
            if (tokenDescriptor != null)
            {
                RSTR rstr = new RSTR(request);
                tokenDescriptor.ApplyTo(rstr);

                // Set the replyTo address of the relying party (if any) in the outgoing RSTR from the generated
                // token descriptor (STD)  based on the table below:
                //
                // RST.ReplyTo       STD.ReplyToAddress            RSTR.ReplyTo
                // ===========       ====================          ============
                // Set               Not Set                       Not Set
                // Set               Set                           Set to STD.ReplyToAddress
                // Not Set           Not Set                       Not Set
                // Not Set           Set                           Not Set
                //
                if (request.ReplyTo != null)
                {
                    rstr.ReplyTo = tokenDescriptor.ReplyToAddress;
                }

                //
                // Set the appliesTo address (if any) in the outgoing RSTR from the generated token descriptor.
                //
                if (!string.IsNullOrEmpty(tokenDescriptor.AppliesToAddress))
                {
                    rstr.AppliesTo = new EndpointReference(tokenDescriptor.AppliesToAddress);
                }

                return(rstr);
            }
            else
            {
                return(null);
            }
        }
示例#40
0
 /// <summary>
 /// Retrieves the relying party information. Override this method to provide a custom scope with
 /// relying party related information.
 /// </summary>
 /// <param name="principal">The identity of the token requestor.</param>
 /// <param name="request">The request message.</param>
 /// <returns>A scope object based on the relying party related information.</returns>
 protected abstract Scope GetScope(ClaimsPrincipal principal, RST request);
示例#41
0
 /// <summary>
 /// Begins async call for GetScope routine. Default implementation will throw a NotImplementedExcetion.
 /// Refer MSDN articles on Using an AsyncCallback Delegate to End an Asynchronous Operation.
 /// </summary>
 /// <param name="principal">The identity of the token requestor.</param>
 /// <param name="request">The request.</param>
 /// <param name="callback">The callback to be invoked when the user Asynchronous operation completed.</param>
 /// <param name="state">The state object.</param>
 /// <returns>IAsyncResult. Represents the status of an asynchronous operation. This will be passed into
 /// EndGetScope.</returns>
 protected virtual IAsyncResult BeginGetScope(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotImplementedException(SR.GetString(SR.ID2081)));
 }
示例#42
0
 /// <summary>
 /// Async Validate.
 /// </summary>
 /// <param name="principal">The <see cref="ClaimsPrincipal"/> to validate.</param>
 /// <param name="request">The security token request which includes request message as well as other client
 /// related information such as authorization context.</param>
 /// <param name="callback">The async call back.</param>
 /// <param name="state">The state object.</param>
 /// <returns>The async result.</returns>
 public virtual IAsyncResult BeginValidate(ClaimsPrincipal principal, RST request, AsyncCallback callback, object state)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Validate"))));
 }
示例#43
0
 /// <summary>
 /// Cancel.
 /// </summary>
 /// <param name="principal">The <see cref="ClaimsPrincipal"/> to cancel.</param>
 /// <param name="request">The request.</param>
 /// <returns>The response.</returns>
 public virtual RSTR Cancel(ClaimsPrincipal principal, RST request)
 {
     throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3141, (request != null && request.RequestType != null ? request.RequestType : "Cancel"))));
 }
示例#44
0
        public ActionResult Index()
        {
            System.ServiceModel.Security.WSTrustChannelFactory factory = null;

            System.Net.ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(RemoteServerCertificateValidationCallback);

            try
            {
                // use a UserName Trust Binding for username authentication
                factory = new System.ServiceModel.Security.WSTrustChannelFactory(
                    new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential),
                    new EndpointAddress("https://win-dcftr8akk4s.dealertracktest.com/adfs/services/trust/13/usernamemixed"));

                factory.TrustVersion = TrustVersion.WSTrust13;


                factory.Credentials.UserName.UserName        = "******";
                factory.Credentials.UserName.Password        = "******";
                factory.Credentials.SupportInteractive       = false;
                factory.Credentials.UseIdentityConfiguration = true;

                var rst = new System.IdentityModel.Protocols.WSTrust.RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference("https://win-dcftr8akk4s.dealertracktest.com/publish/"),//
                    KeyType     = KeyTypes.Bearer,
                    //  TokenType= "urn:oasis:names:tc:SAML:2.0:assertion",
                    // ReplyTo ="https://sts.pcmidev.com/adfs/services/trust/13/issuedtokenmixedsymmetricbasic256"
                    //RequestDisplayToken = true,
                };

                System.ServiceModel.Security.IWSTrustChannelContract channel = factory.CreateChannel();
                System.IdentityModel.Protocols.WSTrust.RequestSecurityTokenResponse rstr;
                var    token        = channel.Issue(rst, out rstr) as GenericXmlSecurityToken;
                string Site         = "https://win-dcftr8akk4s.dealertracktest.com/publish/";
                var    prepareToken = WrapInSoapMessage(token, Site);
                var    samlServer   = Site.EndsWith("/") ? Site : Site + "/";
                var    stringData   = $"wa=wsignin1.0&wresult={HttpUtility.UrlEncode(prepareToken)}&wctx={HttpUtility.UrlEncode("rm=1&id=passive&ru=/home")}";

                var cookies = new CookieContainer();
                var request = WebRequest.Create(samlServer) as HttpWebRequest;

                request.Method            = "POST";
                request.ContentType       = "application/x-www-form-urlencoded";
                request.CookieContainer   = cookies;
                request.AllowAutoRedirect = true;
                var data = Encoding.UTF8.GetBytes(stringData);
                request.ContentLength = data.Length;

                using (var stream = request.GetRequestStream())
                {
                    stream.Write(data, 0, data.Length);
                }

                using (var response = request.GetResponse() as HttpWebResponse)
                {
                    using (var stream = response.GetResponseStream())
                    {
                        using (var reader = new StreamReader(stream))
                        {
                            var responseFromServer = reader.ReadToEnd();
                        }
                    }
                }
            }
            finally
            {
                if (factory != null)
                {
                    try
                    {
                        factory.Close();
                    }
                    catch (CommunicationObjectFaultedException)
                    {
                        factory.Abort();
                    }
                }
            }
            Response.Redirect("https://win-dcftr8akk4s.dealertracktest.com/publish/");
            //HttpContext.Current.RewritePath("https://win-dcftr8akk4s.dealertracktest.com/publish/");
            return(View("home"));
        }
示例#45
0
        /// <summary>
        /// Gets the proof token.
        /// </summary>
        /// <param name="request">The incoming token request.</param>
        /// <param name="scope">The scope instance encapsulating information about the relying party.</param>
        /// <returns>The newly created proof decriptor that could be either asymmetric proof descriptor or symmetric proof descriptor or null in the bearer token case.</returns>
        protected virtual ProofDescriptor GetProofToken(RST request, Scope scope)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }

            if (scope == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("scope");
            }

            EncryptingCredentials requestorWrappingCredentials = GetRequestorProofEncryptingCredentials(request);

            if (scope.EncryptingCredentials != null &&
                !(scope.EncryptingCredentials.SecurityKey is AsymmetricSecurityKey))
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                          new SecurityTokenException(SR.GetString(SR.ID4179)));
            }

            EncryptingCredentials targetWrappingCredentials = scope.EncryptingCredentials;

            //
            // Generate the proof key
            //
            string          keyType = (string.IsNullOrEmpty(request.KeyType)) ? KeyTypes.Symmetric : request.KeyType;
            ProofDescriptor result  = null;

            if (StringComparer.Ordinal.Equals(keyType, KeyTypes.Asymmetric))
            {
                //
                // Asymmetric is only supported with UseKey
                //
                if (request.UseKey == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidRequestException(SR.GetString(SR.ID3091)));
                }

                result = new AsymmetricProofDescriptor(request.UseKey.SecurityKeyIdentifier);
            }
            else if (StringComparer.Ordinal.Equals(keyType, KeyTypes.Symmetric))
            {
                //
                // Only support PSHA1. Overwrite STS to support custom key algorithm
                //
                if (request.ComputedKeyAlgorithm != null && !StringComparer.Ordinal.Equals(request.ComputedKeyAlgorithm, ComputedKeyAlgorithms.Psha1))
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID2011, request.ComputedKeyAlgorithm)));
                }
                //
                // We must wrap the symmetric key inside the security token
                //
                if (targetWrappingCredentials == null && scope.SymmetricKeyEncryptionRequired)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID4007)));
                }

                //
                // We are encrypting the proof token or the server entropy using client's encrypting credential if present,
                // which will be used to encrypt the key during serialization.
                // Otherwise, we can only send back the key in plain text. However, the current implementation of
                // WSTrustServiceContract sets the rst.ProofEncryption = null by default. Therefore, the server entropy
                // or the proof token will be sent in plain text no matter the client's entropy is sent encrypted or unencrypted.
                //
                if (request.KeySizeInBits.HasValue)
                {
                    if (request.Entropy != null)
                    {
                        result = new SymmetricProofDescriptor(request.KeySizeInBits.Value, targetWrappingCredentials, requestorWrappingCredentials,
                                                              request.Entropy.GetKeyBytes(), request.EncryptWith);
                    }
                    else
                    {
                        result = new SymmetricProofDescriptor(request.KeySizeInBits.Value, targetWrappingCredentials,
                                                              requestorWrappingCredentials, request.EncryptWith);
                    }
                }
                else
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID2059)));
                }
            }
            else if (StringComparer.Ordinal.Equals(keyType, KeyTypes.Bearer))
            {
                //
                // Intentionally empty, no proofDescriptor
                //
            }

            return(result);
        }
示例#46
0
        /// <summary>
        /// Get the Requestor's Proof encrypting credentials.
        /// </summary>
        /// <param name="request">RequestSecurityToken</param>
        /// <returns>EncryptingCredentials</returns>
        /// <exception cref="ArgumentNullException">Input argument 'request' is null.</exception>
        protected virtual EncryptingCredentials GetRequestorProofEncryptingCredentials(RST request)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }

            if (request.ProofEncryption == null)
            {
                return(null);
            }

            X509SecurityToken x509SecurityToken = request.ProofEncryption.GetSecurityToken() as X509SecurityToken;

            if (x509SecurityToken != null)
            {
                return(new X509EncryptingCredentials(x509SecurityToken));
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new RequestFailedException(SR.GetString(SR.ID2084, request.ProofEncryption.GetSecurityToken())));
        }
示例#47
0
        /// <summary>
        /// The callback that is invoked on the completion of the BeginGetOutputSubjects call.
        /// </summary>
        /// <param name="result">The async result.</param>
        /// <exception cref="ArgumentNullException">When the given async result is null.</exception>
        void OnGetOutputClaimsIdentityComplete(IAsyncResult result)
        {
            if (null == result)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
            }

            FederatedAsyncState state = result.AsyncState as FederatedAsyncState;

            if (state == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2001)));
            }

            SecurityTokenHandler securityTokenHandler = state.SecurityTokenHandler;

            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2016)));
            }

            Exception unhandledException = null;
            RST       request            = state.Request;
            RSTR      response           = null;

            TypedAsyncResult <RSTR> typedResult = state.Result as TypedAsyncResult <RSTR>;

            if (typedResult == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2004, typeof(TypedAsyncResult <RSTR>), state.Result.GetType())));
            }

            try
            {
                //
                // get token descriptor
                //
                if (_tokenDescriptor == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003));
                }
                // Step 7: Retrieve the output claims to be included in the issued-token
                _tokenDescriptor.Subject = EndGetOutputClaimsIdentity(result);

                //
                // Use the retrieved securityTokenHandler to create and setup the issued token information on the tokenDescriptor
                // (actual issued token, AttachedReference and UnattachedReference)
                // TokenType is preserved from the request if possible
                if (!string.IsNullOrEmpty(request.TokenType))
                {
                    _tokenDescriptor.TokenType = request.TokenType;
                }
                else
                {
                    string[] identifiers = securityTokenHandler.GetTokenTypeIdentifiers();
                    if (identifiers == null || identifiers.Length == 0)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4264, request.TokenType)));
                    }
                    _tokenDescriptor.TokenType = identifiers[0];
                }
                _tokenDescriptor.Token               = securityTokenHandler.CreateToken(_tokenDescriptor);
                _tokenDescriptor.AttachedReference   = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, true);
                _tokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, false);

                // 9. Create the RSTR
                response = GetResponse(request, _tokenDescriptor);
            }
#pragma warning suppress 56500
            catch (Exception e)
            {
                if (System.Runtime.Fx.IsFatal(e))
                {
                    throw;
                }

                unhandledException = e;
            }

            typedResult.Complete(response, typedResult.CompletedSynchronously, unhandledException);
        }
示例#48
0
        /// <summary>
        /// This routine processes the stored data about the target resource
        /// for who the Issued token is for.
        /// </summary>
        /// <param name="result">The async result.</param>
        /// <exception cref="ArgumentNullException">When the given async result is null.</exception>
        void OnGetScopeComplete(IAsyncResult result)
        {
            if (null == result)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("result");
            }

            FederatedAsyncState state = result.AsyncState as FederatedAsyncState;

            if (state == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2001)));
            }

            Exception unhandledException        = null;
            TypedAsyncResult <RSTR> typedResult = state.Result as TypedAsyncResult <RSTR>;

            if (typedResult == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID2004, typeof(TypedAsyncResult <RSTR>), state.Result.GetType())));
            }

            RST request = state.Request;

            try
            {
                //
                // 2. Retrieve the scope information
                //
                Scope scope = EndGetScope(result);
                if (scope == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2013));
                }
                this.Scope = scope;

                //
                // Create a security token descriptor
                //
                this.SecurityTokenDescriptor = CreateSecurityTokenDescriptor(request, this.Scope);
                if (this.SecurityTokenDescriptor == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003));
                }

                if (this.SecurityTokenDescriptor.SigningCredentials == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2079));
                }

                //
                // If TokenEncryptionRequired is set to true, then we must encrypt the token.
                //
                if (this.Scope.TokenEncryptionRequired && this.SecurityTokenDescriptor.EncryptingCredentials == null)
                {
                    throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4184));
                }

                //
                // Step 3: Retrieve the token handler to use for creating token and store it in the state
                //
                SecurityTokenHandler securityTokenHandler = GetSecurityTokenHandler(request == null ? null : request.TokenType);
                if (securityTokenHandler == null)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID4010, request == null ? String.Empty : request.TokenType)));
                }
                state.SecurityTokenHandler = securityTokenHandler;

                //
                // Step 4: Logical issuer name
                //
                _tokenDescriptor.TokenIssuerName = GetValidIssuerName();

                //
                // Step 5: Establish token lifetime
                //
                _tokenDescriptor.Lifetime = GetTokenLifetime(request == null ? null : request.Lifetime);

                //
                // Step 6: Compute the proof key
                //
                _tokenDescriptor.Proof = GetProofToken(request, this.Scope);

                //
                // Start the async call for generating the output subjects.
                //
                BeginGetOutputClaimsIdentity(state.ClaimsPrincipal, state.Request, scope, OnGetOutputClaimsIdentityComplete, state);
            }
#pragma warning suppress 56500
            catch (Exception e)
            {
                if (System.Runtime.Fx.IsFatal(e))
                {
                    throw;
                }

                unhandledException = e;
            }

            if (unhandledException != null)
            {
                //
                // Complete the request in failure
                //
                typedResult.Complete(null, result.CompletedSynchronously, unhandledException);
            }
        }
示例#49
0
 /// <summary>
 /// When overridden in the derived class writes a child element inside the RST.
 /// </summary>
 /// <param name="writer">Writer to which the RST is serialized. </param>
 /// <param name="elementName">The Local name of the element to be written.</param>
 /// <param name="elementValue">The value of the element.</param>
 /// <param name="requestSecurityToken">The entire RST object that is being serialized.</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteXmlElement(XmlWriter writer, string elementName, object elementValue, RequestSecurityToken requestSecurityToken, WSTrustSerializationContext context);
示例#50
0
 /// <summary>
 /// When overriden in the derived class serializes the given RequestSecurityToken into the XmlWriter
 /// </summary>
 /// <param name="request">RequestSecurityToken object to be serialized</param>
 /// <param name="writer">XML writer to serialize into</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteXml(RequestSecurityToken request, XmlWriter writer, WSTrustSerializationContext context);
示例#51
0
        /// <summary>
        /// Issues a Security Token.
        /// </summary>
        /// <param name="principal">The identity of the token requestor.</param>
        /// <param name="request">The request.</param>
        /// <returns>The response.</returns>
        public virtual RSTR Issue(ClaimsPrincipal principal, RST request)
        {
            if (request == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("request");
            }

            _principal = principal;
            _request   = request;

            // 1. Do request validation
            ValidateRequest(request);

            // 2. Get the scope and populate into tokenDescriptor
            Scope scope = GetScope(principal, request);

            if (scope == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2013));
            }
            this.Scope = scope;


            // Create the security token descriptor now that we have a scope.
            this.SecurityTokenDescriptor = CreateSecurityTokenDescriptor(request, scope);
            if (this.SecurityTokenDescriptor == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2003));
            }

            if (this.SecurityTokenDescriptor.SigningCredentials == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID2079));
            }

            //
            // If TokenEncryptionRequired is set to true, then we must encrypt the token.
            //
            if (this.Scope.TokenEncryptionRequired && this.SecurityTokenDescriptor.EncryptingCredentials == null)
            {
                throw DiagnosticUtility.ThrowHelperInvalidOperation(SR.GetString(SR.ID4184));
            }

            // 3. Get the token-handler
            SecurityTokenHandler securityTokenHandler = GetSecurityTokenHandler(request.TokenType);

            if (securityTokenHandler == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new NotSupportedException(SR.GetString(SR.ID4010, request.TokenType)));
            }


            // 4. Get the issuer name and populate into tokenDescriptor
            _tokenDescriptor.TokenIssuerName = GetValidIssuerName();

            // 5. Get the token lifetime and populate into tokenDescriptor
            _tokenDescriptor.Lifetime = GetTokenLifetime(request.Lifetime);

            // 6. Get the proof token and populate into tokenDescriptor
            _tokenDescriptor.Proof = GetProofToken(request, scope);

            // 7. Get the subjects and populate into tokenDescriptor
            _tokenDescriptor.Subject = GetOutputClaimsIdentity(principal, request, scope);

            // use the securityTokenHandler from Step 3 to create and setup the issued token information on the tokenDescriptor
            // (actual issued token, AttachedReference and UnattachedReference)
            // TokenType is preserved from the request if possible
            if (!string.IsNullOrEmpty(request.TokenType))
            {
                _tokenDescriptor.TokenType = request.TokenType;
            }
            else
            {
                string[] identifiers = securityTokenHandler.GetTokenTypeIdentifiers();
                if (identifiers == null || identifiers.Length == 0)
                {
                    throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.ID4264, request.TokenType)));
                }
                _tokenDescriptor.TokenType = identifiers[0];
            }
            _tokenDescriptor.Token               = securityTokenHandler.CreateToken(_tokenDescriptor);
            _tokenDescriptor.AttachedReference   = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, true);
            _tokenDescriptor.UnattachedReference = securityTokenHandler.CreateSecurityTokenReference(_tokenDescriptor.Token, false);

            // 9. Create the RSTR
            RSTR rstr = GetResponse(request, _tokenDescriptor);

            return(rstr);
        }
示例#52
0
 /// <summary>
 /// When overridden in the derived class reads a child element inside RST.
 /// </summary>
 /// <param name="reader">Reader pointing at an element to read inside the RST.</param>
 /// <param name="requestSecurityToken">The RequestSecurityToken element that is being populated from the reader.</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void ReadXmlElement(XmlReader reader, RequestSecurityToken requestSecurityToken, WSTrustSerializationContext context);
示例#53
0
 /// <summary>
 /// When overriden in the derived classs writes out the supported elements on the request object.
 /// </summary>
 /// <param name="requestSecurityToken">The request instance</param>
 /// <param name="writer">The writer to write to</param>
 /// <param name="context">Current Serialization context.</param>
 public abstract void WriteKnownRequestElement(RequestSecurityToken requestSecurityToken, XmlWriter writer, WSTrustSerializationContext context);