验证防伪问题
我有一个关于 MVC 防伪造令牌的问题。 当我进行身份验证时,我有这样的伪代码:
var user = userRepository.GetByEmail(email);
System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = user;
通过这样做,我可以在我的代码中获取当前用户,如下所示:
var user = HttpContext.Current.User as EntityUser;
在我将 [ValidateAntiForgeryToken] 属性添加到操作之前,这工作正常。 当我添加属性时我得到
未提供所需的防伪令牌或该令牌无效。
如果我注释掉这一行:
System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = user;
防伪验证工作正常,但是我没有方便的方法从 HttpContext 获取“EntityUser”。 关于如何解决这个问题有什么想法吗? 此致 米凯尔
I have a problem regarding MVC Anti forgery token.
When I do my authentication I have pseudo code like this:
var user = userRepository.GetByEmail(email);
System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = user;
by doing so I'm able to get the current user in my code like this:
var user = HttpContext.Current.User as EntityUser;
This works fine until I add the [ValidateAntiForgeryToken] attribute to an action.
When I add the attribute I get
A required anti-forgery token was not supplied or was invalid.
If I comment out this line:
System.Threading.Thread.CurrentPrincipal = HttpContext.Current.User = user;
The antiforgery validation works fine, but the I don't have my convenient way of getting my "EntityUser" from the HttpContext.
Any ideas of how to work around this?
Best regards
Mikael
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不认为这些是相关的。当您将
[ValidateAntiForgeryToken]
属性添加到控制器操作时,您还需要在表单中添加隐藏字段:如果您通过 AJAX 提交,则始终需要随请求发送此令牌。
I don't think that those are related. When you add the
[ValidateAntiForgeryToken]
attribute to your controller action you also need to add the hidden field inside your form:If you are submitting it through AJAX you always need to send this token along the request.
实际上 AntiForgeryToken 使用 HttpContextBase.User 进行验证。请参阅 AntiForgeryWorker.Validate
Actually AntiForgeryToken uses HttpContextBase.User in validation. See AntiForgeryWorker.Validate