MVC 5 OWIN login with claims and AntiforgeryToken. Do I miss a ClaimsIdentity provider?
In your Application_Start()
, specify which Claim
to use as the NameIdentifier
:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
...
System.Web.Helpers.AntiForgeryConfig.UniqueClaimTypeIdentifier =
System.Security.Claims.ClaimTypes.NameIdentifier;
...
}
}
See: http://brockallen.com/2012/07/08/mvc-4-antiforgerytoken-and-claims/
Your claim identity does not have ClaimTypes.NameIdentifier
, you should add more into claim array:
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, "username"),
new Claim(ClaimTypes.Email, "[email protected]"),
new Claim(ClaimTypes.NameIdentifier, "userId"), //should be userid
};
To map the information to Claim for more corrective:
ClaimTypes.Name => map to username
ClaimTypes.NameIdentifier => map to user_id
Since username is unique also, so you are able to use username
for anti-forgery token support.
AntiForgeryConfig
One way to solve it is to set AntiForgeryConfig to use other ClaimType.
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.Email;
}
Add NameIdentifier and IdentityProvider ClaimTypes
Alternatively, you can add NameIdentifier and IdentityProvider ClaimTypes to your claims.
List<Claim> _claims = new List<Claim>();
_claims.AddRange(new List<Claim>
{
new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", _user.Email)),
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider", _user.Email)
})
See: https://stack247.wordpress.com/2013/02/22/antiforgerytoken-a-claim-of-type-nameidentifier-or-identityprovider-was-not-present-on-provided-claimsidentity/