[ASP.net WebForm] 防止Open Redirect Url的程式碼

Prevent open redirect attacks in ASP.NET WebForm

前言

ASP.net WebForm貌似沒有內建Url.IsLocalUrl()這個方法,所以自己手動寫一個

Open redirect attacks在官方ASP.NET Core的說明:防止 ASP.NET Core中開啟的重新導向攻擊

內文
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace RTS.Helper
{
    /// <summary>
    /// Url字串的擴充方法
    /// </summary>
    public static class MyUrlHelper
    {
        //文章出處:https://stackoverflow.com/questions/42119735/is-there-a-version-of-islocalurl-for-webforms
        public static bool IsLocalURL(this string _url)
        {
            bool flag = false;//非Local
            if (string.IsNullOrEmpty(_url))
            {//空字串url
                return true;//給過,無資安問題
            }
            if (_url.StartsWith("/"))
            {//有值
                return true;//是Local網址
            }
            //其它
            var url = new Uri(_url);
            var ctx = HttpContext.Current;
            if (url.Host.Equals(ctx.Request.Url.Host,StringComparison.OrdinalIgnoreCase) && url.Port.Equals(ctx.Request.Url.Port))
            {
                return true;
            }
            return flag;
        }//end method
    }
}

使用方式↓

string ReturnUrl = Request.QueryString["ReturnUrl"];

if (!string.IsNullOrEmpty(ReturnUrl) && ReturnUrl.IsLocalURL())//ReturnUrl有值
{// 防止open-redirection-attacks 
//https://learn.microsoft.com/zh-tw/aspnet/mvc/overview/security/preventing-open-redirection-attacks
//https://stackoverflow.com/questions/42119735/is-there-a-version-of-islocalurl-for-webforms

 Response.Redirect(ReturnUrl);//合法的ReturnUrl才轉址
 return;//流程不往下執行
}else
{
 Response.Redirect("Index.aspx");//ReturnUrl無值、ReturnUrl是別人家網域的網址,統一轉址到「Index.aspx」
}