我正在跟踪 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对我来说不是很有帮助
我如何找出 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
(在我的例子中,它只是 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; }
}
最佳答案
正如您在调试 IdentityUser
时发现的那样,它有一个 Id
,在您的情况下它代表用户的 Id。
您需要从 User
类中删除 UserId
,使用 IdentityUser
中的基础 Id
并重命名将自定义用户表中的 UserId
列更改为 Id
。
User
类中的任何属性都需要在数据库的用户表中有匹配的列。如果不是,那么对于不匹配的属性,您将得到相同的错误。
这意味着 Fullname
、Address
和 ContactNumber
必须在 AspNetUsers
表中具有匹配的列名,否则对于这些属性,您也会遇到相同的错误。
关于c# - CreateUserIdenityAsync 为自定义 IdentityUser 返回 "UserId not found"异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34946575/