I am trying to redirect a user to another action if his email address has not been verified. The thing is, I don’t want them to log out, I just want to redirect them. When I do this in OnAuthorization for the controller, it redirects as expected, but the user is not authenticated. I do not know why this is so. My code is as follows:
protected override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (_applicationService.CurrentUser != null)
{
if (_applicationService.CurrentUser.EmailVerified != true)
{
var url = new UrlHelper(filterContext.RequestContext);
var verifyEmailUrl = url.Action("EmailVerificationRequired", "Account", null);
filterContext.Result = new RedirectResult(verifyEmailUrl);
}
}
}
Note. I deleted the unnecessary code to make it more understandable. _applicationService.CurrentUser is populated by the current user - and the user is authenticated correctly when he gets to this point. But after the redirect, the user is no longer authenticated.
, ?
OnActionExecuting, ActionFilterAttribute, , , "" ( : System.Security.Principal. IPrincipal Controller.User) .
? , . .
:
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginViewModel model, string returnUrl)
{
string errorMessage = "The username or password is incorrect";
if (ModelState.IsValid)
{
if (_contextExecutor.ExecuteContextForModel<LoginContextModel, bool>(new LoginContextModel(){
LoginViewModel = model
}))
{
ViewBag.CurrentUser = _applicationService.CurrentUser;
_formsAuthenticationService.SetAuthCookie(model.LoginEmailAddress, model.RememberMe);
if (_applicationService.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home").Success("Thank you for logging in.");
}
else
{
errorMessage = "Email address not found or invalid password.";
}
}
return View(model).Error(errorMessage);
}