I have a Default Role for all controllers configured in my global.asax
protected override void Configure(HttpConfiguration config)
{
//Note: Client Authentication Filter is just a fancy AuthorizeAttribute
config.Filters.Add(new ClientAuthenticationFilter(APIRoles.MYAPI));
}
This adds a requirement for a role to all controllers. I would like to override that role for a specific controller
public class MFAController : ApiController
{
[HttpGet]
[Route(AuthAPIRoutes.GET_MFA_DEVICES)]
[Authorize(Roles = "MyCustomRoles")]
public MFAMethodDTO[] GetMultiFactorMethods()
{
return GlobalFactory<IMFASecurityService>.Instance.GetMultiFactorMethods();
}
//...
}
However when I do this. I get an error because my role original role APIRoles.MYAPI is missing. Is there a default way to override the AuthorizationAtrributes for controllers so they take precedence over the Global Filter?
If I understand correctly, you can do like below. This is not exactly you want, it needs to customize.
public class MyAuthorize : AuthorizeAttribute
{
public override void OnAuthorization(HttpActionContext actionContext)
{
// ...
// if (HttpContext.Current.User == null || HttpContext.Current.User.Identity == null || !HttpContext.Current.User.Identity.IsAuthenticated)
// throw new Exception("Not logged in");
}
}
[MyAuthorize]
public bool DoSomthing()
{
...
}
In my Application_Start method I'm doing some setup and logging to my database. I had an issue where my connectionstring was wrong, which is not a big deal but I'd like to validate the database is available during Application_Start() and report back to the user if it's down.
Since the httpResponse isn't yet available I can't write something to the browser.
What other practical options do I have?
Here's a quick implementation of my suggestion.
Modify global.asax to have a public variable
public class MvcApplication : System.Web.HttpApplication
{
public static bool IsConfigured { get; set; }
Set IsConfigured = true as you leave Application_Start if everything is configured
Then add a ActionFilter like this
public class ConfiguredAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (MvcApplication.IsConfigured) return;
filterContext.Result = new ViewResult
{
ViewName = "Offline",
TempData = filterContext.Controller.TempData
};
}
}
Create your Offline view in the Shared views folder
Register your new filter
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new ConfiguredAttribute());
}
}
I created a custom authorize, which is ignored when an action has [Authorize]:
public class MyGlobalAuthorizeAttribute: AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// check if action is decorated with an Authorize...
var action = filterContext.ActionDescriptor
if (action.IsDefined(typeof(AuthorizeAttribute), true))
return;
base.OnAuthorization(filterContext);
}
}
...then I configured it in the global filters, only allowing admins by default:
public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new MyGlobalAuthorizeAttribute() { Roles = "Admin" });
}
}
If I decorate an action like this:
public class MyController: Controller
{
[Authorize] // non-admins can access this action..
public ActionResult Index()
{
}
}
...it works fine. However, if I put the [Authorize] in controller, MyGlobalAuthorizeAttribute won't detect it.
I found many examples of overriding, but all of them is about an action overriding a controller or a global authorize, but not a controller overriding a global authorize.
Is it possible to achieve this?
You also need to check the ControllerDescriptor:
var action = filterContext.ActionDescriptor;
if (action.IsDefined(typeof(AuthorizeAttribute), true))
return;
if (action.ControllerDescriptor.IsDefined(typeof(AuthorizeAttribute), true))
return;
Documentation for ControllerDescriptor.IsDefined(...)
We have a Asp.net MVC Project that it has over 1000 ActionResult and I need to add all of them a C# Function for check value of Session.
So What is your offer to do this?
These two following lines has some example of my Controller and ActionResult :
public partial class CRMController : Controller
{
public ActionResult OrganizationCategory()
{
//I want add a C# function here
}
}
public partial class BaseInfoController : Controller
{
public ActionResult Lead()
{
//I Want Add a C# Function here
}
}
You can use ActionFilters for this.
The base ActionFilterAttribute class has the following methods that
you can override:
OnActionExecuting – This method is called before a controller action
is executed. OnActionExecuted – This method is called after a
controller action is executed. OnResultExecuting – This method is
called before a controller action result is executed. OnResultExecuted
– This method is called after a controller action result is executed.
Here full code example !
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
Log("OnActionExecuting", filterContext.RouteData);
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
Log("OnActionExecuted", filterContext.RouteData);
}
public override void OnResultExecuting(ResultExecutingContext filterContext)
{
Log("OnResultExecuting", filterContext.RouteData);
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
Log("OnResultExecuted", filterContext.RouteData);
}
private void Log(string methodName, RouteData routeData)
{
var controllerName = routeData.Values["controller"];
var actionName = routeData.Values["action"];
var message = String.Format("{0} controller:{1} action:{2}", methodName, controllerName, actionName);
Debug.WriteLine(message, "Action Filter Log");
}
}
[LogActionFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
Please create a action filter attribute, in that check sessions. Then create a Base Controller, then apply this attribute in that controller. Then inherit this base controller with your business controllers.
public class MySessionCheckFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
//Check Session Method()
//if(SessionNotAvaliable)
//{
// throw new businessException;
//}
base.OnActionExecuting(context);
}
}
[MySessionCheckFilterAttribute]
public class BaseController:Controller
{
}
public class YourController_One: BaseController
{
//Do anything
}
public class YourController_Two : BaseController
{
//Do anything
}
Since your function is on checking the Session, i thought it could relates to an authorization process. If so, you can try with AuthorizeAttribute
Example: Checking the Session["username"] on every Function that tagged with [AuthorizeAttribute]:
public class SessionAuthAttribute : AuthorizeAttribute
{
public SessionAuthAttribute() { }
public override void OnAuthorization(AuthorizationContext filterContext)
{
//base.OnAuthorization(filterContext);
var userID = filterContext.HttpContext.Session["username"];
if (userID == null)
{
filterContext.Result = new RedirectResult("/Home");
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(
new
{
controller = "Home",
action = "Index"
})
);
}
}
In Controller:
[SessionAuthAttribute] //Applied for whole Controller
public class HomeController : Controller
{
[SessionAuthAttribute] //Applied for 1 function
public ActionResult Index()
{
return View();
}
public ActionResult About()
{
return View();
}
}
EDIT: You can create this class in folder Attribute of your MVC Project
What is the best way to do a redirect in an ActionFilterAttribute. I have an ActionFilterAttribute called IsAuthenticatedAttributeFilter and that checked the value of a session variable. If the variable is false, I want the application to redirect to the login page. I would prefer to redirect using the route name SystemLogin however any redirect method at this point would be fine.
Set filterContext.Result
With the route name:
filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);
You can also do something like:
filterContext.Result = new ViewResult
{
ViewName = SharedViews.SessionLost,
ViewData = filterContext.Controller.ViewData
};
If you want to use RedirectToAction:
You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.
public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
return base.RedirectToAction(action, controller);
}
Then your filter would look something like:
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (SomeControllerBase) filterContext.Controller;
filterContext.Result = controller.RedirectToAction("index", "home");
}
Alternatively to a redirect, if it is calling your own code, you could use this:
actionContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new { controller = "Home", action = "Error" })
);
actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);
It is not a pure redirect but gives a similar result without unnecessary overhead.
I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.
Extend AuthorizeAttribute say CutomAuthorizer
override the OnAuthorization and HandleUnauthorizedRequest
Register the CustomAuthorizer in the RegisterGlobalFilters.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizer());
}
upon identifying the unAuthorized access call HandleUnauthorizedRequestand redirect to the concerned controller action as shown below.
public class CustomAuthorizer : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool isAuthorized = IsAuthorized(filterContext); // check authorization
base.OnAuthorization(filterContext);
if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
&& !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
{
HandleUnauthorizedRequest(filterContext);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "LogOn" },
{ "action", "Unauthorized" }
});
}
}
It sounds like you want to re-implement, or possibly extend, AuthorizeAttribute. If so, you should make sure that you inherit that, and not ActionFilterAttribute, in order to let ASP.NET MVC do more of the work for you.
Also, you want to make sure that you authorize before you do any of the real work in the action method - otherwise, the only difference between logged in and not will be what page you see when the work is done.
public class CustomAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
// Do whatever checking you need here
// If you want the base check as well (against users/roles) call
base.OnAuthorization(filterContext);
}
}
There is a good question with an answer with more details here on SO.
Try the following snippet, it should be pretty clear:
public class AuthorizeActionFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(FilterExecutingContext filterContext)
{
HttpSessionStateBase session = filterContext.HttpContext.Session;
Controller controller = filterContext.Controller as Controller;
if (controller != null)
{
if (session["Login"] == null)
{
filterContext.Cancel = true;
controller.HttpContext.Response.Redirect("./Login");
}
}
base.OnActionExecuting(filterContext);
}
}
Here is a solution that also takes in account if you are using Ajax requests.
using System;
using System.Web.Mvc;
using System.Web.Routing;
namespace YourNamespace{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeCustom : ActionFilterAttribute {
public override void OnActionExecuting(ActionExecutingContext context) {
if (YourAuthorizationCheckGoesHere) {
string area = "";// leave empty if not using area's
string controller = "ControllerName";
string action = "ActionName";
var urlHelper = new UrlHelper(context.RequestContext);
if (context.HttpContext.Request.IsAjaxRequest()){ // Check if Ajax
if(area == string.Empty)
context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(controller, action))}');</script>");
else
context.HttpContext.Response.Write($"<script>window.location.reload('{urlHelper.Content(System.IO.Path.Combine(area, controller, action))}');</script>");
} else // Non Ajax Request
context.Result = new RedirectToRouteResult(new RouteValueDictionary( new{ area, controller, action }));
}
base.OnActionExecuting(context);
}
}
}
This works for me (asp.net core 2.1)
using JustRide.Web.Controllers;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
namespace MyProject.Web.Filters
{
public class IsAuthenticatedAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
if (context.HttpContext.User.Identity.IsAuthenticated)
context.Result = new RedirectToActionResult(nameof(AccountController.Index), "Account", null);
}
}
}
[AllowAnonymous, IsAuthenticated]
public IActionResult Index()
{
return View();
}
you could inherit your controller then use it inside your action filter
inside your ActionFilterAttribute class:
if( filterContext.Controller is MyController )
if(filterContext.HttpContext.Session["login"] == null)
(filterContext.Controller as MyController).RedirectToAction("Login");
inside your base controller:
public class MyController : Controller
{
public void RedirectToAction(string actionName) {
base.RedirectToAction(actionName);
}
}
Cons. of this is to change all controllers to inherit from "MyController" class