セッションの値がデータベースの値と一致することを確認するカスタム ActionFilterAttribute があります。値が一致しない場合、ユーザーは AccountController の Login アクションにリダイレクトされます。
public class CheckSessionAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.ActionDescriptor.GetCustomAttributes(typeof(AllowAnonymousAttribute), false).Any())
{
// If the action allows Anonymous users, no need to check the session
return;
}
var session = filterContext.RequestContext.HttpContext.Session;
var userName = filterContext.RequestContext.HttpContext.User.Identity.Name;
var userStore = new ApplicationUserStore(new IdentityDb());
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByNameAsync(userName).Result;
if (userName == null || user == null || session == null || session["ActiveSessionId"] == null ||
session["ActiveSessionId"].ToString() != user.ActiveSessionId.ToString())
{
session.RemoveAll();
session.Clear();
session.Abandon();
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary(new
{
action = "Login",
controller = "Account"
}
));
}
base.OnActionExecuting(filterContext);
}
}
[Authorize]
public class AccountController : Controller
{
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
SignOutAndKillSession();
ViewBag.ReturnUrl = returnUrl;
return View();
}
private void SignOutAndKillSession()
{
AuthenticationManager.SignOut();
Session.RemoveAll();
Session.Clear();
Session.Abandon();
}
}
Login アクションにリダイレクトされた後に再度ログインしようとすると、次の例外が発生します。
The provided anti-forgery token was meant for a different claims-based user than the current user
Login アクション内にブレークポイントを設定すると、SignOutAndKillSession() の呼び出しの前後で、User.Identity.Name がまだログアウト中のユーザーに設定されていることがわかります。これが、ページのレンダリング時に正しくない AntiForgeryToken が生成される原因だと思います。
ユーザーをログアウトするときにユーザー プリンシパルをクリアする方法を教えてもらえますか?
ありがとう