ASP.NET MVC 防伪令牌问题

ASP.NET MVC Anti-Forgery Token Issues

我们在 ASP.NET MVC 4 站点上使用 Amazon EC2 Elastic Beanstalk,在用户尝试登录后出现错误:

The anti-forgery token could not be decrypted. If this application is hosted by a Web Farm or cluster, ensure that all machines are running the same version of ASP.NET Web Pages and that the configuration specifies explicit encryption and validation keys. AutoGenerate cannot be used in a cluster.

我们认为问题可能是由于会话状态处于过程中并具有动态实例,因此我们将其移至 SQL 服务器,但仍然出现错误。奇怪的是,有时登录正常,有时却出现错误。

在像 EC2 这样的动态 Web 服务器环境中,ASP.NET MVC 是否需要做一些特别的事情来处理这个问题?

您需要在 webconfig 中包含明确设置的解密密钥和验证密钥

<configuration>
  <system.web>
    <machineKey decryptionKey="Decryption key goes here, IsolateApps" 
                validationKey="Validation key goes here, IsolateApps" />
  </system.web>
</configuration>

详情可以查看以下文章http://iamdotnetcrazy.blogspot.com/2013/08/how-to-solve-anti-forgery-token-could.html

我删除了 'IsolatedApps',这似乎对我有用。

我的解决方法是像这样获取 cookie 和表单令牌值:

AntiForgery.GetTokens(null, out var cookieToken, out var formToken);