Example #1
0
        protected override bool IsValidRequestString(
            HttpContext context,
            string value,
            RequestValidationSource requestValidationSource,
            string collectionKey,
            out int validationFailureIndex)
        {
            validationFailureIndex = 0;

            if (requestValidationSource == RequestValidationSource.Form &&
                collectionKey.Equals(WSFederationConstants.Parameters.Result, StringComparison.Ordinal))
            {
                //创建登录消息
                //SignInResponseMessage message = WSFederationMessage.CreateFromFormPost(context.Request) as SignInResponseMessage;
                //只要是WSFed的消息都算合法验证
                WSFederationMessage message = WSFederationMessage.CreateFromFormPost(context.Request);

                if (message != null)
                {
                    return(true);
                }
            }

            return(base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex));
        }
Example #2
0
        public ActionResult SignInResponse()
        {
            if (this.User != null && this.User.Identity != null && this.User.Identity.IsAuthenticated)
            {
                var responseMessage =
                    WSFederationMessage.CreateFromFormPost(this.HttpContext.ApplicationInstance.Request);
                return(this.HandleSignInResponse(responseMessage.Context));
            }

            throw new UnauthorizedAccessException();
        }
Example #3
0
        void WSFederationAuthenticationModule_SignedIn(object sender, System.EventArgs e)
        {
            WSFederationMessage wsFederationMessage = WSFederationMessage.CreateFromFormPost(HttpContext.Current.Request);

            if (wsFederationMessage.Context != null)
            {
                var    wctx      = HttpUtility.ParseQueryString(wsFederationMessage.Context);
                string returnUrl = wctx["ru"];

                // TODO: check for absolute url and throw to avoid open redirects
                HttpContext.Current.Response.Redirect(returnUrl, false);
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }
        protected override bool IsValidRequestString(HttpContext context, string value, RequestValidationSource requestValidationSource, string collectionKey, out int validationFailureIndex)
        {
            validationFailureIndex = 0;

            HttpContextWrapper contextWrapper = new HttpContextWrapper(HttpContext.Current);

            if (requestValidationSource == RequestValidationSource.Form && collectionKey.Equals("wresult", StringComparison.Ordinal))
            {
                SignInResponseMessage message = WSFederationMessage.CreateFromFormPost(contextWrapper.Request) as SignInResponseMessage;

                if (message != null)
                {
                    return(true);
                }
            }

            return(base.IsValidRequestString(context, value, requestValidationSource, collectionKey, out validationFailureIndex));
        }
        private void HandleSignInResponse()
        {
            var responseMessage = WSFederationMessage.CreateFromFormPost(this.Page.Request);

            this.HandleSignInResponse(responseMessage);
        }
        public ActionResult Authenticate(string ReturnUrl)
        {
            if (Request.Form.Get(WSFederationConstants.Parameters.Result) != null)
            {
                var settings = this.SettingsService.Retrieve();

                // Parse sign-in response
                SignInResponseMessage message =
                    WSFederationMessage.CreateFromFormPost(System.Web.HttpContext.Current.Request) as
                    SignInResponseMessage;

                XmlTextReader xmlReader = new XmlTextReader(
                    new StringReader(message.Result));
                XDocument  xDoc = XDocument.Load(xmlReader);
                XNamespace xNs  = "http://schemas.xmlsoap.org/ws/2005/02/trust";
                var        rst  = xDoc.Descendants(xNs + "RequestedSecurityToken").FirstOrDefault();
                if (rst == null)
                {
                    throw new ApplicationException("No RequestedSecurityToken element was found in the returned XML token. Ensure an unencrypted SAML 2.0 token is issued.");
                }
                var rstDesc = rst.Descendants().FirstOrDefault();
                if (rstDesc == null)
                {
                    throw new ApplicationException("No valid RequestedSecurityToken element was found in the returned XML token. Ensure an unencrypted SAML 2.0 token is issued.");
                }

                var config = new SecurityTokenHandlerConfiguration();
                config.AudienceRestriction.AllowedAudienceUris.Add(new Uri(settings.AudienceUrl));
                config.CertificateValidator = X509CertificateValidator.None;
                config.IssuerNameRegistry   = new AccessControlServiceIssuerRegistry(
                    settings.StsIssuerUrl, settings.X509CertificateThumbprint);

                var securityTokenHandlers = new SecurityTokenHandlerCollection(config);
                securityTokenHandlers.Add(new Saml11SecurityTokenHandler());
                securityTokenHandlers.Add(new Saml2SecurityTokenHandler());
                securityTokenHandlers.Add(new EncryptedSecurityTokenHandler());

                var token = securityTokenHandlers.ReadToken(rstDesc.CreateReader());

                ClaimsIdentityCollection claims = securityTokenHandlers.ValidateToken(token);
                IPrincipal principal            = new ClaimsPrincipal(claims);

                // Map claims to local users
                string roleClaimValue     = "";
                string usernameClaimValue = "";
                string emailClaimValue    = "";
                foreach (var claimsIdentity in claims)
                {
                    foreach (var claim in claimsIdentity.Claims)
                    {
                        if (claim.ClaimType == "http://schemas.microsoft.com/ws/2008/06/identity/claims/role" && settings.TranslateClaimsToOrchardRoles)
                        {
                            roleClaimValue = claim.Value;
                        }
                        else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" && settings.TranslateClaimsToOrchardUserProperties)
                        {
                            emailClaimValue = claim.Value;
                        }
                        else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name")
                        {
                            usernameClaimValue = claim.Value;
                        }
                        else if (claim.ClaimType == "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier" && string.IsNullOrEmpty(usernameClaimValue))
                        {
                            usernameClaimValue = claim.Value;
                        }
                    }
                }

                if (string.IsNullOrEmpty(usernameClaimValue))
                {
                    throw new SecurityException("Could not determine username from input claims. Ensure a \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name\" or \"http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier\" claim is issued by the STS.");
                }

                IUser user = MembershipService.GetUser(settings.FederatedUsernamePrefix + usernameClaimValue);
                if (user == null)
                {
                    user = MembershipService.CreateUser(new CreateUserParams(settings.FederatedUsernamePrefix + usernameClaimValue,
                                                                             Guid.NewGuid().ToString(), emailClaimValue,
                                                                             Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), true));
                }

                AuthenticationService.SignIn(user, false);

                if (!string.IsNullOrEmpty(roleClaimValue))
                {
                    var role = RoleService.GetRoleByName(roleClaimValue);
                    if (role != null)
                    {
                        UserRolesPartRecord currentRole =
                            UserRolesRepository.Get(r => r.UserId == user.Id && r.Role == role);
                        if (currentRole == null)
                        {
                            UserRolesRepository.Create(new UserRolesPartRecord {
                                UserId = user.Id, Role = role
                            });
                        }
                    }
                }
            }

            return(new RedirectResult(ReturnUrl));
        }