Asp.net is based on Cookie's simple permission judgment

  • 2020-05-07 19:31:40
  • OfStack

After writing Cookie page, create cookie set cookie properties, and add to Response. Cookies reads cookie, use cookie name or index from Request. Got a rewrite Cookie Cookies, first create a namesake cookie, reads Request namesake cookie, read cookie attribute value to pay the new object, to join the Response. Cookies created in 1 BasePage page, other pages inherit from this page, Transfer the code of permission determination from Page_Load with a single page to PreLoad with BasePage. The following is the main code of BasePage

public class BasePage : System.Web.UI.Page 
{ 
private string pageName; 
public BasePage() 
{ 
this.Page.PreLoad += Page_Load; 
} 
protected void Page_Load(object sender, EventArgs e) 
{ 
if (!IsPostBack) 
{ 
Uri r = this.Request.Url; 
pageName = r.AbsolutePath; 
if (NeedToCheck()) 
{ 
if (!HasAuthentication()) 
{ 
HttpContext.Current.Response.Redirect("NoAuthenticationPage.aspx"); 
} 
} 
} 
} 
private bool NeedToCheck() 
{ 
if (pageName.Contains("NoAuthenticationPage.aspx") || pageName == "Login.aspx" ) 
{ 
return false; 
} 
return true; 
} 
private bool HasAuthentication() 
{ 
//look into the config file or database,to see whether this page is in the allow accessing list of the role or not; 
//the signature of the function is like this 
//QueryInConfig(m_UserRole,pageName); 
if (pageName.Contains("Default3.aspx") && UserRole == "2") 
{ 
return false; 
} 
return true; 
} 
protected HttpCookie _RequestCookie; 
protected HttpCookie _ResponseCookie; 
private bool b_IsNewCookie = true; 
public string UserRole 
{ 
get 
{ 
return GetCookieValue("UserRole"); 
} 
set 
{ 
SetCookieValue("UserRole", value); 
} 
} 
public string UserName 
{ 
get 
{ 
return GetCookieValue("UserName"); 
} 
set 
{ 
SetCookieValue("UserName", value); 
} 
} 
protected void SetCookieValue(string name, string value) 
{ 
SetResponseCookie(); 
_ResponseCookie[name] = value; 
} 
private string GetCookieValue(string name) 
{ 
SetReqeustCookie(); 
if (_RequestCookie != null) 
{ 
return _RequestCookie[name]; 
} 
return null; 
} 
protected void SetReqeustCookie() 
{ 
_RequestCookie = HttpContext.Current.Request.Cookies["Cookie_Name"]; 
} 
protected void SetResponseCookie() 
{ 
if (b_IsNewCookie) 
{ 
HttpContext.Current.Response.Cookies.Remove("Cookie_Name"); 
_ResponseCookie = new HttpCookie("Cookie_Name"); 
DateTime dtNow = DateTime.Now; 
TimeSpan tsMinute = new TimeSpan(0, 2, 0, 0); 
_ResponseCookie.Expires = dtNow + tsMinute; 
_ResponseCookie["UserRole"] = UserRole; 
_ResponseCookie["UserName"] = UserName; 
HttpContext.Current.Response.Cookies.Add(_ResponseCookie); 
b_IsNewCookie = false; 
} 
} 
} 

Related articles: