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;
        }
Beispiel #2
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");
    }
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            Scope scope = new Scope(request.AppliesTo.Uri.AbsoluteUri, SecurityTokenServiceConfiguration.SigningCredentials);

            string encryptingCertificateName = WebConfigurationManager.AppSettings[ApplicationSettingsNames.EncryptingCertificateName];
            if (!string.IsNullOrEmpty(encryptingCertificateName))
            {
                scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtilities.GetCertificate(StoreName.My, StoreLocation.LocalMachine, encryptingCertificateName));
            }
            else
            {
                scope.TokenEncryptionRequired = false;
            }

            if (!string.IsNullOrEmpty(request.ReplyTo))
            {
                scope.ReplyToAddress = request.ReplyTo;
            }
            else
            {
                scope.ReplyToAddress = scope.AppliesToAddress;
            }

            return scope;
        }
        /// <summary>
        /// Returns the configuration for the token issuance request.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming request security token.</param>
        /// <returns>The scope information to be used for the token issuance.</returns>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            // Verify the request, i.e. the requesting realm. The reply address does not need to be
            // checked since it is being hardcoded within this security token service and does not
            // depend on the request hence.
            var appliesTo = request.AppliesTo.Uri.AbsoluteUri;
            if(appliesTo != "http://www.silkveil.net/")
            {
                throw new SecurityException(string.Format(CultureInfo.CurrentUICulture,
                    "The uri '{0}' is not supported.", appliesTo));
            }

            // Create the scope.
            var scope = new Scope(
                request.AppliesTo.Uri.OriginalString,
                this.SecurityTokenServiceConfiguration.SigningCredentials,
                new X509EncryptingCredentials(new CertificateManager().GetEncryptingCertificate()));

            // Get the navigation service.
            var navigationService = this._container.Resolve<INavigationService>();

            // Set the reply to address.
            scope.ReplyToAddress = navigationService.GetUIPath();

            // Return the scope to the caller.
            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(IClaimsPrincipal principal, RequestSecurityToken rst)
        {
            if (rst.AppliesTo == null)
            {
                Tracing.Error(string.Format("token request from {0} - but no realm specified.",
                    principal.Identity.Name));

                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().GetClaimValue(ClaimTypes.AuthenticationMethod));

            // 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;
        }
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            throw new NotImplementedException();

            var scope = new Scope();
            return scope;
        }
        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;
        }
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            ValidateAppliesTo(request.AppliesTo);

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

            var settings = ServiceLocator.Current.GetInstance<IEncryptionSettings>();
            if (settings.Encrypt)
            {
                // 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.
                scope.EncryptingCredentials = new X509EncryptingCredentials(settings.Certificate);
            }
            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;
            }

            // Set the ReplyTo address for the WS-Federation passive protocol (wreply). This is the address to which responses will be directed.
            // In this template, we have chosen to set this to the AppliesToAddress.
            scope.ReplyToAddress = scope.AppliesToAddress;

            return scope;
        }
        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;
        }
        /// <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);
        }
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            this.scopeModel = this.ValidateAppliesTo(request.AppliesTo);

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

            string replyTo;
            if (!string.IsNullOrEmpty(request.ReplyTo))
            {
                replyTo = request.ReplyTo;
            }
            else if (this.scopeModel.Url != null)
            {
                replyTo = this.scopeModel.Url.ToString();
            }
            else
            {
                replyTo = scope.AppliesToAddress;
            }

            scope.ReplyToAddress = replyTo;

            return scope;
        }
        public static SecurityToken GetToken(SecurityToken dobstsToken, string endpointUri, string spRealm)
        {
            // WSTrust call over SSL with credentails sent in the message.
            var binding = new IssuedTokenWSTrustBinding();
            binding.SecurityMode = SecurityMode.TransportWithMessageCredential;

            var factory = new WSTrustChannelFactory(
                binding,
                endpointUri);
            factory.TrustVersion = TrustVersion.WSTrust13;
            factory.Credentials.SupportInteractive = false;

            // Request Bearer Token so no keys or encryption required.
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(spRealm),
                KeyType = KeyTypes.Bearer
            };

            // Make the request with the DobstsToken.
            factory.ConfigureChannelFactory();
            var channel = factory.CreateChannelWithIssuedToken(dobstsToken);
            return channel.Issue(rst) as GenericXmlSecurityToken;
        }
        /// <summary>
        /// Creates the token response and invokes the logging callbacks.
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="tokenDescriptor">The token descriptor.</param>
        /// <returns>A RequestSecurityTokenResponse</returns>
        protected override RequestSecurityTokenResponse GetResponse(RequestSecurityToken request, SecurityTokenDescriptor tokenDescriptor)
        {
            var response = base.GetResponse(request, tokenDescriptor);

            // see if token is encrypted
            EncryptedSecurityToken encryptedToken = tokenDescriptor.Token as EncryptedSecurityToken;
            SecurityToken token;

            if (encryptedToken != null)
            {
                // if so, use inner token
                token = encryptedToken.Token;
            }
            else
            {
                // if not, use the token directly
                token = tokenDescriptor.Token;
            }

            var sb = new StringBuilder(128);
            FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers.WriteToken(XmlWriter.Create(new StringWriter(sb)), token);

            try
            {
                // do logging callback
                OnTrace(
                    XElement.Parse(SerializeRequest(request)),
                    XElement.Parse(SerializeResponse(response)),
                    XElement.Parse(sb.ToString()));
            }
            catch
            { }

            return response;
        }
        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class. In our case, we are only capable of issuing a token for a
        /// single RP identity represented by the EncryptingCertificateName.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming RST.</param>
        /// <returns>The scope information to be used for the token issuance.</returns>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            ValidateAppliesTo(request.AppliesTo);

            //
            // Note: The signing certificate used by default has a Distinguished name of "CN=STSTestCert",
            // and is located in the Personal certificate store of the Local Computer. Before going into production,
            // ensure that you change this certificate to a valid CA-issued certificate as appropriate.
            //
            Scope scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials);

            if (!string.IsNullOrEmpty(_encryptingCertificateName))
            {
                // 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.
                scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, _encryptingCertificateName));
            }
            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;
            }

            // Set the ReplyTo address for the WS-Federation passive protocol (wreply). This is the address to which responses will be directed.
            // In this template, we have chosen to set this to the AppliesToAddress.
            scope.ReplyToAddress = scope.AppliesToAddress;

            return scope;
        }
        public void Validate_NoRealm()
        {
            var rst = new RequestSecurityToken { RequestType = RequestTypes.Issue };
            var details = request.Analyze(rst, _alice);

            // unknown realm
            request.Validate();
        }
        public GenericXmlSecurityToken GetIssuedToken(RequestSecurityToken rst)
        {
            EndpointAddress endpointAddress = new EndpointAddress(STSAddress, EndpointIdentity.CreateDnsIdentity(DnsIdentityForServiceCertificates));
            WSTrustClient trustClient = WSTrustClientFactory.GetWSTrustClient(clientCertifikat, serviceCertifikat, endpointAddress);

            GenericXmlSecurityToken token = (GenericXmlSecurityToken) trustClient.Issue(rst);
            trustClient.Close();
            return token;
        }
        /// <summary>
        /// Constructs the Body Writer.
        /// </summary>
        /// <param name="serializer">Serializer to use for serializing the rst.</param>
        /// <param name="rst">The RequestSecurityToken object to be serialized to the outgoing Message.</param>
        public RequestBodyWriter(WSTrustRequestSerializer serializer, RequestSecurityToken rst)
            : base(false)
        {
            if (serializer == null)
                throw new ArgumentNullException("serializer");

            this._serializer = serializer;
            this._rst = rst;
        }
        /// <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;
        }
Beispiel #19
0
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == claimSet)
                return principal.Identity as IClaimsIdentity;

            ClaimsIdentity identity = new ClaimsIdentity();
            identity.Claims.AddRange(claimSet);

            return identity;
        }
        private static RequestSecurityToken CreateBearerRst(EndpointAddress appliesTo)
        {
            var rst = new RequestSecurityToken
            {
                RequestType = RequestTypes.Issue,
                AppliesTo = new EndpointAddress(appliesTo.Uri.AbsoluteUri),
                KeyType = KeyTypes.Bearer
            };

            return rst;
        }
        private string SerializeRequest(RequestSecurityToken request)
        {
            var serializer = new WSTrust13RequestSerializer();
            WSTrustSerializationContext context = new WSTrustSerializationContext();
            StringBuilder sb = new StringBuilder(128);

            using (var writer = new XmlTextWriter(new StringWriter(sb)))
            {
                serializer.WriteXml(request, writer, context);
                return sb.ToString();
            }
        }
        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;
        }
        /// <summary>
        /// Need to implement Certificate with Signing Credentials
        /// </summary>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {

            var scope = new Scope(request.AppliesTo.ToString())
                              {
                                  EncryptingCredentials = GetCredentialsForAppliesTo(request.AppliesTo),
                                  SymmetricKeyEncryptionRequired = false,
                                  // SigningCredentials = new X509SigningCredentials(GetCertificate(StoreName.My, StoreLocation.LocalMachine, "CN=IdentityProvider")),
                                  ReplyToAddress = request.AppliesTo.ToString()
                              };
            return scope;
        }
 /// <summary>
 /// Override this method to provide scope specific encrypting credentials.
 /// </summary>
 /// <param name="principal">The principal.</param>
 /// <param name="request">The request.</param>
 /// <returns></returns>
 protected override Scope GetScope( IClaimsPrincipal principal, RequestSecurityToken request )
 {
     ValidateAppliesTo( request.AppliesTo );
     Scope scope = new Scope( request.AppliesTo.Uri.AbsoluteUri );
     scope.SigningCredentials = new X509SigningCredentials(X509Helper.GetX509Certificate2(RealmSTSServiceConfig.CertStoreName,
                                                         RealmSTSServiceConfig.CertStoreLocation,
                                                         RealmSTSServiceConfig.CertDistinguishedName));
     scope.EncryptingCredentials = new X509EncryptingCredentials(X509Helper.GetX509Certificate2(RealmSTSServiceConfig.CertStoreName,
                                                         RealmSTSServiceConfig.CertStoreLocation,
                                                         RealmSTSServiceConfig.TargetDistinguishedName));
     return scope;
 }
Beispiel #25
0
            protected override Scope GetScope(
                IClaimsPrincipal principal, 
                RequestSecurityToken request)
            {
                var scope = new Scope { AppliesToAddress = request.AppliesTo.Uri.AbsoluteUri };

                scope.TokenEncryptionRequired = false;
                scope.SymmetricKeyEncryptionRequired = false;
                scope.SigningCredentials = new SymmetricSigningCredentials("Sapm9PPZZHly7a9319mksllija112suapoqc321jvso=");

                return scope;
            }
        /// <summary>
        /// Override this method to return the content of the issued token. The content is represented as a set of
        /// IClaimIdentity instances. Each instance corresponds to a single issued token.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, actual token request</param>
        /// <returns>A collection of ClaimsIdentity that contain claims so that they can be sent back inside the issued token</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            IClaimsIdentity callerIdentity = principal.Identity as IClaimsIdentity;

            List <Claim> claims = new List <Claim>();

            Claim nameValue = new Claim(ClaimTypes.Name, callerIdentity.Name);

            claims.Add(nameValue);

            //
            // Find the authentication method claim.
            //
            string authenticationMethod = GetAuthStrengthClaim(callerIdentity);

            //
            // If no authentication method claim was found, use the AuthenticationType that was set on the caller's identity.
            //
            if (String.IsNullOrEmpty(authenticationMethod))
            {
                authenticationMethod = callerIdentity.AuthenticationType;
            }

            //
            // Add an authentication method claim if found.
            //
            if (!String.IsNullOrEmpty(authenticationMethod))
            {
                //
                // Propagate the original authentication method claim. This may be used at the RP to verify authentication strength.
                //
                claims.Add(new Claim(ClaimTypes.AuthenticationMethod, authenticationMethod));
            }

            //
            // Add an authentication instant claim.
            //
            claims.Add(new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.Now.ToUniversalTime(), "yyyy-MM-ddTHH:mm:ss.fffZ")));

            //
            // We send back high assurance claims only when the authentication method is X509.
            // The authenticationMethod value dictates whether high assurance claims need to be sent or not.
            //
            if (authenticationMethod == AuthenticationMethods.X509)
            {
                //
                // Date of Birth claim
                //
                Claim dobClaim = new Claim(ClaimTypes.DateOfBirth, "Jan 01, 1980");
                claims.Add(dobClaim);

                //
                // Resident zip code claim
                //
                Claim zipClaim = new Claim(ClaimTypes.PostalCode, "98052");
                claims.Add(zipClaim);

                //
                // Phone number claim
                //
                Claim phoneClaim = new Claim(ClaimTypes.MobilePhone, "425-123-0000");
                claims.Add(phoneClaim);
            }

            ClaimsIdentityCollection collection     = new ClaimsIdentityCollection();
            ClaimsIdentity           outputIdentity = new ClaimsIdentity(claims);

            return(outputIdentity);
        }
        /// <summary>
        /// Returns the claims to be issued in the token.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming request security token, can be used to obtain addtional information.</param>
        /// <param name="scope">The scope information corresponding to this request.</param>
        /// <returns>The outgoing claims identity to be included in the issued token.</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            // Create the claims identity.
            var claimsIdentity = new ClaimsIdentity();

            // Get the security id for the user.
            var userProvider = this._container.Resolve <IUserProvider>();
            var securityId   = userProvider.ReadSecurityIdByLogin(principal.Identity.Name);

            // Load the claims.
            var claimsProvider = this._container.Resolve <IClaimsProvider>();

            claimsIdentity.Claims.AddRange(claimsProvider.GetClaims(securityId));

            // Return the claims to the caller.
            return(claimsIdentity);
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var output = new ClaimsIdentity();

            if (null == principal)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            SingleSignOnManager.RegisterRelyingParty(scope.ReplyToAddress);

            var input  = (ClaimsIdentity)principal.Identity;
            var issuer = input.Claims.First().Issuer.ToUpperInvariant();

            switch (issuer)
            {
            case "LITWARE":
                CopyClaims(input, new[] { WSIdentityConstants.ClaimTypes.Name }, output);

                TransformClaims(input, AllOrganizations.ClaimTypes.Group, Litware.Groups.Sales, ClaimTypes.Role, Adatum.Roles.OrderTracker, output);

                output.Claims.Add(new Claim(Adatum.ClaimTypes.Organization, Litware.OrganizationName));

                SingleSignOnManager.RegisterIssuer(LitwareIssuer);

                break;

            case "ADATUM":
                output = input;
                SingleSignOnManager.RegisterIssuer(AdatumIssuer);

                break;

            default:
                throw new InvalidOperationException("Issuer not trusted.");
            }

            return(output);
        }
Beispiel #29
0
    /// <summary>
    /// This method returns the claims to be issued in the token.
    /// </summary>
    /// <param name="principal">The caller's principal.</param>
    /// <param name="request">The incoming RST, can be used to obtain addtional information.</param>
    /// <param name="scope">The scope information corresponding to this request.</param>
    /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception>
    /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
    protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
    {
        if (null == principal)
        {
            throw new ArgumentNullException("principal");
        }

        ClaimsIdentity outputIdentity = (ClaimsIdentity)principal.Identity;

        // Issue custom claims.
        // TODO: Change the claims below to issue custom claims required by your application.
        // Update the application's configuration file too to reflect new claims requirement.

        // Gunnar: my custom claim
        outputIdentity.Claims.Add(new Claim(ClaimTypes.Email, "*****@*****.**"));
        outputIdentity.Claims.Add(new Claim(ClaimTypes.Gender, "Male"));
        outputIdentity.Claims.Add(new Claim(ClaimTypes.HomePhone, "12345"));
        outputIdentity.Claims.Add(new Claim(ClaimTypes.Webpage, "carter.was.here"));
        return(outputIdentity);
    }
Beispiel #30
0
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var id = new ClaimsIdentity(principal.Claims, "EmbeddedSTS");

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

            var input = principal.Identity as ClaimsIdentity;

            var tenant = this.tenantStore.GetTenant(input.Claims.First().Issuer);

            if (tenant == null)
            {
                throw new InvalidOperationException("Issuer not trusted.");
            }

            var output = new ClaimsIdentity();

            CopyClaims(input, new[] { WSIdentityConstants.ClaimTypes.Name }, output);
            TransformClaims(input, tenant.ClaimType, tenant.ClaimValue, ClaimTypes.Role, Tailspin.Roles.SurveyAdministrator, output);
            output.Claims.Add(new Claim(Tailspin.ClaimTypes.Tenant, tenant.Name));

            return(output);
        }
Beispiel #32
0
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var output = new ClaimsIdentity();

            if (null == principal)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            var input = (IClaimsIdentity)principal.Identity;

            switch (principal.Identity.Name.ToUpperInvariant())
            {
            // In a production environment, all the information that will be added
            // as claims should be read from the authenticated Windows Principal.
            // The following lines are hardcoded because windows integrated
            // authentication is disabled.
            case "LITWARE\\RICK":
                output.Claims.AddRange(new List <Claim>
                {
                    new Claim(ClaimTypes.Name, "rick"),
                    new Claim(ClaimTypes.GivenName, "Rick"),
                    new Claim(ClaimTypes.Surname, "Rico"),
                    new Claim(ClaimTypes.StreetAddress, "51 Wide Rd."),
                    new Claim(ClaimTypes.StateOrProvince, "WA"),
                    new Claim(ClaimTypes.Country, "United States"),
                    new Claim(Litware.ClaimTypes.CostCenter, "Sales" /*Litware.CostCenters.Sales*/),
                    new Claim(AllOrganizations.ClaimTypes.Group, Litware.Groups.Sales)
                });
                break;

            default:
                throw new UnauthorizedAccessException(string.Format(CultureInfo.CurrentUICulture, "User '{0}' is not authorized.", input.Name));
            }

            return(output);
        }
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity instances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();
            ClaimsIdentity incomingIdentity = principal.Identities[0];

            // Do the claim transform based on who the IP STS is and the claims issued by those
            // Transform the incoming claims to appropriate outgoing claims
            // Add the claims issued by IP STSes for illustrative purposes, ONLY the expected claims
            // are being added to the list and others are disregarded

            bool type1, type2;

            type1 = type2 = false;

            foreach (Claim c in incomingIdentity.Claims)
            {
                if (c.Type.Equals(IPSTS1_IDENTIFIER_CLAIM))
                {
                    type1 = true;
                    break;
                }
                if (c.Type.Equals(IPSTS2_IDENTIFIER_CLAIM))
                {
                    type2 = true;
                    break;
                }
            }

            if (type1)
            {
                TransformIPSTS1Claims(incomingIdentity, outgoingIdentity);
            }

            if (type2)
            {
                TransformIPSTS2Claims(incomingIdentity, outgoingIdentity);
            }

            return(outgoingIdentity);
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var output = new ClaimsIdentity();

            if (null == principal)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            SingleSignOnManager.RegisterRelyingParty(scope.ReplyToAddress);

            var input  = (ClaimsIdentity)principal.Identity;
            var issuer = input.Claims.First().Issuer;

            switch (issuer.ToUpperInvariant())
            {
            case "ADATUM":
                var adatumClaimTypesToCopy = new[]
                {
                    WSIdentityConstants.ClaimTypes.Name,
                    ClaimTypes.GivenName,
                    ClaimTypes.Surname,
                    ClaimTypes.StreetAddress,
                    ClaimTypes.StateOrProvince,
                    ClaimTypes.Country
                };
                CopyClaims(input, adatumClaimTypesToCopy, output);

                TransformClaims(input, AllOrganizations.ClaimTypes.Group, Adatum.Groups.CustomerService, ClaimTypes.Role, Fabrikam.Roles.ShipmentCreator, output);
                TransformClaims(input, AllOrganizations.ClaimTypes.Group, Adatum.Groups.OrderFulfillments, ClaimTypes.Role, Fabrikam.Roles.ShipmentCreator, output);
                TransformClaims(input, AllOrganizations.ClaimTypes.Group, Adatum.Groups.OrderFulfillments, ClaimTypes.Role, Fabrikam.Roles.ShipmentManager, output);
                TransformClaims(input, AllOrganizations.ClaimTypes.Group, Adatum.Groups.ItAdmins, ClaimTypes.Role, Fabrikam.Roles.Administrator, output);
                TransformClaims(input, Adatum.ClaimTypes.CostCenter, "*", Fabrikam.ClaimTypes.CostCenter, "*", output);

                output.Claims.Add(new Claim(Fabrikam.ClaimTypes.Organization, Adatum.OrganizationName));

                SingleSignOnManager.RegisterIssuer("https://localhost/Adatum.SimulatedIssuer.3/");

                break;

            case "LITWARE":
                var litwareClaimTypesToCopy = new[]
                {
                    WSIdentityConstants.ClaimTypes.Name,
                    ClaimTypes.GivenName,
                    ClaimTypes.Surname,
                    ClaimTypes.StreetAddress,
                    ClaimTypes.StateOrProvince,
                    ClaimTypes.Country
                };
                CopyClaims(input, litwareClaimTypesToCopy, output);

                TransformClaims(input, AllOrganizations.ClaimTypes.Group, Litware.Groups.Sales, ClaimTypes.Role, Fabrikam.Roles.ShipmentCreator, output);
                TransformClaims(input, Litware.ClaimTypes.CostCenter, "*", Fabrikam.ClaimTypes.CostCenter, "*", output);

                output.Claims.Add(new Claim(Fabrikam.ClaimTypes.Organization, Litware.OrganizationName));

                SingleSignOnManager.RegisterIssuer("https://localhost/Litware.SimulatedIssuer.3/");

                break;

            case "FABRIKAM-SIMPLE":
                var fabrikamSimpleClaimTypesToCopy = new[]
                {
                    WSIdentityConstants.ClaimTypes.Name,
                    ClaimTypes.GivenName,
                    ClaimTypes.Surname,
                    ClaimTypes.StreetAddress,
                    ClaimTypes.StateOrProvince,
                    ClaimTypes.Country
                };
                CopyClaims(input, fabrikamSimpleClaimTypesToCopy, output);

                switch (input.Name.ToUpperInvariant())
                {
                // In a production environment, all the claims for the users are taken from claim
                // mappings where the user name is the input claim and all the claims added here
                // are output claims.
                case "*****@*****.**":
                    output.Claims.AddRange(new List <Claim>
                    {
                        new Claim(ClaimTypes.Role, Fabrikam.Roles.Administrator),
                        new Claim(ClaimTypes.Role, Fabrikam.Roles.ShipmentManager),
                        new Claim(ClaimTypes.Role, Fabrikam.Roles.ShipmentCreator),
                        new Claim(Fabrikam.ClaimTypes.CostCenter, Contoso.CostCenters.SingleCostCenter),
                        new Claim(Fabrikam.ClaimTypes.Organization, Contoso.OrganizationName)
                    });

                    break;
                }

                SingleSignOnManager.RegisterIssuer("https://localhost/Fabrikam.SimulatedIssuer.3/");
                break;

            default:
                throw new InvalidOperationException("Issuer not trusted.");
            }

            return(output);
        }
    /// <summary>
    /// This method returns the claims to be issued in the token.
    /// </summary>
    /// <param name="scope">The scope information corresponding to this request.</param>
    /// <param name="principal">The caller's principal</param>
    /// <param name="request">The incoming RST, we don't use this in our implementation</param>
    /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
    protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
    {
        ClaimsIdentity outputIdentity = new ClaimsIdentity();

        if (null == principal)
        {
            throw new InvalidRequestException("The caller's principal is null.");
        }

        // Get User Name from SID and issue that as a Name Claim.
        string ntAccountValue = GetNTAccountName(principal);

        ntAccountValue = ntAccountValue.Substring(ntAccountValue.IndexOf('\\') + 1);
        outputIdentity.Claims.Add(new Claim(Microsoft.IdentityModel.Claims.ClaimTypes.Name, ntAccountValue));

        // Issue Custom Claims.
        ntAccountValue = ntAccountValue + "@contoso.com";
        outputIdentity.Claims.Add(new Claim("http://WindowsIdentityFoundationSamples/myID", ntAccountValue, ClaimValueTypes.String));
        outputIdentity.Claims.Add(new Claim("http://WindowsIdentityFoundationSamples/2008/05/AgeClaim", "25", ClaimValueTypes.Integer));

        return(outputIdentity);
    }
Beispiel #36
0
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException(nameof(principal));
            }

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

            var inputClaims = ((ClaimsIdentity)principal.Identity).Claims.ToArray();

            if (scopeModel.UseClaimsPolicyEngine)
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.DebugFormat("Mapping of claims. All values before are: {0}", String.Join(",", inputClaims.Select(i => i.ToString())));
                }
                IClaimsPolicyEvaluator evaluator = new ClaimsPolicyEvaluator(PolicyStoreFactory.Instance);
                outputClaims = evaluator.Evaluate(new Uri(scope.AppliesToAddress), inputClaims);
                if (Logger.IsDebugEnabled)
                {
                    Logger.DebugFormat("Mapping of claims. All values after are: {0}", String.Join(",", outputClaims.Select(i => i.ToString())));
                }
            }
            else
            {
                if (Logger.IsDebugEnabled)
                {
                    Logger.DebugFormat("No mapping of claims. All values are: {0}", String.Join(",", inputClaims.Select(i => i.ToString())));
                }
                outputClaims = inputClaims;
            }

            outputIdentity.AddClaims(outputClaims);
            var nameIdentifierClaim = outputIdentity.Claims.SingleOrDefault(c => c.Type == ClaimTypes.NameIdentifier);

            if (outputIdentity.Name == null && nameIdentifierClaim != null)
            {
                outputIdentity.AddClaim(new Claim(ClaimTypes.Name, nameIdentifierClaim.Value));
            }

            var isPersistentClaim = inputClaims.SingleOrDefault(c => c.Type == ClaimTypes.IsPersistent);

            if (isPersistentClaim != null)
            {
                outputIdentity.AddClaim(new Claim(ClaimTypes.IsPersistent, isPersistentClaim.Value));
            }

            return(outputIdentity);
        }
Beispiel #37
0
 /// <summary>
 /// Creates new Security Token Descriptor.
 /// </summary>
 /// <param name="request">The incoming token request.</param>
 /// <param name="scope">The Scope object returned from GetScope.</param>
 /// <returns>New security token descriptor.</returns>
 protected override SecurityTokenDescriptor CreateSecurityTokenDescriptor(RequestSecurityToken request, Scope scope)
 {
     return(base.CreateSecurityTokenDescriptor(request, scope));
 }
Beispiel #38
0
        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);
        }
Beispiel #39
0
            protected override BodyWriter GetFirstOutgoingMessageBody(IssuedSecurityTokenProvider.FederatedTokenProviderState negotiationState, out MessageProperties messageProperties)
            {
                messageProperties = null;
                RequestSecurityToken token = new RequestSecurityToken(base.StandardsManager);

                if (this.addTargetServiceAppliesTo)
                {
                    if (this.MessageVersion.Addressing != AddressingVersion.WSAddressing10)
                    {
                        if (this.MessageVersion.Addressing != AddressingVersion.WSAddressingAugust2004)
                        {
                            throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ProtocolException(System.ServiceModel.SR.GetString("AddressingVersionNotSupported", new object[] { this.MessageVersion.Addressing })));
                        }
                        token.SetAppliesTo <EndpointAddressAugust2004>(EndpointAddressAugust2004.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddressAugust2004), 0x10000));
                    }
                    else
                    {
                        token.SetAppliesTo <EndpointAddress10>(EndpointAddress10.FromEndpointAddress(negotiationState.TargetAddress), DataContractSerializerDefaults.CreateSerializer(typeof(EndpointAddress10), 0x10000));
                    }
                }
                token.Context = negotiationState.Context;
                if (!this.isKeySizePresentInRstProperties)
                {
                    token.KeySize = this.keySize;
                }
                Collection <XmlElement> collection = new Collection <XmlElement>();

                if (this.requestProperties != null)
                {
                    for (int i = 0; i < this.requestProperties.Count; i++)
                    {
                        collection.Add(this.requestProperties[i]);
                    }
                }
                if (!this.isKeyTypePresentInRstProperties)
                {
                    XmlElement item = base.StandardsManager.TrustDriver.CreateKeyTypeElement(this.keyType);
                    collection.Insert(0, item);
                }
                if (this.keyType == SecurityKeyType.SymmetricKey)
                {
                    byte[] requestorEntropy = negotiationState.GetRequestorEntropy();
                    token.SetRequestorEntropy(requestorEntropy);
                }
                else if (this.keyType == SecurityKeyType.AsymmetricKey)
                {
                    RsaKeyIdentifierClause clause        = new RsaKeyIdentifierClause(negotiationState.Rsa);
                    SecurityKeyIdentifier  keyIdentifier = new SecurityKeyIdentifier(new SecurityKeyIdentifierClause[] { clause });
                    collection.Add(base.StandardsManager.TrustDriver.CreateUseKeyElement(keyIdentifier, base.StandardsManager));
                    RsaSecurityTokenParameters tokenParameters = new RsaSecurityTokenParameters {
                        InclusionMode      = SecurityTokenInclusionMode.Never,
                        RequireDerivedKeys = false
                    };
                    SupportingTokenSpecification specification = new SupportingTokenSpecification(negotiationState.RsaSecurityToken, System.ServiceModel.Security.EmptyReadOnlyCollection <IAuthorizationPolicy> .Instance, SecurityTokenAttachmentMode.Endorsing, tokenParameters);
                    messageProperties = new MessageProperties();
                    SecurityMessageProperty property = new SecurityMessageProperty {
                        OutgoingSupportingTokens = { specification }
                    };
                    messageProperties.Security = property;
                }
                if ((this.keyType == SecurityKeyType.SymmetricKey) && (this.KeyEntropyMode == SecurityKeyEntropyMode.CombinedEntropy))
                {
                    collection.Add(base.StandardsManager.TrustDriver.CreateComputedKeyAlgorithmElement(base.StandardsManager.TrustDriver.ComputedKeyAlgorithm));
                }
                token.RequestProperties = collection;
                token.MakeReadOnly();
                return(token);
            }
Beispiel #40
0
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity intances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation only
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();

            foreach (Claim c in principal.Claims)
            {
                outgoingIdentity.AddClaim(new Claim(c.Type, c.Value, c.ValueType, "IPSTS2", "IPSTS2"));
            }

            outgoingIdentity.AddClaim(new Claim(IDENTITY_PROVIDER_CLAIM, "ipsts2.com"));

            return(outgoingIdentity);
        }
Beispiel #41
0
        /// <summary>
        /// This method returns the claims to be issued in the token.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming RST, can be used to obtain addtional information.</param>
        /// <param name="scope">The scope information corresponding to this request.</param>
        /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception>
        /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            ClaimsIdentity outputIdentity = new ClaimsIdentity();

            // Issue custom claims.
            // TODO: Change the claims below to issue custom claims required by your application.
            // Update the application's configuration file too to reflect new claims requirement.

            outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name));
            outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, "Manager"));

            return(outputIdentity);
        }
Beispiel #42
0
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var outputIdentity = new ClaimsIdentity();

            if (null == principal)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            switch (principal.Identity.Name.ToUpperInvariant())
            {
            // In a production environment, all the information that will be added
            // as claims should be read from the authenticated Windows Principal.
            // The following lines are hardcoded because windows integrated
            // authentication is disabled.
            case "ADATUM\\JOHNDOE":
                outputIdentity.Claims.AddRange(new List <Claim>
                {
                    new Claim(System.IdentityModel.Claims.ClaimTypes.Name, "ADATUM\\johndoe"),
                    new Claim(AllOrganizations.ClaimTypes.Group, Adatum.Groups.DomainUsers),
                    new Claim(AllOrganizations.ClaimTypes.Group, Adatum.Groups.MarketingManagers)
                });
                break;
            }

            return(outputIdentity);
        }
Beispiel #43
0
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity instances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();

            foreach (Claim c in principal.Claims)
            {
                if (String.Compare(c.Type, IDENTITY_PROVIDER_CLAIM) == 0)
                {
                    outgoingIdentity.AddClaim(new Claim(c.Type, "fpsts." + c.Value));
                }
                else
                {
                    outgoingIdentity.AddClaim(new Claim(c.Type, c.Value, c.ValueType, "FPSTS", c.OriginalIssuer));
                }
            }

            Claim  nameClaim    = principal.FindFirst(ClaimTypes.Name);
            string emailAddress = nameClaim.Value + "@fpsts.com";
            Claim  emailClaim   = new Claim(ClaimTypes.Email, emailAddress, ClaimValueTypes.String, "FPSTS");

            outgoingIdentity.AddClaim(emailClaim);

            return(outgoingIdentity);
        }
Beispiel #44
0
        /// <summary>
        /// This method returns the claims to be included in the issued token.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST</param>
        /// <returns>The claims to be included in the issued token.</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            IClaimsIdentity callerIdentity = (IClaimsIdentity)principal.Identity;

            Console.WriteLine("\nRequest from: " + callerIdentity.Name + "\n");

            IClaimsIdentity outputIdentity = new ClaimsIdentity();

            // Create a name claim from the incoming identity.
            Claim nameClaim = new Claim(ClaimTypes.Name, callerIdentity.Name);

            // Create an 'Age' claim with a value of 25. In a real scenario, this may likely be looked up from a database.
            Claim ageClaim = new Claim("http://WindowsIdentityFoundationSamples/2008/05/AgeClaim", "25", ClaimValueTypes.Integer);

            outputIdentity.Claims.Add(nameClaim);
            Console.WriteLine("ClaimType  : " + nameClaim.ClaimType);
            Console.WriteLine("ClaimValue : " + nameClaim.Value);
            Console.WriteLine();

            Console.WriteLine("ClaimType  : " + ageClaim.ClaimType);
            Console.WriteLine("ClaimValue : " + ageClaim.Value);
            Console.WriteLine("===========================");

            outputIdentity.Claims.Add(ageClaim);

            return(outputIdentity);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            WriteVerbose("Process record");

            string connectionPassword;
            string connectionUsername;

            switch (this.ParameterSetName)
            {
            case "Securestring":
            {
                connectionPassword = password;
                connectionUsername = securePassword.ToUnsecureString();
                break;
            }

            case "Credentials":
            {
                connectionPassword = credentials.Password.ToUnsecureString();
                connectionUsername = credentials.UserName;
                break;
            }

            default:
            {
                connectionPassword = password;
                connectionUsername = username;
                break;
            }
            }

            string serverUrl = string.Format("{0}://{1}{2}", requestProtocol, adfsServer, adfsRequestUrl);

            try
            {
                var factory = new WSTrustChannelFactory(new UserNameWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(serverUrl))
                {
                    TrustVersion = TrustVersion.WSTrust13
                };
                factory.Credentials.UserName.UserName = connectionUsername;
                factory.Credentials.UserName.Password = connectionPassword;
                var rst = new RequestSecurityToken
                {
                    RequestType = WSTrust13Constants.RequestTypes.Issue,
                    AppliesTo   = new EndpointAddress(adfsAudience),
                    KeyType     = WSTrust13Constants.KeyTypes.Bearer
                };

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

                if (outputFormat.ToLower() == "xmltoken")
                {
                    WriteObject(genericToken.TokenXml.OuterXml);
                }
                else if (outputFormat.ToLower() == "samltoken")
                {
                    var tokenHandler = System.IdentityModel.Tokens.SecurityTokenHandlerCollection.CreateDefaultSecurityTokenHandlerCollection();
                    var tokenString  = genericToken.TokenXml.OuterXml;
                    WriteObject(tokenHandler.ReadToken(new XmlTextReader(new StringReader(tokenString))));
                }
                else
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.LoadXml(genericToken.TokenXml.OuterXml);
                    WriteObject(xmlDocument);
                }
            }
            catch (Exception ex)
            {
                WriteError(new ErrorRecord(new SecurityException(ex.Message), "100", ErrorCategory.AuthenticationError, null));
            }
        }
Beispiel #46
0
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var outputIdentity = new ClaimsIdentity();

            if (null == principal)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            switch (principal.Identity.Name)
            {
            // In a production environment, all the information that will be added
            // as claims should be read from the authenticated Windows Principal.
            // The following lines are hardcoded because windows integrated
            // authentication is disabled.
            case Tailspin.Users.FullName:
                outputIdentity.Claims.AddRange(new List <Claim>
                {
                    new Claim(ClaimTypes.Name, Tailspin.Users.FullName),
                    new Claim(ClaimTypes.GivenName, "Robert"),
                    new Claim(ClaimTypes.Surname, "Roe"),
                    new Claim(ClaimTypes.Role, Tailspin.Roles.TenantAdministrator)
                });
                break;

            default:
                if (!principal.Identity.Name.Equals(this.CustomUserName, System.StringComparison.InvariantCultureIgnoreCase))
                {
                    throw new InvalidOperationException(string.Format("Cannot get claims for {0} - not authorized", principal.Identity.Name));
                }

                var tenantName = principal.Identity.Name.Split('\\')[0];

                outputIdentity.Claims.AddRange(new List <Claim>
                {
                    new Claim(ClaimTypes.Name, principal.Identity.Name),
                    new Claim(ClaimTypes.GivenName, tenantName + " Jr."),
                    new Claim(ClaimTypes.Surname, "John"),
                    new Claim(ClaimTypes.Role, Tailspin.Roles.SurveyAdministrator),
                    new Claim(Tailspin.ClaimTypes.Tenant, tenantName)
                });

                break;
            }

            return(outputIdentity);
        }
Beispiel #47
0
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (principal == null)
            {
                throw new ArgumentNullException("principal");
            }

            ClaimsIdentity userIdentity = principal.Identities.FirstOrDefault();

            if (userIdentity == null)
            {
                throw new Exception("User Identity not found.");
            }

            var claimTypes = new List <string> {
                ClaimTypes.AuthenticationInstant, ClaimTypes.AuthenticationMethod
            };

            var inheritedClaims =
                userIdentity.Claims.Where(i => !claimTypes.Contains(i.Type))
                .Select(c => new Claim(c.Type, c.Value));

            var relyingParty = (scope as RequestScope).RelyingParty;

            var outputIdentity = new ClaimsIdentity(relyingParty.IssuerName);

            // We also have the ClaimTypes.AuthenticationMethod that shows which was the original authenticator
            outputIdentity.AddClaim(new Claim(ClaimTypes.AuthenticationInstant,
                                              DateTime.UtcNow.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'"),
                                              ClaimValueTypes.DateTime, relyingParty.IssuerName));
            outputIdentity.AddClaim(new Claim(ClaimTypes.AuthenticationMethod,
                                              relyingParty.AuthenticationUrl,
                                              ClaimValueTypes.String, relyingParty.IssuerName));

            outputIdentity.AddClaims(inheritedClaims);

            return(outputIdentity);
        }
        /// <summary>
        /// <see cref="ITokenIssuingService.RequestToken"/>
        /// </summary>
        public SecurityToken RequestToken(TokenIssuingRequestConfiguration config)
        {
            // Check input arguments
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }
            if (string.IsNullOrEmpty(config.WspEndpointId))
            {
                throw new ArgumentException("WspEndpointId");
            }
            if (string.IsNullOrEmpty(config.StsEndpointAddress))
            {
                throw new ArgumentException("StsEndpointAddress");
            }
            // X509FindType cannot be tested below because default value is FindByThumbprint
            if (config.ClientCertificate == null)
            {
                throw new ArgumentException("ClientCertificate");
            }
            if (config.StsCertificate == null)
            {
                throw new ArgumentException("StsCertificate");
            }

            Logger.Instance.Trace($@"RequestToken called with the client certificate: {config.ClientCertificate.SubjectName.Name} ({config.ClientCertificate.Thumbprint})");
            Logger.Instance.Trace($@"RequestToken called with the STS certificate: {config.StsCertificate.SubjectName.Name} ({config.StsCertificate.Thumbprint})");

            try
            {
                // Create custom binding
                var stsBinding = new CustomBinding();
                if (config.SendTimeout.HasValue)
                {
                    Logger.Instance.Warning($"RequestToken send timeout set to {config.SendTimeout.Value}");
                    stsBinding.SendTimeout = config.SendTimeout.Value;
                }
                stsBinding.Elements.Add(new SignatureCaseBindingElement(config.StsCertificate));
                stsBinding.Elements.Add(new TextMessageEncodingBindingElement(MessageVersion.Soap11WSAddressing10,
                                                                              Encoding.UTF8));
                // ManualAddressing must be true in order to make sure that wsa header elements are not altered in the HttpsTransportChannel which happens after xml elements have been digitally signed.
                stsBinding.Elements.Add(new HttpsTransportBindingElement()
                {
                    ManualAddressing = true
                });

                // Setup channel factory and apply client credentials
                var factory = new WSTrustChannelFactory(stsBinding, new EndpointAddress(config.StsEndpointAddress));
                factory.TrustVersion = TrustVersion.WSTrust13;
                factory.Credentials.ClientCertificate.Certificate = config.ClientCertificate;

                // Create token request
                // UseKey and KeyType are only set in order for WCF to know which proof token to use when signing the request sent from WSC to WSP. Hence, UseKey and KeyType are actually sent to the NemLogin-STS but not used for anything by the STS.
                var requestSecurityToken = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    AppliesTo   = new EndpointReference(config.WspEndpointId),
                    // TokenType is optional according to [NEMLOGIN-STSRULES]. If specified it must contain the value http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0 which is the only type NemLogin STS supports.
                    // We specify it in case that NemLogin STS supports other token types in the future.
                    // Currently if TokenType is not specified ... then TokenType is also not specified in the RequestSecurityTokenResponse (RSTR). According to spec it should always be specified in the RSTR. Specifying TokenType in the RST triggers the TokenType to be specified in the RSTR.
                    TokenType = "http://docs.oasis-open.org/wss/oasis-wss-saml-token-profile-1.1#SAMLV2.0",
                    UseKey    = new UseKey(new X509SecurityToken(config.ClientCertificate)), // The UseKey must be set in order for WCF to know which certificate must be used for signing the request from WSC to WSP. Thus, the usekey is actually the same as the proof key in the holder-of-key scenario.
                    KeyType   = KeyTypes.Asymmetric                                          // The KeyType must be set to Asymmetric in order for WCF to know that it must use the UseKey as proof token.
                };
                // Lifetime is only specified if it has been configured. Should result in a default life time (8 hours) on issued token if not specified. If specified, STS is not obligated to honor this range and may return a token with a shorter life time in RSTR.
                if (config.TokenLifeTimeInMinutes.HasValue)
                {
                    requestSecurityToken.Lifetime = new Lifetime(null,
                                                                 DateTime.UtcNow.AddMinutes(config.TokenLifeTimeInMinutes.Value));
                }

                // Request token and return
                var wsTrustChannelContract = factory.CreateChannel();
                var securityToken          = wsTrustChannelContract.Issue(requestSecurityToken);

                return(securityToken);
            }
            // Log all errors and rethrow
            catch (Exception e)
            {
                Logger.Instance.Error("Error occured while requesting token. See exception details!", e);
                throw;
            }
        }
Beispiel #49
0
    /// <summary>
    /// This method returns the claims to be issued in the token.
    /// </summary>
    /// <param name="scope">The scope information corresponding to this request.</param>
    /// <param name="principal">The caller's principal</param>
    /// <param name="request">The incoming RST.</param>
    /// <returns>The IClaimsIdentity to be included in the issued token.</returns>
    protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
    {
        ClaimsIdentity outputIdentity = new ClaimsIdentity();

        // Get the Name Claim.
        string name = GetName(principal);

        outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, name));

        // Issue Custom Claims.
        // In this sample, we simply map Bob to Editor and everyone else (Joe) to Reviewer
        // In production, there would probably be a database to make these decisions.
        if (StringComparer.OrdinalIgnoreCase.Equals(name, "Bob"))
        {
            outputIdentity.Claims.Add(new Claim(StsClaimTypes.RoleClaimType, "Editor", ClaimValueTypes.String));
        }
        else
        {
            outputIdentity.Claims.Add(new Claim(StsClaimTypes.RoleClaimType, "Reviewer", ClaimValueTypes.String));
        }

        outputIdentity.Claims.Add(new Claim(StsClaimTypes.BookNameClaimType, "FrameworkSamples.txt", ClaimValueTypes.String));

        return(outputIdentity);
    }
Beispiel #50
0
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// ClaimIdentity intances, each instance corresponds to a single issued token.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method.</param>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming RST.</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            ClaimsIdentity callerIdentity = principal.Identities.First();
            ClaimsIdentity outputIdentity = new ClaimsIdentity(ClaimIdentityName);

            CopyClaims(callerIdentity, outputIdentity);

            return(outputIdentity);
        }
Beispiel #51
0
        /// <summary>
        /// Gets the output claims identity.
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="request">The request.</param>
        /// <param name="scope">The scope.</param>
        /// <returns>Returns output claims identity.</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            const string ContainerName        = "defaultContainer";
            UnityConfigurationSection section = ConfigurationManager.GetSection("unity") as UnityConfigurationSection;

            if (!section.Containers.Any(container => container.Name == ContainerName))
            {
                throw new ArgumentException("No defaultContainer in unity configuration section.");
            }

            UnityContainer unityContainer = new UnityContainer();

            section.Configure(unityContainer, ContainerName);

            IClaimProvider claimProvider = unityContainer.Resolve <IClaimProvider>();

            ClaimsIdentity outputIdentity = new ClaimsIdentity(principal.Identity);

            string[] canHandleTypes = claimProvider.CanHandle(new[] { System.IdentityModel.Claims.ClaimTypes.Name }, outputIdentity);
            outputIdentity = claimProvider.UpdateIdentity(canHandleTypes, outputIdentity) as ClaimsIdentity;
            Logger.Write("Created claims identity: " + outputIdentity.Name);

            return(outputIdentity);
        }
Beispiel #52
0
        static void Main(string[] args)
        {
            {
                // read token
                var jwtHandler = new JwtSecurityTokenHandler();
                //string jwtEncodedString = "eyJ0eXAiOiJKV1QiLCJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjcnNhLXNoYTEiLCJ4NXQiOiI0dnk1YV9oM0NVcFJEd3QzbUFCSUdaWlgxMWcifQ.eyJpc3MiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJhdWQiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJuYmYiOjE0NDEzNzg0MTQsImV4cCI6MTQ0MTk4MzIxNCwidW5pcXVlX25hbWUiOiJXZW5qdW4iLCJnaXZlbl9uYW1lIjoiV2VuanVuIiwiZ3JvdXAiOlsiUkFZTUFSS0xBQlxcRG9tYWluIEFkbWlucyIsIlJBWU1BUktMQUJcXERvbWFpbiBVc2VycyJdLCJhdXRobWV0aG9kIjoiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2F1dGhlbnRpY2F0aW9ubWV0aG9kL3Bhc3N3b3JkIiwiYXV0aF90aW1lIjoiMjAxNS0wOS0wNFQxNDo1MzoyNi4xNDdaIn0.NTEU48x2-faKVISrv50ucfwJSma4lDuAFGOe5e6QScOxT7rNUilyn3SxIsUVtRKVDLY1Inof8FhARiBUXcoED153z9EyQVoqX4xgWwTccKzcRGdwELn77iK1bGl_Mb51mj4QWbDARSVXS3m4fMrS4V70XuDXhWM5bv7xpRUxW5ibkMu6Ih60OVUvStLb7XM1RZ3mvtqjFhOTO1Omsng5gU2OViLsuPBoNCi-nMyi47qKz5R3X502uFvCQirLud3Igjc0OqMhRkZzz-NNAvo4i_78fTmvrltyLMxHgTuiM7w9vGsGQ-u6SA-PR9LT3lkIlhtuzkBZLi1wWS55Gmc-1g";
                string        jwtEncodedString = "eyJ0eXAiOiJKV1QiLCJhbGciOiJodHRwOi8vd3d3LnczLm9yZy8yMDAwLzA5L3htbGRzaWcjcnNhLXNoYTEiLCJ4NXQiOiI0dnk1YV9oM0NVcFJEd3QzbUFCSUdaWlgxMWcifQ.eyJpc3MiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJhdWQiOiJodHRwczovL3YtbGFiL2NyYXNlcnZpY2UiLCJuYmYiOjE0NDEzNzg0MTQsImV4cCI6MTQ0MTk4MzIxNCwidW5pcXVlX25hbWUiOiJXZW5qdW4iLCJnaXZlbl9uYW1lIjoiV2VuanVuIiwiZ3JvdXAiOlsiUkFZTUFSS0xBQlxcRG9tYWluIEFkbWlucyIsIlJBWU1BUktMQUJcXERvbWFpbiBVc2VycyJdLCJhdXRobWV0aG9kIjoiaHR0cDovL3NjaGVtYXMubWljcm9zb2Z0LmNvbS93cy8yMDA4LzA2L2lkZW50aXR5L2F1dGhlbnRpY2F0aW9ubWV0aG9kL3Bhc3N3b3JkIiwiYXV0aF90aW1lIjoiMjAxNS0wOS0wNFQxNDo1MzoyNi4xNDdaIn0.NTEU48x2-faKVISrv50ucfwJSma4lDuAFGOe5e6QScOxT7rNUilyn3SxIsUVtRKVDLY1Inof8FhARiBUXcoED153z9EyQVoqX4xgWwTccKzcRGdwELn77iK1bGl_Mb51mj4QWbDARSVXS3m4fMrS4V70XuDXhWM5bv7xpRUxW5ibkMu6Ih60OVUvStLb7XM1RZ3mvtqjFhOTO1Omsng5gU2OViLsuPBoNCi-nMyi47qKz5R3X502uFvCQirLud3Igjc0OqMhRkZzz-NNAvo4i_78fTmvrltyLMxHgTuiM7w9vGsGQ-u6SA-PR9LT3lkIlhtuzkBZLi1wWS55Gmc-1g";
                SecurityToken sToken           = jwtHandler.ReadToken(jwtEncodedString);

                X509Store store = new X509Store(StoreName.TrustedPeople, StoreLocation.LocalMachine);
                store.Open(OpenFlags.ReadOnly);

                var cs = store.Certificates.Find(X509FindType.FindByThumbprint, "E2FCB96BF877094A510F0B77980048199657D758", false);
                X509Certificate2 certificate = store.Certificates.Find(X509FindType.FindByThumbprint, "E2FCB96BF877094A510F0B77980048199657D758", false)[0];

                TokenValidationParameters validationParameters = new TokenValidationParameters()
                {
                    AllowedAudience = "https://v-lab/craservice",
                    ValidIssuer     = "https://v-lab/craservice",

                    // Fetch the signing token from the FederationMetadata document of the tenant.
                    SigningToken = new X509SecurityToken(certificate)
                };

                var claims1 = jwtHandler.ValidateToken(jwtEncodedString, validationParameters);

                {
                    var configuration = new SecurityTokenHandlerConfiguration();
                    configuration.AudienceRestriction.AudienceMode = AudienceUriMode.Never;
                    configuration.CertificateValidationMode        = X509CertificateValidationMode.None;
                    configuration.RevocationMode       = X509RevocationMode.NoCheck;
                    configuration.CertificateValidator = X509CertificateValidator.None;

                    var registry = new ConfigurationBasedIssuerNameRegistry();
                    registry.AddTrustedIssuer("e2fcb96bf877094a510f0b77980048199617d758", "V-LAB.RAYMARKLAB.COM");
                    configuration.IssuerNameRegistry = registry;


                    jwtHandler.Configuration = configuration;

                    //var claimP = jwtHandler.ValidateToken(jwtEncodedString);
                    var claims = jwtHandler.ValidateToken(sToken);
                }
            }


            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            {
                const string relyingPartyId = "https://adfsserver.security.net/MyApp"; //ID of the relying party in AD FS
                const string adfsEndpoint   = "https://adfsserver.security.net/adfs/services/trust/13/windowsmixed";
                const string certSubject    = "CN=adfsserver.security.net";

                //Setup the connection to ADFS
                var factory = new WSTrustChannelFactory(new WindowsWSTrustBinding(SecurityMode.TransportWithMessageCredential), new EndpointAddress(adfsEndpoint))
                {
                    TrustVersion = TrustVersion.WSTrust13
                };

                //Setup the request object
                var rst = new RequestSecurityToken
                {
                    RequestType = RequestTypes.Issue,
                    KeyType     = KeyTypes.Bearer,
                    AppliesTo   = new EndpointReference(relyingPartyId)
                };

                //Open a connection to ADFS and get a token for the logged in user
                var channel      = factory.CreateChannel();
                var genericToken = channel.Issue(rst) as GenericXmlSecurityToken;

                if (genericToken != null)
                {
                    //Setup the handlers needed to convert the generic token to a SAML Token
                    var tokenHandlers = new SecurityTokenHandlerCollection(new SecurityTokenHandler[] { new SamlSecurityTokenHandler() });
                    tokenHandlers.Configuration.AudienceRestriction = new AudienceRestriction();
                    tokenHandlers.Configuration.AudienceRestriction.AllowedAudienceUris.Add(new Uri(relyingPartyId));

                    var trusted = new TrustedIssuerNameRegistry(certSubject);
                    tokenHandlers.Configuration.IssuerNameRegistry = trusted;

                    //convert the generic security token to a saml token
                    var samlToken = tokenHandlers.ReadToken(new XmlTextReader(new StringReader(genericToken.TokenXml.OuterXml)));

                    //convert the saml token to a claims principal
                    var claimsPrincipal = new ClaimsPrincipal(tokenHandlers.ValidateToken(samlToken).First());

                    //Display token information
                    Console.WriteLine("Name : " + claimsPrincipal.Identity.Name);
                    Console.WriteLine("Auth Type : " + claimsPrincipal.Identity.AuthenticationType);
                    Console.WriteLine("Is Authed : " + claimsPrincipal.Identity.IsAuthenticated);
                    foreach (var c in claimsPrincipal.Claims)
                    {
                        Console.WriteLine(c.Type + " / " + c.Value);
                    }
                    Console.ReadLine();
                }
            }
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            {
                var stsEndpoint   = "https://[server]/adfs/services/trust/13/windowstransport";
                var relayPartyUri = "https://localhost:8080/WebApp";

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

                factory.TrustVersion = TrustVersion.WSTrust13;

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

                var channel = factory.CreateChannel();

                SecurityToken token = channel.Issue(rst);
            }
            /////////////////////////////////////////////////////////////////////////////////////////////////////////
            {
                var stsEndpoint   = "https://[server]/adfs/services/trust/13/UsernameMixed";
                var relayPartyUri = "https://localhost:8080/WebApp";

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

                factory.TrustVersion = TrustVersion.WSTrust13;

                // Username and Password here...
                factory.Credentials.UserName.UserName = "";
                factory.Credentials.UserName.Password = "";

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

                var channel = factory.CreateChannel();

                SecurityToken token = channel.Issue(rst);
            }
        }
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity intances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation only
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override ClaimsIdentity GetOutputClaimsIdentity(ClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            //
            // Return a default claim set which contains a custom decision claim
            // Here you can actually examine the user by looking at the IClaimsPrincipal and
            // return the right decision based on that.
            //
            ClaimsIdentity outgoingIdentity = new ClaimsIdentity();

            outgoingIdentity.AddClaims(principal.Claims);

            return(outgoingIdentity);
        }
Beispiel #54
0
        /// <summary>
        /// This method returns the content of the issued token. The content is represented as a set of
        /// IClaimIdentity intances, each instance corresponds to a single issued token. Currently, the Windows Identity Foundation only
        /// supports a single token issuance, so the returned collection must always contain only a single instance.
        /// </summary>
        /// <param name="scope">The scope that was previously returned by GetScope method</param>
        /// <param name="principal">The caller's principal</param>
        /// <param name="request">The incoming RST, we don't use this in our implementation</param>
        /// <returns></returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            ClaimsIdentity outputIdentity = new ClaimsIdentity();

            // Add the default claims that this STS would issue

            // Name from SID as a claim
            string ntAccountValue = GetNTAccountName(principal);

            ntAccountValue = ntAccountValue.Substring(ntAccountValue.IndexOf('\\') + 1);
            outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, ntAccountValue));

            // myID claim
            outputIdentity.Claims.Add(new Claim(IPSTS2_ID_CLAIM, ntAccountValue, ClaimValueTypes.String));

            // Zipcode claim
            outputIdentity.Claims.Add(new Claim(IPSTS2_ZIPCODE_CLAIM, "98053", ClaimValueTypes.Integer));

            // IP Identifier claim
            outputIdentity.Claims.Add(new Claim(IPSTS2_IDENTIFIER_CLAIM, "IPSTS2", ClaimValueTypes.String));

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

            var claimsIdentity = principal.Identity as ClaimsIdentity;

            if (claimsIdentity == null)
            {
                throw new InvalidRequestException("The caller's identity is invalid.");
            }

            return(claimsIdentity);
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var callerIdentity = (IClaimsIdentity)principal.Identity;

            // Create new identity and copy content of the caller's identity into it (including the existing delegate chain)
            var result = new ClaimsIdentity();
            CopyClaims(callerIdentity, result);

            // If there is an ActAs token in the RST, add and return the claims from it as the top-most identity
            // and put the caller's identity into the Delegate property of this identity.
            if (request.ActAs != null)
            {
                var actAsIdentity = new ClaimsIdentity();
                var actAsSubject = request.ActAs.GetSubject()[0];
                CopyClaims(actAsSubject, actAsIdentity);

                // Find the last delegate in the actAs identity
                var lastActingVia = actAsIdentity as IClaimsIdentity;
                while (lastActingVia.Actor != null)
                {
                    lastActingVia = lastActingVia.Actor;
                }

                // Put the caller's identity as the last delegate to the ActAs identity
                lastActingVia.Actor = result;

                // Return the actAsIdentity instead of the caller's identity in this case
                result = actAsIdentity;
            }

            return result;
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal 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), ((IClaimsIdentity)principal.Identity).Claims);
            }
            else
            {
                outputClaims = ((IClaimsIdentity)principal.Identity).Claims;
            }

            outputIdentity.Claims.AddRange(outputClaims);
            if (outputIdentity.Name == null && outputIdentity.Claims.SingleOrDefault(c => c.ClaimType == ClaimTypes.NameIdentifier) != null)
                outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, outputIdentity.Claims.SingleOrDefault(c => c.ClaimType == ClaimTypes.NameIdentifier).Value));

            return outputIdentity;
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal,
            RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }
            var outputIdentity = new ClaimsIdentity();

            var userName = principal.Identity.Name;
            using (var db = new StsContext())
            {
                var webUser = db.WebUsers.Single(w => w.Username == userName);
                foreach (var requestClaim in request.Claims)
                {
                    var value = GetValueForClaimRequest(requestClaim, webUser);
                    if (value != null)
                    {
                        outputIdentity.Claims.Add(new Claim(requestClaim.ClaimType, value));
                    }
                }
                if (outputIdentity.Claims.All(c => c.ClaimType != Security.ClaimTypes.Name))
                {
                    outputIdentity.Claims.Add(new Claim(Security.ClaimTypes.Name, webUser.Username));
                }
                if (outputIdentity.Claims.All(c => c.ClaimType != Security.ClaimTypes.Role))
                {
                    outputIdentity.Claims.Add(new Claim(Security.ClaimTypes.Role, webUser.Role));
                }
            }
            return outputIdentity;
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            var outputIdentity = new ClaimsIdentity();

            if (null == principal)
            {
                throw new InvalidRequestException("The caller's principal is null.");
            }

            switch (principal.Identity.Name.ToUpperInvariant())
            {
                // In a production environment, all the information that will be added
                // as claims should be read from the authenticated Windows Principal.
                // The following lines are hardcoded because windows integrated
                // authentication is disabled.
                case "ADATUM\\JOHNDOE":
                    outputIdentity.Claims.AddRange(new List<Claim>
                       {
                           new Claim(System.IdentityModel.Claims.ClaimTypes.Name, "ADATUM\\johndoe"),
                           new Claim(AllOrganizations.ClaimTypes.Group, Adatum.Groups.DomainUsers),
                           new Claim(AllOrganizations.ClaimTypes.Group, Adatum.Groups.MarketingManagers)
                       });
                    break;
            }

            return outputIdentity;
        }
        /// <summary>
        /// This method returns the claims to be issued in the token.
        /// </summary>
        /// <param name="principal">The caller's principal.</param>
        /// <param name="request">The incoming RST, can be used to obtain addtional information.</param>
        /// <param name="scope">The scope information corresponding to this request.</param> 
        /// <exception cref="ArgumentNullException">If 'principal' parameter is null.</exception>
        /// <returns>The outgoing claimsIdentity to be included in the issued token.</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            var outputIdentity = new ClaimsIdentity();

            var attributes = (UserAttribute[])HttpContext.Current.Session["Attributes"];

            foreach (var attribute in attributes)
            {
                if (attribute.Name == "Email")
                {
                    outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Email, attribute.Value));
                }
                else if (attribute.Name == "Group")
                {
                    outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, attribute.Value));
                }
            }

            outputIdentity.Claims.Add(new Claim(System.IdentityModel.Claims.ClaimTypes.Name, principal.Identity.Name));

            return outputIdentity;
        }