我使用Identityserver3作为MVC应用程序的授权服务器。因此,我的Startup
课程是这样的:
public void Configuration(IAppBuilder app)
{
app.UseExternalSignInCookie();
JwtSecurityTokenHandler.InboundClaimTypeMap = new Dictionary<string, string>();
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = "Cookies"
});
app.UseOpenIdConnectAuthentication(new OpenIdConnectAuthenticationOptions
{
Authority = "http://localhost:5000/",
ClientId = "mvc",
RedirectUri = "http://localhost:12262/",
ResponseType = "id_token",
UseTokenLifetime = false,
SignInAsAuthenticationType = "Cookies"
});
}
这是我的IdentityUser
子类:
public class ApplicationUser : IdentityUser
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", this.Email));
userIdentity.AddClaim(
new Claim("http://schemas.microsoft.com/accesscontrolservice/2010/07/claims/identityprovider",
this.Email));
return userIdentity;
}
public UserType UserType { get; set; }
....
}
这是我的Global.asax.cs
:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;
}
但是在我Account/Register
视图中包含@Html.AntiForgeryToken()
的行中,我收到此错误:
类型声明
'http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier' 未提供的ClaimsIdentity。
我在SO上遇到过类似问题的一些问题(可能没有在任何地方使用Identityserver3),但他们的解决方案似乎不起作用,至少我正在使用它们。
答案 0 :(得分:0)
恕我直言,我认为问题在于没有在正确的地方添加声明。但要确认这一点,我需要一些反馈。您是否使用与Identity Server相关的Microsoft.AspNet.Identity *(NuGet包)? 您是通过代码创建用户还是从数据库中读取?
例如,我在IdentityServer3中使用AspNet.Identity并为每个用户添加声明,您可以修改用户服务GetClaimsFromAccount方法,如下所示:
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using IdentityServer3.Core;
using IdentityServer3.AspNetIdentity;
using IdentityServer3.Core.Configuration;
using IdentityServer3.Core.Services;
namespace ..... {
public class UserService : AspNetIdentityUserService<IdentityUser, string>
{
public UserService(UserManager userMgr) : base(userMgr)
{
}
protected override async Task<IEnumerable<System.Security.Claims.Claim>> GetClaimsFromAccount(IdentityUser user)
{
var claims = (await base.GetClaimsFromAccount(user)).ToList();
// to make sure the email is in the claims
if (claims.Any(c=>c.Type == Constants.ClaimTypes.Email) && !string.IsNullOrWhiteSpace(user.Email))
{
claims.Add(.....);
}
return claims;
}
}
....
}
请注意,identityServer3.core附带了包含声明类型的常量(Constants.Claimtypes.Email)。
希望这有点帮助:)