Configure loginUrl dynamic authentication forms?

I have an ASP.NET MVC site that uses forms authentication with a custom AuthorizeAttribute for both actions and controller classes.

I have this in my web.config file:

 <authentication mode="Forms"> <forms loginUrl="~/Account/LogOn" timeout="2880" /> </authentication> 

When the site is in "normal" mode, it works fine. Users who need to log in are redirected to this page.

But when I switch to test mode, all Controllers will be locked, as well as AccountController.

Now I need to change the loginUrl value when I am in test mode to indicate a controller action that is not blocked, and this is specially done for the test scenario.

How can I change loginUrl or can I redirect from AuthorizeAttribute ?

+4
source share
1 answer

We do an override with the custom Authorize attribute, which redirects for the HandleUnauthorizedRequest function like this:

 public class AuthorizeAttribute : System.Web.Mvc.AuthorizeAttribute { public string LoginController { get; set; } public string LoginAction { get; set; } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { if (string.IsNullOrEmpty(LoginController)&&string.IsNullOrEmpty(LoginAction)) base.HandleUnauthorizedRequest(filterContext); filterContext.Result =new RedirectToRouteResult( new RouteValueDictionary(new { controller = LoginController, action = LoginAction, returnUrl = HttpContext.Current.Request.Url })); } } 

Thus, we can specify the entry route for any authorization attribute by assigning a controller and an action for the transition. Otherwise, it behaves like a standard authorize attribute.

You can change this for redirection in test mode or in real time.

+5
source

Source: https://habr.com/ru/post/1390723/


All Articles