Asp.Net MVC anti-forgery token的问题:nameidentifier or identityprovider not present

当使用ClaimsIdentity的时候,Asp.Net MVC在生成AntiForgeryToken的时候会默认使用User.Identity中两种ClaimsType的值:NameIdentifier (http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier )和IdentityProvider (http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider)。如果我们使用的STS(Security Token Service)没有提供两种ClaimsType的值,那么MVC就会报AntiForgeryToken生成失败的错误。

image

详细的错误信息是这样的:

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.

从错误提示我们可以看到Asp.net MVC强制要求提供NameIdentifier和IdentityProvider这两个值,这是默认的行为。但是这个默认的行为是可以改的。我们用ADFS,IdentityProvider这个值是没有的。根据错误消息的最后一句提示我们,可以修改AntiForgeryConfig.UniqueClaimTypeIdentifier的值,从而告诉Asp.Net MVC用别的ClaimsType的值来生成AntiForgeryToken。比如我们准备使用NameIdentifier,只需要在Global.asax.cs中添加下面一句话:

AntiForgeryConfig.UniqueClaimTypeIdentifier = System.Security.Claims.ClaimTypes.NameIdentifier;

重新编译运作之后,只要ADFS提供了NameIdentifier程序就不会再报错了。

参考资料:
posted @ 2016-03-02 17:42  排骨虾  阅读(2995)  评论(0编辑  收藏  举报