在某些情况下,登录用户没有设置 Identity.Name(在我的情况下,我必须将我的应用程序与一些疯狂的登录系统集成)。然后有两种方法:
1) 不安全 - 所有用户都将被防伪系统以同样的方式对待,无论他们的身份验证状态如何
// System.Web.WebPages.dll
using System.Web.Helpers;
// not a production solution
public class MvcApplication : HttpApplication {
protected void Application_Start() {
AntiForgeryConfig.SuppressIdentityHeuristicChecks = true;
}
}
2) 安全 - 提供您自己(自定义)的方式来区分您的用户
using System;
using System.Globalization;
using System.Web;
using System.Web.Helpers;
public class ContoscoAntiForgeryAdditionalDataProvider : IAntiForgeryAdditionalDataProvider {
public string GetAdditionalData(HttpContextBase context) {
if (context == null) {
throw new ArgumentNullException("context");
}
var contoscoContext = new ContoscoHttpContext(context);
int userID = contoscoContext.GetUserID().GetValueOrDefault();
return Convert.ToString(userID, CultureInfo.InvariantCulture);
}
public bool ValidateAdditionalData(HttpContextBase context, string additionalData) {
string data = GetAdditionalData(context);
return string.Compare(data, additionalData, StringComparison.Ordinal) == 0;
}
}
public class MvcApplication : HttpApplication {
protected void Application_Start() {
AntiForgeryConfig.AdditionalDataProvider =
new ContoscoAntiForgeryAdditionalDataProvider();
}
}
ContoscoHttpContext
根据当前上下文(即)返回 UserID(或任何唯一用户令牌)的类在哪里HttpContextBase
:
public class ContoscoHttpContext {
private HttpContextBase _context;
public ContoscoHttpContext(HttpContextBase context) {
_context = context;
}
public int? GetUserID() {
// TODO: provide your own implementation how to get user id
// based on HttpContextBase stored in _context
// in my case it was something like
// return ((ContoscoPrincipal)_context.User).UserID;
}
}