【发布时间】:2016-04-29 01:05:40
【问题描述】:
我正在关注bitoftech tutorial 关于使用 JWT 创建基于身份和角色的声明。我的应用程序用户是具有 int PK 的自定义用户表。
目前,GenerateUserIdentityAsync 方法只返回一个奇怪的UserId not found 错误。这是我的代码:
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
以及User实体中的实现:
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 中的实例 this 确实有一个 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 对我来说并不是那么有帮助
如何找出用户 ID 不可用的原因/位置?
模式详情:
我的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(在我的例子中,就是User)
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; }
}
【问题讨论】:
-
在你的 aspnet 数据库中验证你是否有正确的列名(UserId 而不是 Id,反之亦然)。还有一种可能性是列类型不匹配(与 nvarchar(256) 相比的唯一标识符)。
标签: c# asp.net asp.net-web-api asp.net-identity