Ejemplo n.º 1
0
        /// <summary>
        /// 检查应用的认证Cookie是否有效。如果失效,根据autoRedirect参数来决定是否转到认证页面
        /// </summary>
        /// <param name="autoRedirect">是否自动转到认证页面</param>
        public static void CheckAuthenticated(bool autoRedirect)
        {
            Common.CheckHttpContext();
            HttpContext context = HttpContext.Current;

            TicketSource ticketSource = TicketSource.Unknown;
            ITicket      ticket       = GetTicket(out ticketSource);

            if (IsTicketValid(ticket) == false)
            {
                if (autoRedirect)
                {
                    context.Response.Redirect(GetSignInPageUrl(GetReturnUrl()));
                }
            }
            else
            {
                //票据合法
                ticket.SaveToCookie();
                ticket.SaveToHeader();

                //如果不是来源于cookie,说明来源于url。是从认证页面post过来的,直接转到应用页面即可。
                if (ticketSource != TicketSource.FromCookie && ticketSource != TicketSource.FromHeader)
                {
                    if (PassportClientSettings.GetConfig().Method == TicketTransferMethod.HttpPost &&
                        string.Compare(context.Request.HttpMethod, "POST", true) == 0)
                    {
                        context.Response.Redirect(context.Request.Url.ToString());
                    }
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 拼接认证url中的额外参数
        /// </summary>
        /// <param name="strReturlUrl"></param>
        /// <returns></returns>
        private static string GetExtraRequestParams(string strReturlUrl)
        {
            HttpRequest request = HttpContext.Current.Request;

            PassportClientSettings clientConfig = PassportClientSettings.GetConfig();

            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("ru", strReturlUrl);
            parameters.Add("to", clientConfig.AppSignInTimeout.ToString());
            parameters.Add("aid", clientConfig.AppID);
            parameters.Add("ip", request.UserHostAddress);
            parameters.Add("lou", GetLogOffCallBackUrl().ToString());
            parameters.Add("m", clientConfig.Method.ToString());

            if (TenantContext.Current.Enabled)
            {
                parameters.Add(TenantExtensions.TenantCodeParamName, TenantContext.Current.TenantCode);
            }
            //string result = "?ru=" + HttpUtility.UrlEncode(strReturlUrl)
            //                + "&to=" + HttpUtility.UrlEncode(clientConfig.AppSignInTimeout.ToString())
            //                + "&aid=" + HttpUtility.UrlEncode(clientConfig.AppID)
            //                + "&ip=" + HttpUtility.UrlEncode(request.UserHostAddress)
            //                + "&lou=" + HttpUtility.UrlEncode(GetLogOffCallBackUrl().ToString())
            //                + "&m=" + HttpUtility.UrlEncode(clientConfig.Method.ToString());

            return("?" + parameters.ToUrlParameters(true));
        }
Ejemplo n.º 3
0
        /// <summary>
        /// 获取注销后重定向地址
        /// </summary>
        /// <returns>注销后重定向url</returns>
        public static Uri GetLogOffCallBackUrl()
        {
            string strLouUrl = string.Empty;
            string locu      = PassportClientSettings.GetConfig().LogOffCallBackUrl.ToString();

            HttpRequest request = HttpContext.Current.Request;

            if (locu == string.Empty)
            {
                strLouUrl = request.Url.GetComponents(
                    UriComponents.SchemeAndServer, UriFormat.SafeUnescaped) +
                            (request.ApplicationPath == "/" ?
                             request.ApplicationPath + Common.C_LOGOFF_CALLBACK_VIRTUAL_PATH :
                             request.ApplicationPath + "/" + Common.C_LOGOFF_CALLBACK_VIRTUAL_PATH);
            }
            else
            {
                strLouUrl = ChangeUrlToCurrentServer(locu);
            }

            NameValueCollection uriParams = UriHelper.GetUriParamsCollection(strLouUrl);

            uriParams[TenantExtensions.TenantCodeParamName] = TenantContext.Current.TenantCode;

            return(new Uri(UriHelper.CombineUrlParams(strLouUrl, true, uriParams), UriKind.RelativeOrAbsolute));
        }
Ejemplo n.º 4
0
        /// <summary>
        /// 检查应用的认证Cookie是否有效。如果失效,根据autoRedirect参数来决定是否转到认证页面
        /// </summary>
        /// <param name="autoRedirect">是否自动转到认证页面</param>
        public static void CheckAuthenticated(bool autoRedirect)
        {
            Common.CheckHttpContext();
            HttpContext context = HttpContext.Current;

            bool    fromCookie = false;
            ITicket ticket     = GetTicket(out fromCookie);

            if (IsTicketValid(ticket) == false)
            {
                if (autoRedirect)
                {
                    context.Response.Redirect(GetSignInPageUrl(GetReturnUrl()));
                }
            }
            else
            {
                ticket.SaveToCookie();

                if (fromCookie == false)
                {
                    if (PassportClientSettings.GetConfig().Method == TicketTransferMethod.HttpPost &&
                        string.Compare(context.Request.HttpMethod, "POST", true) == 0)
                    {
                        context.Response.Redirect(context.Request.Url.ToString());
                    }
                }
            }
        }
Ejemplo n.º 5
0
 private static void AdjustSignInTimeout(ITicket ticket)
 {
     if (PassportClientSettings.GetConfig().HasSlidingExpiration)
     {
         ticket.AppSignInTime = SNTPClient.AdjustedTime;
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// 获取登录或注销的url,设置url中的认证后重定向的returnUrl,设置注销后重定向的logOffAutoRedirect
        /// </summary>
        /// <param name="returnUrl">认证后重定向的地址</param>
        /// <param name="logOffAutoRedirect">是否注销后重定向</param>
        /// <param name="logOffAll">是否注销所有应用</param>
        /// <returns>登录或是注销url</returns>
        public static string GetLogOnOrLogOffUrl(string returnUrl, bool logOffAutoRedirect, bool logOffAll)
        {
            Common.CheckHttpContext();
            string strResult = string.Empty;

            bool    fromCookie = false;
            ITicket ticket     = GetTicket(out fromCookie);

            HttpContext context = HttpContext.Current;
            HttpRequest request = context.Request;

            PassportClientSettings settings = PassportClientSettings.GetConfig();
            string strPassportPath          = settings.SignInUrl.ToString();

            int nSplit = strPassportPath.LastIndexOf("/");

            strPassportPath = strPassportPath.Substring(0, nSplit + 1);

            if (IsTicketValid(ticket) == true)
            {
                StringBuilder strB = new StringBuilder(1024);

                strB.Append(settings.LogOffUrl);

                if (settings.LogOffUrl.ToString().IndexOf("?") == -1)
                {
                    strB.Append("?");
                }
                else
                {
                    strB.Append("&");
                }

                NameValueCollection parameters = new NameValueCollection();

                parameters.Add("asid", ticket.SignInInfo.SignInSessionID);
                parameters.Add("ru", returnUrl);
                parameters.Add("lar", logOffAutoRedirect.ToString().ToLower());
                parameters.Add("appID", ticket.AppID);
                parameters.Add("lou", GetLogOffCallBackUrl().ToString());
                parameters.Add("loa", logOffAll.ToString().ToLower());
                parameters.Add("wi", ticket.SignInInfo.WindowsIntegrated.ToString().ToLower());
                parameters.Add("lu", ticket.SignInInfo.OriginalUserID);

                if (TenantContext.Current.Enabled)
                {
                    parameters.Add(TenantExtensions.TenantCodeParamName, TenantContext.Current.TenantCode);
                }

                strB.Append(parameters.ToUrlParameters(true));

                strResult = strB.ToString();
            }
            else
            {
                strResult = GetSignInPageUrl(returnUrl);
            }

            return(strResult);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// 将加密之后的ticket对应字符转换回来
        /// </summary>
        /// <param name="strTicketEncoded">待解密的字符串原始数据</param>
        /// <returns>解密之后的ticket对象</returns>
        /// <remarks>
        /// 解密的源数据要求采用相同加密格式要求,配置于PassportEncryptionSettings中
        /// </remarks>
        public static ITicket DecryptTicket(string strTicketEncoded)
        {
            ITicketEncryption et = PassportEncryptionSettings.GetConfig().TicketEncryption;

            byte[] data = Convert.FromBase64String(strTicketEncoded);

            return(et.DecryptTicket(data, PassportClientSettings.GetConfig().RsaKeyValue));
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 得到保存时的Cookie的Key
        /// </summary>
        /// <returns></returns>
        private string GetSavingCookieKey()
        {
            string result = PassportClientSettings.GetConfig().TicketCookieKey;

            //暂时不按照租户分Cookie
            //if (TenantContext.Current.Enabled)
            //    result += "-" + HttpUtility.UrlEncode(this.SignInInfo.TenantCode);

            return(result);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 得到加载时的Cookie的Key
        /// </summary>
        /// <returns></returns>
        public static string GetLoadingCookieKey()
        {
            string result = PassportClientSettings.GetConfig().TicketCookieKey;

            //暂时不按照租户分Cookie
            //if (TenantContext.Current.Enabled)
            //    result += "-" + HttpUtility.UrlEncode(TenantContext.Current.TenantCode);

            return(result);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// 负责认证的服务,带上Ticket重定向到应用的url
        /// </summary>
        /// <param name="ticket"></param>
        public static void SignInServiceRedirectToApp(ITicket ticket)
        {
            HttpRequest  request  = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;

            string strReturnUrl = HttpUtility.UrlDecode(request.QueryString["ru"]);
            string strLogOffUrl = request.QueryString["lou"];
            string strAppID     = request.QueryString["aid"];

            if (strAppID == null)
            {
                strAppID = PassportClientSettings.GetConfig().AppID;
            }

            System.Uri uri = request.Url;

            if (strReturnUrl != null)
            {
                uri = new Uri(strReturnUrl, UriKind.RelativeOrAbsolute);
            }

            NameValueCollection uriParams = uri.GetUriParamsCollection();

            uriParams[TenantExtensions.TenantCodeParamName] = TenantContext.Current.TenantCode;

            uri = new Uri(UriHelper.CombineUrlParams(uri.ToString(), true, uriParams), UriKind.RelativeOrAbsolute);

            if (strLogOffUrl == null)
            {
                strLogOffUrl = "#";
            }

            Uri logOffUri = new Uri(UriHelper.CombineUrlParams(strLogOffUrl, true, uriParams), UriKind.RelativeOrAbsolute);

            PassportSignInSettings.GetConfig().PersistSignInInfo.SaveTicket(
                ticket,
                uri,
                logOffUri);

            string ticketString = Common.EncryptTicket(ticket);

            TicketTransferMethod method = request.QueryString.GetValue("m", TicketTransferMethod.HttpGet);

            if (method == TicketTransferMethod.HttpGet)
            {
                RedirectTicketToApp(uri, ticketString);
            }
            else
            {
                SubmitTicketToApp(uri, ticketString);
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 获取认证页面的url
        /// </summary>
        /// <param name="strReturlUrl"></param>
        /// <param name="uid"></param>
        /// <returns></returns>
        public static string GetSignInPageUrl(string strReturlUrl, string uid)
        {
            Common.CheckHttpContext();

            string url = PassportClientSettings.GetConfig().SignInUrl.ToString() + GetExtraRequestParams(strReturlUrl);

            if (uid.IsNotEmpty())
            {
                url += "&uid=" + HttpUtility.UrlEncode(Common.EncryptString(uid));
            }

            return(url);
        }
Ejemplo n.º 12
0
        private DateTime GetConfigExpireDate()
        {
            DateTime dt = DateTime.MaxValue;

            PassportClientSettings settings = PassportClientSettings.GetConfig();

            if (settings.AppSignInTimeout >= 0)
            {
                dt = this.AppSignInTime.AddSeconds(settings.AppSignInTimeout);
            }

            return(dt);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 从Cookie中得到Ticket
        /// </summary>
        /// <returns><see cref="ITicket"/> 对象。</returns>
        public static ITicket GetTicket(out TicketSource tickedSource)
        {
            tickedSource = TicketSource.Unknown;

            Common.CheckHttpContext();

            HttpContext context = HttpContext.Current;

            ITicket ticket = null;

            if (PassportClientSettings.GetConfig().Method == TicketTransferMethod.HttpPost &&
                string.Compare(context.Request.HttpMethod, "POST", true) == 0)
            {
                tickedSource = TicketSource.FromForm;
                ticket       = Ticket.LoadFromForm();
            }
            else
            {
                tickedSource = TicketSource.FromUrl;
                ticket       = Ticket.LoadFromUrl();
            }

            if (IsTicketValid(ticket) == false)
            {
                tickedSource = TicketSource.FromHeader;
                ticket       = Ticket.LoadFromHeader();

                if (IsTicketValid(ticket) == false)
                {
                    tickedSource = TicketSource.FromCookie;

                    ticket = Ticket.LoadFromCookie();   //从Cookie中加载Ticket

                    if (ticket != null)
                    {
                        Trace.WriteLine(string.Format("从cookie中找到用户{0}的ticket", ticket.SignInInfo.UserID), "PassportSDK");
                    }
                    else
                    {
                        tickedSource = TicketSource.Unknown;
                    }
                }
            }

            if (IsTicketValid(ticket) == true)
            {
                AdjustSignInTimeout(ticket);
            }

            return(ticket);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// 相对时间过期
        /// </summary>
        /// <returns></returns>
        private bool IsSlidingExpired()
        {
            bool bExpired = false;

            PassportClientSettings settings = PassportClientSettings.GetConfig();

            if (settings.HasSlidingExpiration)
            {
                DateTime dtTO = this.AppSignInTime.Add(settings.AppSlidingExpiration);
                bExpired = (SNTPClient.AdjustedTime >= dtTO);
            }

            return(bExpired);
        }
        /// <summary>
        /// 进行认证,返回用户名
        /// </summary>
        /// <param name="ticket"><see cref="ITicket"/> 对象。</param>
        /// <returns>用户名</returns>
        protected override string GetLogOnName(out ITicket ticket)
        {
            string userID = string.Empty;

            ticket = CheckAuthenticatedAndGetTicket();

            if (ticket != null)
            {
                if (PassportClientSettings.GetConfig().IdentityWithoutDomainName)
                {
                    userID = ticket.SignInInfo.UserID;
                }
                else
                {
                    userID = ticket.SignInInfo.UserIDWithDomain;
                }

                AuthenticationModuleBase.CanLogOff = true;
            }

            return(userID);
        }
Ejemplo n.º 16
0
        /// <summary>
        /// 解密票据形成ITicket对象
        /// </summary>
        /// <param name="strTicketEncoded"></param>
        /// <returns></returns>
        public static ITicket DecryptTicket(string strTicketEncoded)
        {
            ITicket ticket = null;

            ITicketEncryption et = PassportEncryptionSettings.GetConfig().TicketEncryption;

            try
            {
                byte[] data = Convert.FromBase64String(strTicketEncoded);

                ticket = et.DecryptTicket(data, PassportClientSettings.GetConfig().RsaKeyValue);
            }
            catch (System.Exception ex)
            {
                if (ex is CryptographicException || ex is System.IO.EndOfStreamException || ex is SystemSupportException || ex is FormatException)
                {
                    throw;
                }
            }

            return(ticket);
        }
Ejemplo n.º 17
0
        private static void SetPrincipal(string userID, ITicket ticket)
        {
            IPrincipal principal = GetPrincipalInSession(userID);

            if (principal == null)
            {
                LogOnIdentity loi = new LogOnIdentity(userID);

                string identityID = string.Empty;

                if (PassportClientSettings.GetConfig().IdentityWithoutDomainName)
                {
                    identityID = loi.LogOnNameWithoutDomain;
                }
                else
                {
                    identityID = loi.LogOnName;
                }

                principal = PrincipalSettings.GetConfig().GetPrincipalBuilder().CreatePrincipal(identityID, ticket);

                HttpCookie cookie = new HttpCookie(Common.GetPrincipalSessionKey());
                cookie.Expires = DateTime.MinValue;

                CookieCacheDependency cookieDependency = new CookieCacheDependency(cookie);

                SlidingTimeDependency slidingDependency =
                    new SlidingTimeDependency(Common.GetSessionTimeOut());

                PrincipalCache.Instance.Add(
                    Common.GetPrincipalSessionKey(),
                    principal,
                    new MixedDependency(cookieDependency, slidingDependency));
            }

            PrincipaContextAccessor.SetPrincipal(principal);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 认证服务器是否一致
        /// </summary>
        /// <returns></returns>
        private bool IsDifferentAuthenticateServer()
        {
            Uri url = PassportClientSettings.GetConfig().SignInUrl;

            return(string.Compare(this.SignInInfo.AuthenticateServer, url.Host + ":" + url.Port, true) != 0);
        }