防止開放重定向,惡意篡改returnUrl

 

1.防止開放重定向:url

  

        /// <summary>
        /// 防止開放重定向
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static bool IsLocalUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;
            bool result = ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/'));

            //絕對路徑
            if (!result && (url.StartsWith("http:", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https:", StringComparison.OrdinalIgnoreCase)))
            {
                Uri absoluteUri;
                if (Uri.TryCreate(url, UriKind.Absolute, out absoluteUri))
                {
                    return String.Equals(HttpContext.Current.Request.Url.Host, absoluteUri.Host, StringComparison.OrdinalIgnoreCase);
                }
            }
            return result;
            //來自Mvc中的UrlHelper.IsLocalUrl,只能判斷相對路徑
            //!string.IsNullOrEmpty(url) && ((url[0] == '/' && (url.Length == 1 || (url[1] != '/' && url[1] != '\\'))) || (url.Length > 1 && url[0] == '~' && url[1] == '/'));
        }

  

2.使用方法:spa

public void Login(string userName,string password, string returnUrl)
{
//logic code
//validate userName password

if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl) )
{
return Response.Redirect(returnUrl);
}
return Response.Redirect("/");
}
相關文章
相關標籤/搜索