ChatGPT解决这个技术问题 Extra ChatGPT

我在使用防伪令牌时遇到问题 :( 我创建了自己的 User 类,它运行良好,但现在每当我转到 /Account/Register 页面时都会收到错误消息。错误是:

“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier”或“http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider”类型的声明是不存在于提供的 ClaimsIdentity 中。要启用基于声明的身份验证的防伪令牌支持,请验证配置的声明提供程序是否在其生成的 ClaimsIdentity 实例上提供这两个声明。如果配置的声明提供程序使用不同的声明类型作为唯一标识符,则可以通过设置静态属性 AntiForgeryConfig.UniqueClaimTypeIdentifier 进行配置。

我找到了这篇文章:

http://stack247.wordpress.com/2013/02/22/antiforgerytoken-a-claim-of-type-nameidentifier-or-identityprovider-was-not-present-on-provided-claimsidentity/

所以我将我的 Application_Start 方法更改为:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();

    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);

    AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
}

但是当我这样做时,我得到了这个错误:

提供的 ClaimsIdentity 上不存在“http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress”类型的声明。

有没有人遇到过这个?如果是这样,您知道如何解决吗?

这是我的自定义用户类:

public class Profile : User, IProfile
{
    public Profile()
        : base()
    {
        this.LastLoginDate = DateTime.UtcNow;
        this.DateCreated = DateTime.UtcNow;
    }

    public Profile(string userName)
        : base(userName)
    {
        this.CreatedBy = this.Id;

        this.LastLoginDate = DateTime.UtcNow;
        this.DateCreated = DateTime.UtcNow;

        this.IsApproved = true;
    }
    
    [NotMapped]
    public HttpPostedFileBase File { get; set; }

    [Required]
    public string CompanyId { get; set; }

    [Required]
    public string CreatedBy { get; set; }
    public string ModifiedBy { get; set; }

    public DateTime DateCreated { get; set; }
    public DateTime? DateModified { get; set; }
    public DateTime LastLoginDate { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredTitle")]
    public string Title { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredFirstName")]
    public string Forename { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredLastName")]
    public string Surname { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredEmail")]
    public string Email { get; set; }
    public string JobTitle { get; set; }
    public string Telephone { get; set; }
    public string Mobile { get; set; }
    public string Photo { get; set; }
    public string LinkedIn { get; set; }
    public string Twitter { get; set; }
    public string Facebook { get; set; }
    public string Google { get; set; }
    public string Bio { get; set; }

    public string CompanyName { get; set; }

    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredCredentialId")]
    public string CredentialId { get; set; }
    [Required(ErrorMessageResourceType = typeof(Resources.Resources), ErrorMessageResourceName = "RequiredSecurityCode")]
    public bool IsLockedOut { get; set; }
    public bool IsApproved { get; set; }

    [Display(Name = "Can only edit own assets")]
    public bool CanEditOwn { get; set; }
    [Display(Name = "Can edit assets")]
    public bool CanEdit { get; set; }
    [Display(Name = "Can download assets")]
    public bool CanDownload { get; set; }
    [Display(Name = "Require approval to upload assets")]
    public bool RequiresApproval { get; set; }
    [Display(Name = "Can approve assets")]
    public bool CanApprove { get; set; }
    [Display(Name = "Can synchronise assets")]
    public bool CanSync { get; set; }

    public bool AgreedTerms { get; set; }
    public bool Deleted { get; set; }
}

public class ProfileContext : IdentityStoreContext
{
    public ProfileContext(DbContext db)
        : base(db)
    {
        this.Users = new UserStore<Profile>(this.DbContext);
    }
}

public class ProfileDbContext : IdentityDbContext<Profile, UserClaim, UserSecret, UserLogin, Role, UserRole>
{
}

我的个人资料对于我的存储库来说很简单,如下所示:

public interface IProfile
{
    string Id { get; set; }
    string CompanyId { get; set; }
    
    string UserName { get; set; }
    string Email { get; set; }

    string CredentialId { get; set; }
}

User 类是 Microsoft.AspNet.Identity.EntityFramework.User 类。我的 AccountController 如下所示:

[Authorize]
public class AccountController : Controller
{
    public IdentityStoreManager IdentityStore { get; private set; }
    public IdentityAuthenticationManager AuthenticationManager { get; private set; }
    
    public AccountController() 
    {
        this.IdentityStore = new IdentityStoreManager(new ProfileContext(new ProfileDbContext()));
        this.AuthenticationManager = new IdentityAuthenticationManager(this.IdentityStore);
    }

    //
    // GET: /Account/Register
    [AllowAnonymous]
    public ActionResult Register()
    {
        return View();
    }

    //
    // POST: /Account/Register
    [HttpPost]
    [AllowAnonymous]
    public async Task<ActionResult> Register(RegisterViewModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                // Create a profile, password, and link the local login before signing in the user
                var companyId = Guid.NewGuid().ToString();
                var user = new Profile(model.UserName)
                {
                    CompanyId = companyId,
                    Title = model.Title,
                    Forename = model.Forename,
                    Surname = model.Surname,
                    Email = model.Email,
                    CompanyName = model.CompanyName,
                    CredentialId = model.CredentialId
                };

                if (await IdentityStore.CreateLocalUser(user, model.Password))
                {
                    //Create our company
                    var company = new Skipstone.Web.Models.Company()
                    {
                        Id = companyId,
                        CreatedBy = user.Id,
                        ModifiedBy = user.Id,
                        Name = model.CompanyName
                    };

                    using (var service = new CompanyService())
                    {
                        service.Save(company);
                    }

                    await AuthenticationManager.SignIn(HttpContext, user.Id, isPersistent: false);
                    return RedirectToAction("Setup", new { id = companyId });
                }
                else
                {
                    ModelState.AddModelError("", "Failed to register user name: " + model.UserName);
                }
            }
            catch (IdentityException e)
            {
                ModelState.AddModelError("", e.Message);
            }
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

    //
    // POST: /Account/Setup
    public ActionResult Setup(string id)
    {
        var userId = User.Identity.GetUserId();
        using (var service = new CompanyService())
        {
            var company = service.Get(id);
            var profile = new Profile()
            {
                Id = userId,
                CompanyId = id
            };

            service.Setup(profile);

            return View(company);
        }
    }
}

它曾经用 [ValidateAntiForgeryToken] 属性装饰,但这就是它停止工作的地方。

为什么?

你能告诉我们自定义的用户类以及你是如何使用它的吗?
我已经添加了自定义用户类,以及我是如何使用它的。
您正在使用测试版。我建议你升级到发布版本然后看看问题是否仍然存在。

J
Jon

尝试设置(在 global.cs 中):

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

我认为重要的是要注意它为什么有效:这告诉 AntiForgery 类使用 NameIdentifier(这是 GetUserId 找到的用户 ID 字符串)。感谢迈克古德温的回答帮助我学习这个!
我在 Global.asax.cs 中设置了这个
如果您使用 OpenId(即 Azure ActiveDirectory)作为您的身份验证,这也是解决方案。
完整的命名空间.. 我不得不做一些挖掘来找出 ClaimTypes 的存放位置。 System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier = System.Security.Claims.ClaimTypes.NameIdentifier;
这是在 System.Web.WebPages.dll, v2.0.0.0 中,所以不要忘记包含这个对项目的引用
M
Mike Goodwin

您知道您在 ClaimsIdentity 中获得了哪些声明吗?如果不:

删除 [ValidateAntiForgeryToken] 属性 在控制器中的某处放置一个断点并中断它然后查看当前的 ClaimsIdentity 并检查声明找到一个您认为可以唯一标识您的用户的声明将 AntiForgeryConfig.UniqueClaimTypeIdentifier 设置为该声明类型放回 [ ValidateAntiForgeryToken] 属性


这不仅仅是提供直接的勺子喂食答案,它还讲述了背景并实现了自我发现。 :) 非常感谢
这真的帮助了我。事实证明,在我的本地主机上运行的另一个应用程序中,我的应用程序没有使用任何声明(这就是为什么声明对我来说听起来很奇怪)。因此,当我退出另一个应用程序时,声明消失了,错误也消失了。在实时测试环境中,这些站点更加分离。所以我认为我需要上述解决方案,但仅限于本地开发。
我发现这个答案更有帮助。就我而言,我正在将现有应用程序转换为使用 IdentityServer,并且开始出现此错误。使用 Mike 的方法,我能够检查声明并使用适当的声明,例如主题 ID(子声明)。
A
Ali Behzadian Nejad

只需将其放入 global.asax.cs

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;

谢谢。我不明白为什么我必须进行此更改,我修复了昨晚我的代码遇到的一些不同问题,并且一切正常。在没有改变任何东西的情况下,我在另一台机器上进行了测试,直到几分钟前它都可以正常工作。
G
Gurgen Sargsyan

尝试在隐身窗口中打开链接或从该域(即本地主机)中清除 cookie。


为什么这会起作用,问题的原因是什么?
这是因为当您有一个带有无效名称标识符的会话 cookie 时,服务器会尝试使用无效标识符而不将用户重定向到登录页面并获取正确的名称标识符。
c
cederlof

编辑:此时对这个问题有了更深入的了解,您可以忽略我在下面的回答。

在 Global.asax.cs 的 Application_Start() 中设置 AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier; 为我修复了它。即使我设置了声明 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier,我也会得到与原始问题相同的错误。但是如上所述指出它是可行的。

从 MVC4 开始,anti-forgery-token 不使用 User.Identity.Name 作为唯一标识符。相反,它会查找错误消息中给出的两个声明。

更新注意:这应该不需要您可以在用户登录时将缺少的声明添加到您的 ClaimsIdentity 中,如下所示:

string userId = TODO;
var identity = System.Web.HttpContext.Current.User.Identity as ClaimsIdentity;
identity.AddClaim(new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", userId));
identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId));

请注意,之前可能已经存在其中一个声明,如果同时添加两个声明,则会出现重复声明的错误。如果是这样,只需添加缺少的一个。


我理解您为什么使用 userId 作为“/nameidentifier”,但为什么将 userId 作为“/identityprovider”?
E
EstevaoLuis

在 Global.asax.cs 中,

1.添加这些命名空间

using System.Web.Helpers;
using System.Security.Claims;

2.在Application_Start方法中加入这一行:

 protected void Application_Start()
 {
       .......
       AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
 } 

它如何增加比上面回答的更多的价值
感谢您添加使用。 @NitinSingh 我认为这增加了更多价值,因为我不知道要使用项目中三个潜在命名空间中的哪一个。
每当您添加新功能时,它都会要求正确的引用。编译后,您应该通过右键单击 Refactor 菜单删除未使用的
A
Ashu

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;

适用于我正在使用 ADFS 身份验证的情况。


关注公众号,不定期副业成功案例分享
关注公众号

不定期副业成功案例分享

领先一步获取最新的外包任务吗?

立即订阅