If you are allowed the business to actually use the form for re-authentication (in other words, there is a page on which they enter the username and password), you can do the following.
ReauthorizeAttribute
// custom page where user does type user/pass private string revalidateLoginUrl = "/account/reauth"; private bool? hasReauthenticated = false; protected override bool AuthorizeCore(HttpContextBase httpContext) { var authUrl = HttpContext.Request.Url; hasReauthenticated = httpContext.Session[authUrl] as bool? // could be just (hasReauthenticated) // this look a bit more readable return (hasReauthenticated == true); } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext == null) { throw new ArgumentNullException("filterContext"); } var isAuthorized = AuthorizeCore(filterContext.HttpContext); var authUrl = filterContext.HttpContext.Request.Url; filterContext.HttpContext.Session[authUrl] = false; if (!isAuthorized) { HandleUnauthorizedRequest(filterContext); } } protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) { // something like this var fullUrl = validateLoginurl + "?returnUrl=" + HttpUtility.UrlEncode(revalidaetLoginUrl); filterContext.HttpContext.Response.Redirect(validateLoginUrl); }
Reauthmodel
public class ReauthModel { public string Username { get; set; } public string Password { get; set; } public string ReturnUrl { get; set; } }
AccoountController.cs ( Confirm username and password in Active Directory? )
using System.DirectoryServices.AccountManagement; public ActionResult Reauth(string returnUrl) { var model = new ReauthModel(); model.ReturnUrl = returnUrl; return View(model); } [ValidateAntiForgeryToken] public ActionResult Reauth(ReauthModel model) { using(PrincipalContext pc = new PrincipalContext(ContextType.Domain, "YOURDOMAIN")) { // validate the credentials bool isValid = pc.ValidateCredentials("myuser", "mypassword"); if (isValid) { Session[model.ReturnUrl] = true; return RedirectTolocal(model.ReturnUrl); } } // not authenticated return RedirectToAction("?"); //or model.Username = string.Empty; model.Passsword = string.Empty; return View(model); }
I think you can imagine, based on ReauthModel, what the view will look like.
Note. should be used in addition to any other authorization attribute that you use, and not instead. Since the user enters the username and password on the website, you must use SSL (even if it is internal).
source share