Detailed. Net Core Authorization Filter, ActionFilterAttribute

Time:2019-8-4

AuthorizeFilter or ActionFilterAttribute is used in. Net Core to authenticate and authorize login privileges

I. AuthorizeFilter

New authorization class AllowAnonymous inherits AuthorizeFilter, IAllowAnonymousFilter


public class AllowAnonymous : AuthorizeFilter, IAllowAnonymousFilter
{

 }

New interception class inherits AuthorizeFilter


public class LoginAuthorzation : AuthorizeFilter
{

}

Adding methods to handle requests in interception classes

/// <summary>
  /// Request validation, do not throw an exception in the current validation section, ExceptionFilter will not handle it
  /// </summary>
  /// <param name="context">request content information </param>
  public override async Task OnAuthorizationAsync(AuthorizationFilterContext context)
  {
   if (IsHaveAllow(context.Filters))
   {
    return;
   }
 

   // parsing URL
   // {/ Home / Index}
   var url = context.HttpContext.Request.Path.Value;
   if (string.IsNullOrWhiteSpace(url))
   {
    return;
   }

   var list = url.Split("/");
   if (list.Length<=0||url=="/")
   {
    return;
   }
   var controllerName = list[1].ToString().Trim();
   var actionName = list[2].ToString().Trim();
 

   // Verification
   var flag=PowerIsTrue.IsHavePower(controllerName, actionName);
   if (flag.Item1!=0)
   {

    context.Result = new RedirectResult("/Home/Index");
   }
  }
 

// Determine whether permissions are not required

public static bool IsHaveAllow(IList<IFilterMetadata> filers)
  {
   for (int i = 0; i < filers.Count; i++)
   {
    if (filers[i] is IAllowAnonymousFilter)
    {
     return true;
    }
   }
   return false;

  }

Create a new business logic judgment class

public static (int,string) IsHavePower(string controllerName,string actionName)
  {

   Return (0,'through');

  }

Register in Startup

services.AddMvc(options =>
   {

    Options. Filters. Add < LoginAuthorization >(); // Add an authentication filter

   }

Context. HttpContext. Request. Path. Value

II. ActionFilterAttribute

Creating a privilege judgment class inherits ActionFilterAttribute

public class ActionFilterAttributeLogin: ActionFilterAttribute
 {
  public override void OnActionExecuting(ActionExecutingContext filterContext)

   {
   var isDefined = false;
   var controllerActionDescriptor = filterContext.ActionDescriptor as ControllerActionDescriptor;
   if (controllerActionDescriptor != null)
   {
    isDefined = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
     .Any(a => a.GetType().Equals(typeof(NoPermissionRequiredAttribute)));
   }
   if (isDefined) return;
   if (string.IsNullOrWhiteSpace(filterContext.HttpContext.Request.Query["LoginInfo"].ToString()))
   {
    var item = new ContentResult();
    Item. Content = No permission;
    
    filterContext.Result = new RedirectResult("/Account/Login");
   }
   base.OnActionExecuting(filterContext);
  }

  public class NoPermissionRequiredAttribute : ActionFilterAttribute
  {
   public override void OnActionExecuting(ActionExecutingContext filterContext)
   {
    base.OnActionExecuting(filterContext);

   }

  }
 }

Register in Startup

services.AddMvc(options =>
   {
    Options. Filters. Add < ActionFilterAttributeLogin >(); // Add Authentication Filter - Menu Operating Rights

   }

FilterContext. ActionDescriptor as Controller Action Descriptor Gets the Controller and Method Requesting Inbound

controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true )

Any (a => a. GetType (). Equals (NoPermissionRequiredAttribute).) Determine whether the controller and method of the request have NoPermissionRequiredAttribute added (no permission required)

String. IsNullOrWhiteSpace (filterContext. HttpContext. Request. Query [“LoginInfo”]. ToString ()] Determines whether the request header is identified

The above is the whole content of this article. I hope it will be helpful to everyone’s study, and I hope you will support developpaer more.

Recommended Today

The method of obtaining the resolution of display by pyqt5

The code is as follows import sys from PyQt5.QtWidgets import QApplication, QWidget class Example(QWidget): def __init__(self): super().__init__() self.initUI() #Interface drawing to initui method def initUI(self): self.desktop = QApplication.desktop() #Get display resolution size self.screenRect = self.desktop.screenGeometry() self.height = self.screenRect.height() self.width = self.screenRect.width() print(self.height) print(self.width) #Show window self.show() if __name__ == ‘__main__’: #Create applications and objects app […]