I used the MVC5 web template to create a new site with Individual User authentication and when I try to run it I get:
System.InvalidOperationException: 'A claim of type
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier'
or
'http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider'
was not present on the provided ClaimsIdentity. To enable anti-forgery
token support with claims-based authentication, please verify that the
configured claims provider is providing both of these claims on the
ClaimsIdentity instances it generates. If the configured claims
provider instead uses a different claim type as a unique identifier,
it can be configured by setting the static property
AntiForgeryConfig.UniqueClaimTypeIdentifier.'
I haven't changed anything in the code since it was generated. What could be causing this?
So the answer to this turned out to be to clear the cookies for the site.
As far as I can tell, the issue occured because I was also developing another MVC5 app at the same time, and that one was using a different set of authentication code (Active Directory based).
I worked out that the two apps were interfering with each other by commenting out the @Html.AntiForgeryToken()
line in the _LoginPartial class and then the home page loaded without the error. What I then saw was that I was already logged in, even though this was the first run of the app.
Clearing the cookies sorted that issue, but I definitely wasn't expecting two different MVC apps to share a cookie. However, that is actually the expected behaviour, because by default the ASP.NET Cookie Authentication will create a cookie named .AspNet.ApplicationCookie
for every app. If you inspect the cookies for your ASP site you can see this:
That's actually very easy to change, just modify the code in Startup.Configuration
to set a specific CookieName:
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "ApplicationCookie",
LoginPath = new PathString("/Account/Login"),
CookieName = "yourCookieName"
});
}
}
Then, clear the cookies for the site, run it up again and you should see the Cookie has now been renamed.