Custom AuthorizeAttribute in ASP.NET Core.
Introduction.
Filter in MVC are attribute which can be apply to controller and action method. filters allow us to write our custom code before and after method execution.
filters can be implemented into different level of scope Global, Class, and Method level. MVC provides different types of filters.
The Authorization filter will run first and are used to determine whether the current user is authorized or unauthorized for the current request.
In this article we will learn how to create custom authorization filter, were you can write your own authorization framework.
Description.
For creating Authorization filter IAuthorizationFilter interface must be inherited. For example, the following code demonstrate custom Authorization
below CustomAuthorization attribute allow only Home controller to access the particular method under home controller class else it will return "error" in response if it is called via ajaxcall, otherwise it will be redirect to Session Expired page.
[AttributeUsage(AttributeTargets.Class)]
public sealed class CustomAuthorization: Attribute, IAuthorizationFilter {
public void OnAuthorization(AuthorizationFilterContext filterContext) {
var controllerInfo = filterContext.ActionDescriptor as ControllerActionDescriptor;
if (filterContext != null) {
string controllerName = controllerInfo.ControllerName;
if (controllerName != "Home") {
if (filterContext.HttpContext.Request.Headers["X-Requested-With"] == "XMLHttpRequest") {
filterContext.Result = new JsonResult("") {
Value = new {
Status = "Error"
},
};
} else {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary {
{
"Controller",
"Home"
}, {
"Action",
"SessionExpired"
}
});
}
}
}
}
}
You can write your own custom logic under OnAuthorization method, by inheriting Attribute it allow us to GetCustomAttributes() method that does not look at parent declarations. It only looks at attributes applied to the specified member.
For impletmentation of above filter you need to add below namespace into your class.
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Routing;
Below defines the attribute target if we need to target Class, method, Assembly or Interface.
[AttributeUsage(AttributeTargets.Class)]
Attribute over Controller :
[CustomAuthorization]
public class HomeController: Controller {
public IActionResult Index() {
}
public IActionResult Contact() {
}
}
by applying Custom Authorization only method under home controller can be accessible.
Where Solution
ReplyDeleteWith Shawkt
DeleteHobaLaLA
ReplyDeleteTHANK YOU SO MUCH!
ReplyDelete