Asp.net Mvc authentication exception handling permission verification of interceptor implementation code

  • 2020-05-17 05:14:53
  • OfStack

1. User login
The steps to verify whether the user has logged in successfully are directly ignored, and how to save the current user's login information after the user has logged in successfully (session, cookie). This article introduces authentication (which is actually based on cookie). Let's take a look at the code below.
Introduce namespace
using System.Web.Security;
 
Users ModelUser = new Users() { ID = 10000, Name = UserName, UserName = UserName, PassWord = PassWord, Roles = "admin" };// The user entity  
string UserData = SerializeHelper.Instance.JsonSerialize<Users>(ModelUser);// Serialize user entities  
// Save the identity information, parameter description can see the prompt  
FormsAuthenticationTicket Ticket = new FormsAuthenticationTicket(1, UserName, DateTime.Now, DateTime.Now.AddHours(12), false, UserData); 
HttpCookie Cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket));// Encrypt identity information and save to Cookie 
Response.Cookies.Add(Cookie); 

Now that the identity information is stored in cookie, what if there is a scenario that requires the current user's user ID or other information?
So, we get the identity information in cookie again, decrypt it, and deserialize it to the user entity. That's OK.
 
/// <summary> 
///  Get user login information  
/// </summary> 
/// <returns></returns> 
public Users GetUser() 
{ 
if (HttpContext.Current.Request.IsAuthenticated)// Whether it is authenticated  
{ 
HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];// To obtain cookie 
FormsAuthenticationTicket Ticket = FormsAuthentication.Decrypt(authCookie.Value);// decryption  
return SerializeHelper.Instance.JsonDeserialize<Users>(Ticket.UserData);// deserialization  
} 
return null; 
} 

2. Permission verification
The action interceptor (rewrite OnActionExecuting) in MVC is used, and the code in the interceptor is run before action is executed. This also allows authentication to expire.
 
/// <summary> 
///  Permission to verify  
/// </summary> 
public class AuthAttribute : ActionFilterAttribute 
{ 
/// <summary> 
///  Character name  
/// </summary> 
public string Code { get; set; } 
/// <summary> 
///  Verify permissions ( action I'm going to execute it before I execute it here.)  
/// </summary> 
/// <param name="filterContext"></param> 
public override void OnActionExecuting(ActionExecutingContext filterContext) 
{ 
// If identity information exists  
if (!HttpContext.Current.User.Identity.IsAuthenticated) 
{ 
ContentResult Content = new ContentResult(); 
Content.Content = string.Format("<script type='text/javascript'>alert(' Please log in first! ');window.location.href='{0}';</script>", FormsAuthentication.LoginUrl); 
filterContext.Result = Content; 
} 
else 
{ 
string[] Role = CheckLogin.Instance.GetUser().Roles.Split(',');// Get all roles  
if (!Role.Contains(Code))// Verify permissions  
{ 
// Fail validation  
ContentResult Content = new ContentResult(); 
Content.Content = "<script type='text/javascript'>alert(' Permission verification failed! ');history.go(-1);</script>"; 
filterContext.Result = Content; 
} 
} 
} 
} 

So how do you call it in action? Here's the code posted in HomeController.
 
public class HomeController : BaseController 
{ 
[AuthAttribute(Code = "admin")]// The verification passed (this one action Only allow admin View)  
public ActionResult Index() 
{ 
Users ModelUser = CheckLogin.Instance.GetUser(); 
return View(ModelUser); 
} 
[AuthAttribute(Code = "user")]// Fail validation  
public ActionResult Index2() 
{ 
return View(); 
} 
[AuthAttribute(Code = "admin")]// The validation passed and an exception occurred  
public ActionResult Index3() 
{ 
return View(); 
} 
} 

This allows you to control permissions to action.
3. Exception handling
The above HomeController does not inherit Controller, but inherits one BaseController defined by ourselves. So what does BaseController say?
 
[ErrorAttribute] 
public class BaseController : Controller 
{ 
// all Controller inherit BaseController , the exception will be caught  
} 

In this case, BaseController only does one thing, which is to add a fault interceptor of ErrorAttribute. Then, any exception that occurs in Controller will be handled in ErrorAttribute, and you can record it to the database and other operations. So let's see how ErrorAttribute works.
 
/// <summary> 
///  Error log ( Controller When there is an exception, it will be executed here.)  
/// </summary> 
public class ErrorAttribute : ActionFilterAttribute, IExceptionFilter 
{ 
/// <summary> 
///  abnormal  
/// </summary> 
/// <param name="filterContext"></param> 
public void OnException(ExceptionContext filterContext) 
{ 
// Get the exception information and store it in storage  
Exception Error = filterContext.Exception; 
string Message = Error.Message;// The error message  
string Url = HttpContext.Current.Request.RawUrl;// Error location  
filterContext.ExceptionHandled = true; 
filterContext.Result = new RedirectResult("/Error/Show/");// Jump to the error page  
} 
} 

Here you can catch exceptions and jump to a friendly error page. A few operations in MVC are as simple as this, and the code is available for download below.

The sample code

Author: LyIng Net

Related articles: