我正在跟随
bitoftech tutorial关于使用JWT创建基于身份和角色的声明.我的应用程序用户是一个带有int PK的自定义User表.
目前,GenerateUserIdentityAsync方法只返回一个奇怪的UserId not found错误.这是我的代码:
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,"JWT");
和用户实体中的实现:
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User,int> manager,string authenticationType) { //error on this line: CreateIdentityAsync throws error var userIdentity = await manager.CreateIdentityAsync(this,authenticationType); return userIdentity; }
我的UserManager类定义如下:
public class AppUserManager : UserManager<User,int>
奇怪的是,当我调试时,GenerateIdentityAsync中的实例确实有一个UserId属性,但是只有一个id,我想知道这是不是错误的地方? (听起来不对)
我正在查看source code(第80行),但我无法弄清楚抛出异常的位置.
抛出的确切异常是:
UserId not found. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.InvalidOperationException: UserId not found.
stack trace并不是那么有用(对我而言)
如何找出UserId不可用的原因/位置?
模式细节:
我的GrantResourceOwnerCredentials():
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context) { context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin",new[] {"*"}); var userManager = context.OwinContext.GetUserManager<ApplicationUserManager>(); User user = await userManager.FindAsync(context.UserName,context.Password); if (user == null) // this is NOT null { context.SetError("invalid_grant","The username or password is incorrect"); return; } // this line fails ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager,"JWT"); var ticket = new AuthenticationTicket(oAuthIdentity,null); context.Validated(ticket); }
和ApplicationUser(在我的例子中,只是用户)
public partial class User : IdentityUser<int,CustomUserLogin,CustomUserRole,CustomUserClaim> { public int UserId { get; set; } public string Fullname { get; set; } public string Address { get; set; } public string ContactNumber { get; set; } }