[C#] 위조 방지 토큰 발행 (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;
}

그러나 그렇게하면 다음 오류가 발생합니다.

제공된 ClaimsIdentity에 ‘ http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress ‘ 유형의 클레임 이 없습니다.

누군가 전에 이것을 본 적이 있습니까? 그렇다면 해결 방법을 알고 있습니까?

미리 건배,
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; }
}

사용자 클래스는이다 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] 속성 으로 데코 레이팅 되었지만 작동이 중지되었습니다.

충분한 코드가 되길 바랍니다. 🙂



답변

(global.cs에서) 설정을 시도하십시오.

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;


답변

ClaimsIdentity에서 어떤 클레임을 받는지 알고 있습니까? 그렇지 않은 경우 :

  1. [ValidateAntiForgeryToken]속성 제거
  2. 컨트롤러 어딘가에 중단 점을 놓고 중단하십시오.
  3. 그런 다음 현재를보고 ClaimsIdentity주장을 검토하십시오.
  4. 사용자를 고유하게 식별 할 것으로 생각되는 것을 찾으십시오.
  5. 를 설정 AntiForgeryConfig.UniqueClaimTypeIdentifier그 주장의 유형
  6. [ValidateAntiForgeryToken]속성 되돌리기

답변

이것을 global.asax.cs에 넣으십시오.

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimsIdentity.DefaultNameClaimType;


답변

시크릿 창에서 링크를 열거 나 해당 도메인 (예 : localhost)에서 쿠키를 삭제 해보세요.


답변

편집 : 현재이 문제에 대해 더 잘 이해하고 있으면 아래의 내 대답을 무시할 수 있습니다.

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;Global.asax.cs의 Application_Start ()에서 설정하면 문제가 해결 되었습니다. 클레임 http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier세트 가 있지만 원래 질문과 동일한 오류가 발생합니다. 그러나 위와 같이 지적하면 어떻게 든 작동합니다.



MVC4부터 위조 방지 토큰은 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));

클레임 중 하나가 이전에 이미있을 수 있으며 둘 다 추가하면 중복 클레임과 함께 오류가 발생합니다. 그렇다면 누락 된 것을 추가하십시오.


답변

Global.asax.cs에서

1. 다음 네임 스페이스 추가

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

2. Application_Start 메서드에 다음 줄을 추가합니다.

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


답변

AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;

내 경우에는 ADFS 인증을 사용하고 있습니다.