How do I force a user to reauthenticate before performing an Action in MVC?
We're using Windows authentication. There are some actions that we want to make sure are being performed by the user (and prevent other users from performing those actions if the user forgot to lock their workstation).
Ideally I'd just be able to write an attribute that extends Authorize
:
namespace AuthTest.Controllers
{
[Authorize(Roles="MyApp")]
public class HomeController : Controller
{
public ActionResult Index()
{
// A regular action
return View();
}
[ReAuthenticate]
public ActionResult CriticalAction()
{
// Do something important
return View();
}
}
}
It appears that I can force the user to re-enter their credentials by having the custom ReAuthenticate
attribute issue a HTTP 401
response in the AuthorizeCore
method. However, this required some trickery since Html.ActionLink
was sending two requests:
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
bool ok = base.AuthorizeCore(httpContext);
if (!ok) return false;
if (httpContext.Session["ReAuthCnt"] == null)
{
httpContext.Session["ReAuthCnt"] = 1;
return false;
}
else if ((int) httpContext.Session["ReAuthCnt"] < 2)
{
httpContext.Session["ReAuthCnt"] = (int)httpContext.Session["ReAuthCnt"] + 1;
return false;
}
else
{
httpContext.Session["ReAuthCnt"] = 0;
return true;
}
}
Is there a better way to accomplish the re-authorization?