Exemple #1
0
        private void ShowClaims(IClaimsPrincipal principal)
        {
            foreach (IClaimsIdentity identity in principal.Identities)
            {
                var identityInfo = new HtmlGenericControl("dl");
                AddListItem(identityInfo, "BootstrapToken",
                    null != identity.BootstrapToken ? identity.BootstrapToken.ToString() : String.Empty);
                AddListItem(identityInfo, "Label", identity.Label);
                AddListItem(identityInfo, "NameClaimType", identity.NameClaimType);
                AddListItem(identityInfo, "RoleClaimType", identity.RoleClaimType);

                var claimsInfo = new HtmlGenericControl("dl");
                identityInfo.Controls.Add(new HtmlGenericControl("dt") { InnerText = "Claims" });
                var claims = new HtmlGenericControl("dd");
                claims.Controls.Add(claimsInfo);
                identityInfo.Controls.Add(claims);
                foreach (Claim claim in identity.Claims)
                {
                    AddListItem(claimsInfo, "ClaimType", claim.ClaimType);
                    AddListItem(claimsInfo, "Issuer", claim.Issuer);
                    AddListItem(claimsInfo, "OriginalIssuer", claim.OriginalIssuer);
                    AddListItem(claimsInfo, "Value", claim.Value);
                    AddListItem(claimsInfo, "ValueType", claim.ValueType);
                }

                claimsList.Controls.Add(identityInfo);
            }
        }
    /// <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);

        string encryptingCertificateName = WebConfigurationManager.AppSettings["EncryptingCertificateName"];

        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);
    }
        /// <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;
        }
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (null == principal)
            {
                throw new ArgumentNullException("principal");
            }

            var name   = principal.FindClaims(ClaimTypes.Name).First().Value;
            var nameId = new Claim(ClaimTypes.NameIdentifier, name);

            var userClaims = new List <Claim>
            {
                new Claim(ClaimTypes.Name, name),
                nameId,
                new Claim(ClaimTypes.AuthenticationMethod, principal.FindClaims(ClaimTypes.AuthenticationMethod).First().Value),
                new Claim(ClaimTypes.AuthenticationInstant, XmlConvert.ToString(DateTime.UtcNow, "yyyy-MM-ddTHH:mm:ss.fffZ"), ClaimValueTypes.Datetime),
                new Claim(ClaimTypes.Upn, principal.FindClaims(ClaimTypes.Upn).First().Value),
                new Claim(ClaimTypes.Sid, principal.FindClaims(ClaimTypes.Sid).First().Value),
            };

            userClaims.AddRange(principal.FindClaims(ClaimTypes.GroupSid));

            var outputIdentity = new ClaimsIdentity(userClaims);

            return(outputIdentity);
        }
Exemple #5
0
        public bool TryIssueToken(EndpointAddress appliesTo, IClaimsPrincipal principal, string tokenType, out TokenResponse response)
        {
            SecurityToken token = null;

            response = new TokenResponse {
                TokenType = tokenType
            };

            var result = TryIssueToken(appliesTo, principal, tokenType, out token);

            if (result == false)
            {
                return(false);
            }

            var swt = token as SimpleWebToken;

            if (swt != null)
            {
                response.TokenString = swt.RawToken;
                response.ContentType = "text";
            }
            else
            {
                var handler = FederatedAuthentication.ServiceConfiguration.SecurityTokenHandlers;
                var sb      = new StringBuilder(128);
                handler.WriteToken(new XmlTextWriter(new StringWriter(sb)), token);

                response.ContentType = "text/xml";
                response.TokenString = sb.ToString();
            }

            return(result);
        }
Exemple #6
0
        public static string GetUsedEmail(IClaimsPrincipal claimsPrincipal)
        {
            if (claimsPrincipal == null)
            {
                return(GenerateFakeEmail());
            }
            var claimsIdentity = (IClaimsIdentity)claimsPrincipal.Identity;

            if (claimsIdentity.Name.Contains('@'))
            {
                // parse a claim identity to pull out a user's name
                var nameSplit = claimsIdentity.Name.Split('|');
                if (nameSplit.Length == 3)
                {
                    return(nameSplit[2]);
                }
                return(claimsIdentity.Name);
            }
            var possibleUpn = LookForClaim(claimsIdentity.Claims, Constants.ClaimUpnSts);

            if (possibleUpn != null)
            {
                return(possibleUpn);
            }
            possibleUpn = LookForClaim(claimsIdentity.Claims, Constants.ClaimUpnSp);
            if (possibleUpn != null)
            {
                return(possibleUpn);
            }
            return(GenerateFakeEmail());
        }
        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;
        }
Exemple #8
0
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            if (principal == null)
            {
                throw new ArgumentNullException("incomingPrincipal");
            }

            // We should have only one Identity.
            if (principal.Identities.Count != 1)
            {
                throw new ArgumentException("incomingPrincipal");
            }

            IClaimsIdentity identity = principal.Identities[0];

            string experienceClass = "Beginner";

            experienceClassMap.TryGetValue(identity.Name, out experienceClass);

            return(new ClaimsIdentity(
                       new Claim[]
            {
                new Claim(WSIdentityConstants.ClaimTypes.Name, identity.Name),
                new Claim(PetShopClaimTypes.ExperienceClass, experienceClass)
            }));
        }
Exemple #9
0
        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);
        }
    /// <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"));

        // 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);
    }
        private void AuthorizeCall(IClaimsPrincipal principal)
        {
            string action = OperationContext.Current.RequestContext.RequestMessage.Headers.Action;

            ClaimsPrincipalPermission p = null;

            switch (action)
            {
            case "http://www.thatindigogirl.com/samples/2006/06/ICrudService/CreateSomething":
                p = new ClaimsPrincipalPermission(true, new DefaultClaimSet(ClaimsAuthorizationPolicy.CreateIssuerClaimSet(), ClaimsAuthorizationPolicy.CreateApplicationCreateClaim()));
                p.CheckClaims(principal);
                break;

            case "http://www.thatindigogirl.com/samples/2006/06/ICrudService/ReadSomething":
                p = new ClaimsPrincipalPermission(true, new DefaultClaimSet(ClaimsAuthorizationPolicy.CreateIssuerClaimSet(), ClaimsAuthorizationPolicy.CreateApplicationReadClaim()));
                p.CheckClaims(principal);
                break;

            case "http://www.thatindigogirl.com/samples/2006/06/ICrudService/UpdateSomething":
                p = new ClaimsPrincipalPermission(true, new DefaultClaimSet(ClaimsAuthorizationPolicy.CreateIssuerClaimSet(), ClaimsAuthorizationPolicy.CreateApplicationUpdateClaim()));
                p.CheckClaims(principal);
                break;

            case "http://www.thatindigogirl.com/samples/2006/06/ICrudService/DeleteSomething":
                p = new ClaimsPrincipalPermission(true, new DefaultClaimSet(ClaimsAuthorizationPolicy.CreateIssuerClaimSet(), ClaimsAuthorizationPolicy.CreateApplicationDeleteClaim()));
                p.CheckClaims(principal);
                break;
            }
        }
Exemple #12
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);
        }
Exemple #13
0
        /// <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);

            string encryptingCertificateName = WebConfigurationManager.AppSettings["EncryptingCertificateName"];

            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.  Symmetric keys are
                // required to be 'wrapped' and the STS will throw.
                scope.TokenEncryptionRequired = false;

                // Symmetric keys are required to be 'wrapped' or the STS will throw, uncomment the code below to turn off proof key encryption.
                // Turning off proof key encryption is not secure and should not be used in a deployment scenario.

                scope.SymmetricKeyEncryptionRequired = false;
            }

            return(scope);
        }
        public override IClaimsPrincipal Authenticate(string endpointUri, IClaimsPrincipal incomingPrincipal)
        {
            Console.WriteLine("\n--ClaimsAuthenticationManager.Authenticate");

            string issuer   = "ClaimsAuthenticationManager";
            var    identity = incomingPrincipal.First();

            ClaimsIdentity id = new ClaimsIdentity(new List <Claim>
            {
                new Claim(WSIdentityConstants.ClaimTypes.Name,
                          identity.Name,
                          ClaimValueTypes.String,
                          issuer),
                new Claim("http://www.thinktecture.com/claims/clearance",
                          "Secret",
                          ClaimValueTypes.String,
                          issuer),
                identity.FindClaims(ClaimTypes.AuthenticationMethod).First(),
                identity.FindClaims(ClaimTypes.AuthenticationInstant).First()
            });

            return(new ClaimsPrincipal(new List <IClaimsIdentity> {
                id
            }));
        }
        /// <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;
        }
    /// <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" ) );

        //Wingtip implementation
        string       username = principal.Identity.Name;
        List <Claim> claims   = UserInfo.GetClaimsForUser(username);

        foreach (Claim claim in claims)
        {
            outputIdentity.Claims.Add(claim);
        }

        return(outputIdentity);
    }
Exemple #17
0
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            // do nothing if anonymous request
            if (!incomingPrincipal.Identity.IsAuthenticated)
            {
                return base.Authenticate(resourceName, incomingPrincipal);
            }

            var userRepo = (System.Web.Mvc.DependencyResolver.Current.GetService(typeof(Blog.Dal.UserRepo)) as Blog.Dal.UserRepo);

            string uniqueId = GetUniqueId(incomingPrincipal);

            // check if user is registered
            var user = userRepo.GetUserByIdentity(uniqueId);
            if (user == null)
            {
                //user = userRepo.CreateUser(uniqueId);
                //user.Claims.AddRange(ToSimpleClaim(uniqueId, incomingPrincipal.Identities[0].Claims));
            }
            else
            {
                // sync claims
            }

            //return CreateUserPrincipal(uniqueId, data);

            //// authenticated by ACS, but not registered
            //// create unique id claim
            //incomingPrincipal.Identities[0].Claims.Add(new Claim(Constants.ClaimTypes.Id, uniqueId));
            //return incomingPrincipal;

            return base.Authenticate(resourceName, incomingPrincipal);
        }
Exemple #18
0
        public override bool CheckAccess(AuthorizationContext context)
        {
            Claim            actionClaim   = context.Action.Where(x => x.ClaimType == ClaimTypes.Name).FirstOrDefault();
            Claim            resourceClaim = context.Resource.Where(x => x.ClaimType == ClaimTypes.Name).FirstOrDefault();
            IClaimsPrincipal principal     = context.Principal;

            var    resource = new Uri(resourceClaim.Value);
            string action   = actionClaim.Value;

            if (action == "GET" && resource.PathAndQuery.Contains("/frommyorganization"))
            {
                if (!principal.IsInRole("Sales"))
                {
                    return(false);
                }
            }

            if (action == "GET" && resource.PathAndQuery.Contains("/all"))
            {
                if (!principal.IsInRole("Sales Manager"))
                {
                    return(false);
                }
            }

            return(true);
        }
Exemple #19
0
        /// <summary>
        /// Gets the scope.
        /// </summary>
        /// <param name="principal">The principal.</param>
        /// <param name="request">The request.</param>
        /// <returns>Returns scope.</returns>
        protected override Scope GetScope(IClaimsPrincipal principal, RequestSecurityToken request)
        {
            ValidateAppliesTo(request.AppliesTo);

            Scope scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials)
            {
                AppliesToAddress = request.AppliesTo.Uri.AbsoluteUri
            };

            string encryptingCertificateName = GetEncryptingCertificateName(request.AppliesTo.Uri.ToString());

            if (!string.IsNullOrEmpty(encryptingCertificateName))
            {
                scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, encryptingCertificateName));
            }
            else
            {
                scope.TokenEncryptionRequired = false;
            }

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

            return(scope);
        }
Exemple #20
0
        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);
        }
Exemple #21
0
        /*internal void UpdateProfile(string ProfileAttribute, string Value)
         * {
         *  uP[ProfileAttribute].Value = Value;
         *  needProfileUpdate = true;
         * }*/

        internal Dictionary <string, string> GetClaimsForUser()
        {
            Dictionary <string, string> claims = new Dictionary <string, string>();
            IClaimsPrincipal            cp     = (IClaimsPrincipal)Thread.CurrentPrincipal;

            foreach (var c in cp.Identities[0].Claims)
            {
                string type = c.ClaimType.Substring(c.ClaimType.LastIndexOf('/') + 1);
                try
                {
                    if (!String.IsNullOrEmpty(c.Value))
                    {
                        if (c.Value.ToUpper() != "NA_NULL")
                        {
                            claims.Add(type, c.Value.Replace(" ", "_"));
                        }
                    }
                }
                catch (ArgumentException)
                {
                    //duplicated claimtype from acs and sharepoint
                }
            }
            return(claims);
        }
        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;
        }
Exemple #23
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);
        }
        public IEnumerable<Claim> GetClaims(IClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims = new List<Claim>();

            // email address
            string email = Membership.FindUsersByName(userName)[userName].Email;
            if (!String.IsNullOrEmpty(email))
            {
                claims.Add(new Claim(ClaimTypes.Email, email));
            }

            // roles
            GetRoles(userName, RoleTypes.Client).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            if (ProfileManager.Enabled)
            {
                var profile = ProfileBase.Create(userName, true);
                if (profile != null)
                {
                    foreach (SettingsProperty prop in ProfileBase.Properties)
                    {
                        string value = profile.GetPropertyValue(prop.Name).ToString();
                        if (!String.IsNullOrWhiteSpace(value))
                        {
                            claims.Add(new Claim(ProfileClaimPrefix + prop.Name.ToLowerInvariant(), value));
                        }
                    }
                }
            }

            return claims;
        }
Exemple #25
0
        public bool TryIssueToken(EndpointAddress appliesTo, IClaimsPrincipal principal, string tokenType, out SecurityToken token)
        {
            token = null;

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

            var sts = TokenServiceConfiguration.Current.CreateSecurityTokenService();

            try
            {
                var rstr = sts.Issue(principal, rst);
                token = rstr.RequestedSecurityToken.SecurityToken;
                return(true);
            }
            catch
            {
                return(false);
            }
        }
        /// <summary>
        /// Sets Windows Identify Foundation Claims
        /// </summary>
        internal static void SetClaims()
        {
            if (HttpContext.Current.ApplicationInstance.IsSTSaware())
            {
                //Set Claims
                IClaimsPrincipal principal = (IClaimsPrincipal)Thread.CurrentPrincipal;
                IClaimsIdentity  identity  = (IClaimsIdentity)principal.Identity;

                UserProfile Profile = GetCurrentConnectionToken().Profile;
                if (!string.IsNullOrEmpty(Profile.DateOfBirth))
                {
                    identity.Claims.Add(new Claim(ClaimTypes.DateOfBirth.ToString(), Profile.DateOfBirth, "string", "SocialAuth.NET", Profile.Provider.ToString()));
                }
                if (!string.IsNullOrEmpty(Profile.FirstName))
                {
                    identity.Claims.Add(new Claim(ClaimTypes.GivenName.ToString(), Profile.FirstName, "string", "SocialAuth.NET", Profile.Provider.ToString()));
                }
                if (!string.IsNullOrEmpty(Profile.LastName))
                {
                    identity.Claims.Add(new Claim(ClaimTypes.Surname.ToString(), Profile.LastName, "string", "SocialAuth.NET", Profile.Provider.ToString()));
                }
                if (!string.IsNullOrEmpty(Profile.Email))
                {
                    identity.Claims.Add(new Claim(ClaimTypes.Email.ToString(), Profile.Email, "string", "SocialAuth.NET", Profile.Provider.ToString()));
                }
                if (!string.IsNullOrEmpty(Profile.Gender))
                {
                    identity.Claims.Add(new Claim(ClaimTypes.Gender.ToString(), Profile.Gender, "string", "SocialAuth.NET", Profile.Provider.ToString()));
                }
                if (!string.IsNullOrEmpty(Profile.Country))
                {
                    identity.Claims.Add(new Claim(ClaimTypes.Country.ToString(), Profile.Country, "string", "SocialAuth.NET", Profile.Provider.ToString()));
                }
            }
        }
        /// <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;
        }
        /// <summary>
        /// This overriden method returns a collection of output subjects to be included in the issued token.
        /// </summary>
        /// <param name="scope">The scope information about the Relying Party.</param>
        /// <param name="principal">The IClaimsPrincipal that represents the identity of the requestor.</param>
        /// <param name="request">The token request parameters that arrived in the call.</param>
        /// <returns>The claims collection that will be placed inside the issued token.</returns>
        protected override IClaimsIdentity GetOutputClaimsIdentity(IClaimsPrincipal principal, RequestSecurityToken request, Scope scope)
        {
            string clientName = ServiceSecurityContext.Current.PrimaryIdentity.Name;

            if (string.IsNullOrEmpty(clientName))
            {
                throw new FaultException("The client name was not specified.");
            }

            // Create Name and PurchaseLimit claims

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

            //
            // Purchase limit claim
            //
            double purchaseLimit = GetPurchaseLimit();
            Claim  plClaim       = new Claim(ScenarioConstants.PurchaseLimitClaim, purchaseLimit.ToString());

            claims.Add(plClaim);

            //
            // Name claim
            //
            Claim nameClaim = new Claim(ClaimTypes.Name, clientName);

            claims.Add(nameClaim);

            return(new ClaimsIdentity(claims));
        }
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal.Identity.IsAuthenticated)
            {
                var identity = incomingPrincipal.Identity as IClaimsIdentity;
                var user = EnsureApplicationUser(identity);

                if (user != null)
                {
                    if (identity.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.Name) == null)
                    {
                        identity.Claims.Add(new Claim(ClaimTypes.Name, user.Name, user.Name.GetType().Name, ClaimIssuerName));
                    }

                    if (identity.Claims.FirstOrDefault(c => c.ClaimType == ClaimTypes.Email) == null)
                    {
                        identity.Claims.Add(new Claim(ClaimTypes.Email, user.Email, user.Email.GetType().Name, ClaimIssuerName));
                    }

                    foreach (var role in user.Roles)
                    {
                        identity.Claims.Add(new Claim(ClaimTypes.Role, role.RoleName, role.RoleName.GetType().Name, ClaimIssuerName));
                    }
                }
            }

            return incomingPrincipal;
        }
Exemple #30
0
        public IEnumerable <Claim> GetClaims(IClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var userName = principal.Identity.Name;
            var claims   = new List <Claim>();

            // email address
            string email = Membership.FindUsersByName(userName)[userName].Email;

            if (!String.IsNullOrEmpty(email))
            {
                claims.Add(new Claim(ClaimTypes.Email, email));
            }

            // roles
            GetRolesForToken(userName).ToList().ForEach(role => claims.Add(new Claim(ClaimTypes.Role, role)));

            // profile claims
            if (ProfileManager.Enabled)
            {
                var profile = ProfileBase.Create(userName, true);
                if (profile != null)
                {
                    foreach (SettingsProperty prop in ProfileBase.Properties)
                    {
                        string value = profile.GetPropertyValue(prop.Name).ToString();
                        if (!String.IsNullOrWhiteSpace(value))
                        {
                            claims.Add(new Claim(ProfileClaimPrefix + prop.Name.ToLowerInvariant(), value));
                        }
                    }
                }
            }

            return(claims);
        }
    /// <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 to 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);

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

        // Setting the encrypting credentials
        // Note: In this sample app, the same certificate (localhost) is used to encrypt the token for both
        // PassiveRedirectBasedClaimsAwareWebApp and WebControlBasedClaimsAwareWebAppAddress
        // In a production deployment, you would need to select the certificate that is specific to the RP that is requesting the token.
        scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, EncryptingCertificateName));

        // Set the ReplyTo address for the WS-Federation passive protocol (wreply). This is the address to which responses will be directed.
        if (request.ReplyTo != null && request.ReplyTo.ToString().StartsWith(request.AppliesTo.Uri.ToString()))
        {
            // A valid ReplyTo address was provided. We use it to send the response.
            scope.ReplyToAddress = request.ReplyTo.ToString();
        }
        else
        {
            // If the ReplyTo address is not provided or does not match the AppliesTo,
            // we set this to the Default.aspx page on the Relying Party. Note that this is not used in the WS-Trust active case.
            scope.ReplyToAddress = scope.AppliesToAddress + "/Default.aspx";
        }

        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);
        }
Exemple #33
0
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            if (!incomingPrincipal.Identity.IsAuthenticated)
            {
                return(base.Authenticate(resourceName, incomingPrincipal));
            }


            //Add permission claimes to identity

            if (SessionManager.User != null)
            {
                using (ConfigurationCoordinator coordinator = new ConfigurationCoordinator(false, false))
                {
                    //SessionManager.VolatileElements.ClientCommand = "GetConfiguration";
                    var profile = coordinator.GetConfiguration("permissions.profiles." + SessionManager.User.PermissionProfile);

                    foreach (var permission in profile.Root.Element("configValue").Element("profile").Element("permissions").Elements("permission"))
                    {
                        var claim = new Claim(FractusClaimTypes.Permission, permission.Attribute("key").Value);
                        incomingPrincipal.Identities[0].Claims.Add(claim);
                    }
                }
            }

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

            var scope = new Scope();
            return scope;
        }
Exemple #37
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, 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.");
        }

        // Issue the common claims
        // NOTE: In this sample, these claims must match the claims actually generated in Common.GetFederationMetadata.
        //       In a production system, there would be some common data store that both use
        outputIdentity.Claims.Add(new Claim(ClaimTypes.Name, principal.Identity.Name));
        outputIdentity.Claims.Add(new Claim(ClaimTypes.Role, "Manager"));

        // Issue a custom claim if requested
        IEnumerable <RequestClaim> claimCollection = (from c in request.SecondaryParameters.Claims
                                                      where c.ClaimType == Common.QuotationClassClaimType
                                                      select c);

        if (claimCollection.Count <RequestClaim>() > 0)
        {
            outputIdentity.Claims.Add(GetRandomQuoteClassClaim());
        }

        return(outputIdentity);
    }
        protected void Page_Load(object sender, EventArgs e)
        {
            // Convert to an IClaimPrincipal so we can access Claims properties
            IClaimsPrincipal claimsPrincipal = (IClaimsPrincipal)this.User;

            // Get collection of claims
            ClaimCollection claims   = claimsPrincipal.Identities[0].Claims;
            StringBuilder   sbClaims = new StringBuilder();

            // Iterate through claims, build list for rendering to UI
            foreach (Claim claim in claims)
            {
                if (claim.ClaimType.Contains("identityprovider"))
                {
                    lblIdP.Text = claim.Value;
                }
                sbClaims.AppendLine(claim.ClaimType + ": " + claim.Value);
            }
            lblClaims.Text = sbClaims.ToString();

            // check to see if the user is in the admin role
            if (User.IsInRole("admin"))
            {
                EnableAdminAccess();
            }
        }
Exemple #39
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  = (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));

                break;

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

            return(output);
        }
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal != null && incomingPrincipal.Identity.IsAuthenticated)
            {
                ClaimsIdentityCollection x509Ids = GetIdentitiesFromClaim(incomingPrincipal,
                    ClaimTypes.AuthenticationMethod, AuthenticationMethods.X509);

                foreach(IClaimsIdentity x509Identity in x509Ids)
                {
                    // this is the main identity, get the entity attributes in the Trust Fabric from the X509 thumbprint
                    string x509Thumbprint = GetClaimValue(x509Identity, "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/thumbprint");

                    if (!string.IsNullOrEmpty(x509Thumbprint))
                    {
                        string x509HexThumbprint = Base64Util.FromBase64ToHex(x509Thumbprint);

                        List<EntityAttribute> entityAttributes = _trustFabric.GetWscEntityAttributesFromX509Thumprint(x509HexThumbprint);

                        // now add the antity attributes to the identity
                        foreach (EntityAttribute entityAttribute in entityAttributes)
                        {
                            x509Identity.Claims.Add(new Claim(entityAttribute.AttributeType, entityAttribute.AttributeValue));
                        }
                    }
                }
            }

            return incomingPrincipal;
        }
        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;
        }
        /// <summary>
        /// This method returns the configuration for the token issuance request. The configuration
        /// is represented by the Scope class.
        /// </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)
        {
            var plugin = IdentityProviderPlugin.Plugin;

            if (plugin == null)
            {
                return(null);
            }

            var scope = new Scope(request.AppliesTo.Uri.OriginalString, SecurityTokenServiceConfiguration.SigningCredentials);
            var encryptingCertificateName = plugin.Configuration.GetString(IdentityProviderPlugin.PropertyId.EncryptingCertificateName);

            if (!string.IsNullOrEmpty(encryptingCertificateName))
            {
                scope.EncryptingCredentials = new X509EncryptingCredentials(CertificateUtil.GetCertificate(StoreName.My, StoreLocation.LocalMachine, encryptingCertificateName));
            }
            else
            {
                scope.TokenEncryptionRequired = false;
            }

            // Set the ReplyTo address for the WS-Federation passive protocol (wreply). This is the address to which responses will be directed.
            scope.ReplyToAddress = scope.AppliesToAddress;
            return(scope);
        }
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            if (incomingPrincipal.Identity.IsAuthenticated)
            {
                incomingPrincipal.Identities.First().Claims.Add(new Claim("http://claims/localtest", DateTime.Now.ToLongTimeString()));
            }

            return incomingPrincipal;
        }
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            if (!incomingPrincipal.Identity.IsAuthenticated)
            {
                return base.Authenticate(resourceName, incomingPrincipal);
            }

            return CreateClientIdentity(incomingPrincipal.Identity as ClaimsIdentity);
        }
        public IEnumerable<Claim> GetClaims(IClaimsPrincipal principal, RequestDetails requestDetails)
        {
            var claims = from c in NewContext.UserClaims
                         where c.PartitionKey == principal.Identity.Name.ToLower() &&
                               c.Kind == UserClaimEntity.EntityKind
                         select new Claim(c.ClaimType, c.Value);

            return claims.ToList();
        }
        public static bool CheckAccess(IClaimsPrincipal principal, string action, string resource, params string[] additionalResources)
        {
            var context = CreateAuthorizationContext(
                principal,
                action,
                resource,
                additionalResources);

            return ClaimsAuthorization.CheckAccess(context);
        }
        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;
        }
        /// <summary>
        /// Processes a WS-Federation request.
        /// </summary>
        /// <param name="request">The WS-Federation request message.</param>
        /// <param name="principal">The client principal.</param>
        /// <param name="configuration">The token service configuration.</param>
        public static void ProcessRequest(WSFederationMessage request, IClaimsPrincipal principal, SecurityTokenServiceConfiguration configuration)
        {
            Contract.Requires(request != null);
            Contract.Requires(principal != null);
            Contract.Requires(configuration != null);


            HttpContext context = HttpContext.Current;

            if (request.Action == WSFederationConstants.Actions.SignIn)
            {
                var response = ProcessSignInRequest(
                    (SignInRequestMessage)request,
                    principal,
                    configuration);

                response.Write(context.Response.Output);
                context.Response.Flush();
                context.Response.End();
            }
            else if (request.Action == WSFederationConstants.Actions.SignOut)
            {
                var signOut = (SignOutRequestMessage)request;
                ProcessSignOutRequest();

                if (!String.IsNullOrEmpty(signOut.Reply))
                {
                    context.Response.Redirect(signOut.Reply);
                }
                else
                {
                    context.Response.Redirect("~/");
                }
            }
            else if (request.Action == WSFederationConstants.Actions.SignOutCleanup)
            {
                var signOut = (SignOutCleanupRequestMessage)request;
                ProcessSignOutRequest();

                if (!String.IsNullOrEmpty(signOut.Reply))
                {
                    context.Response.Redirect(signOut.Reply);
                }
                else
                {
                    context.Response.Redirect("~/");
                }
            }
            else
            {
                throw new InvalidOperationException(String.Format(
                             CultureInfo.InvariantCulture,
                             "Unsupported Action: {0}", request.Action));
            }
        }
        /// <summary>
        /// Authenticates a specified resource by its name.
        /// </summary>
        /// <param name="resourceName">
        /// Name of the resource. 
        /// </param>
        /// <param name="claimsPrincipal">
        /// The claims principal. 
        /// </param>
        /// <returns>
        /// Returns claims principal for given resource 
        /// </returns>
        public override IClaimsPrincipal Authenticate( string resourceName, IClaimsPrincipal claimsPrincipal )
        {
            if ( claimsPrincipal.Identity.IsAuthenticated )
            {
                var sessionFactory = GetSessionFactory ();

                using ( var session = sessionFactory.GetCurrentSession () )
                using ( var trans = session.BeginTransaction () )
                {
                    var identity = claimsPrincipal.Identity as IClaimsIdentity;
                    if ( identity != null )
                    {
                        var nameIdentifier = identity.Claims.First ( c => c.ClaimType == Microsoft.IdentityModel.Claims.ClaimTypes.NameIdentifier ).Value;
                        Logger.Debug("Name identifier for authenticated principal ({0}): {1}.", identity.Name, nameIdentifier);

                        Logger.Debug("Resolving dependency on {0}.", typeof(ISystemAccountRepository).Name);
                        var systemAccountRepository = IoC.CurrentContainer.Resolve<ISystemAccountRepository>();
                        Logger.Debug("Resolved dependency on {0}.", typeof(ISystemAccountRepository).Name);

                        var systemAccount = systemAccountRepository.GetByIdentifier ( nameIdentifier );

                        if ( systemAccount != null )
                        {
                            Logger.Debug("Resolving dependency on {0}.", typeof(IPermissionClaimsManager).Name);
                            var permissionClaimsManager = IoC.CurrentContainer.Resolve<IPermissionClaimsManager>();
                            Logger.Debug("Resolved dependency on {0}.", typeof(IPermissionClaimsManager).Name);

                            Logger.Debug("Issue more claims for ({0} ({1}))", systemAccount.DisplayName, systemAccount.EmailAddress.Address);
                            permissionClaimsManager.IssueSystemPermissionClaims ( claimsPrincipal, systemAccount );
                            permissionClaimsManager.IssueAccountKeyClaims ( claimsPrincipal, systemAccount );
                        }
                        else
                        {
                            var errorMessage = string.Format (
                                "Authenticated principal ({0}) with identifier ({1}) does not have a system account in REM.", identity.Name, nameIdentifier );
                            Logger.Debug(errorMessage);
                        }
                    }

                    trans.Commit ();
                }
            }
            else
            {
                Logger.Debug("Resolving dependency on {0}.", typeof(IFederatedAuthenticationProvider).Name);
                var federatedAuthenticationProvider = IoC.CurrentContainer.Resolve<IFederatedAuthenticationProvider>();
                Logger.Debug("Resolved dependency on {0}.", typeof(IFederatedAuthenticationProvider).Name);

                var federationAuthenticationModule = federatedAuthenticationProvider.GetFederationAuthenticationModule ();
                Logger.Debug("Incoming IClaimsPrincipal was not authenticated. WIF will will redirect the request to the identity server {0}.", federationAuthenticationModule.Issuer);
            }

            return claimsPrincipal;
        }
        /// <summary>
        /// Checks the authorization policy.
        /// </summary>
        /// <param name="resource">The resource.</param>
        /// <param name="action">The action.</param>
        /// <param name="principal">The principal.</param>
        /// <returns>true when authorized, otherwise false</returns>
        public static bool CheckAccess(string resource, string action, IClaimsPrincipal principal)
        {
            Contract.Requires(!String.IsNullOrEmpty(resource));
            Contract.Requires(!String.IsNullOrEmpty(action));
            Contract.Requires(principal != null);


            var context = new AuthorizationContext(principal, resource, action);

            return AuthorizationManager.CheckAccess(context);
        }
Exemple #51
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;
            }
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            if (!incomingPrincipal.Identity.IsAuthenticated)
            {
                return base.Authenticate(resourceName, incomingPrincipal);
            }

            UserRepository.GetRoles(incomingPrincipal.Identity.Name, RoleTypes.IdentityServer).ToList().ForEach(role =>
                incomingPrincipal.Identities[0].Claims.Add(new Claim(ClaimTypes.Role, role)));

            return incomingPrincipal;
        }
 /// <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;
 }
        public override IClaimsPrincipal Authenticate(string resourceName, IClaimsPrincipal incomingPrincipal)
        {
            var identity = incomingPrincipal.Identity as IClaimsIdentity;

            if (identity == null)
                throw new ArgumentException("Principal must have an identity of type IClaimsIdentity");

            //Only process if the identity is authenticated, otherwise, we want the pipeline to redirect to the STS
            if (identity.IsAuthenticated)
                return base.Authenticate(resourceName, ClaimsAuthenticationManagerProvider.Get(resourceName, incomingPrincipal));
            return base.Authenticate(resourceName, incomingPrincipal);
        }
        /// <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;
        }
        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;
        }