MVC3 AntiForgeryToken Issue

后端 未结 3 1407
醉梦人生
醉梦人生 2021-01-01 08:03

I am trying to implement AntiForgeryToken for my MVC3 Application. I am having a problem with AntiForgeryToken after setting FormAuthentication cookie. Here is a simple exam

3条回答
  •  误落风尘
    2021-01-01 08:25

    I did some tests, and determined that even after you call FormsAuthentication.SetAuthCookie(...), the problem is that httpContext.User.Identity.Name will still be empty for the duration of the request.

    Therefore, to solve this issue, you need to manually set the current User as so:

    FormsAuthentication.SetAuthCookie(email, true);
    this.HttpContext.User = new GenericPrincipal(new GenericIdentity(email), null);
    

    This will set the correct User that is used when Html.AntiForgeryToken() is called.

    Please note that this code isn't necessary for normal PRG-pattern websites, because after the redirect, the correct User will be loaded.

    Also, since your Logon method requires a valid user name and password, it isn't really susceptible to CSRF attacks, so you probably don't need to use ValidateAntiForgeryToken on that method. Maybe that's why the AntiForgeryToken is dependent on the user name. CSRF attacks usually only exploit already-authenticated users.

提交回复
热议问题