web-dev-qa-db-ja.com

偽造防止トークンの問題(MVC 5)

偽造防止トークンに問題があります:(正常に動作する独自のユーザークラスを作成しましたが、/ 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;
}

しかし、私がそれを行うと、私はこのエラーを受け取ります:

タイプ ' http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress 'のクレームは、提供されたClaimsIdentityに存在しませんでした。

これに出会った人はいますか?もしそうなら、あなたはそれを解決する方法を知っていますか?

事前に乾杯、
r3plica

更新1

カスタムユーザークラスは次のとおりです。

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クラス。 MyAccountControllerは次のようになります。

[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]属性で装飾されていましたが、そこで機能しなくなりました。

私はそれが十分なコードであることを願っています:)

108
r3plica

(global.csで)設定してみてください:

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
209
Alex Filipovici

ClaimsIdentityで取得するクレームを知っていますか?そうでない場合:

  1. [ValidateAntiForgeryToken]属性を削除します
  2. コントローラーのどこかにブレークポイントを置き、ブレークする
  3. 次に、現在のClaimsIdentityを見て、クレームを調べます
  4. ユーザーを一意に識別すると思われるものを見つける
  5. AntiForgeryConfig.UniqueClaimTypeIdentifierをそのクレームタイプに設定します
  6. [ValidateAntiForgeryToken]属性を戻す
56
Mike Goodwin

これをglobal.asax.csに入れるだけです

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
23
mzk

シークレットウィンドウでリンクを開くか、そのドメイン(つまりlocalhost)からCookieをクリアします。

12
Gurgen Sargsyan

編集:現時点でこの問題をよく理解しているので、以下の私の答えは無視してください。

Global.asax.csのApplication_Start()でAntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;を設定すると、修正されました。要求http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifierが設定されていても、元の質問と同じエラーが表示されます。しかし、上記のように指摘することは何らかの形で機能します。



MVC4以降、偽造防止トークンはUser.Identity.Nameを一意の識別子として使用しません。代わりに、エラーメッセージで指定された2つのクレームを探します。

注記の更新:これは必要ありませんユーザーがログインしているときに、次のように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));

クレームの1つが以前からすでに存在している可能性があることに注意してください。両方を追加すると、クレームが重複してエラーが発生します。その場合、不足しているものを追加します。

3
cederlof

Global.asax.csで、

1.これらの名前空間を追加する

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

2.メソッドApplication_Startに次の行を追加します。

 protected void Application_Start()
 {
       .......
       AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;
 } 
1
Kiran Chaudhari
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;

私の場合、ADFS認証を使用しています。

0
Ashu