Loc*_*rde 6 c# asp.net asp.net-web-api asp.net-identity
我正在关注使用JWT创建基于身份和角色的声明的bitoftech教程.我的应用程序用户是一个带有int PK的自定义User表.
目前,GenerateUserIdentityAsync方法只返回一个奇怪的UserId not found错误.这是我的代码:
ClaimsIdentity oAuthIdentity = await user.GenerateUserIdentityAsync(userManager, "JWT");
Run Code Online (Sandbox Code Playgroud)
以及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;
}
Run Code Online (Sandbox Code Playgroud)
我的UserManager类定义如下:
public class AppUserManager : UserManager<User, int>
Run Code Online (Sandbox Code Playgroud)
奇怪的是,当我调试时,实例this中GenerateIdentityAsync确实有一个UserId属性,但是只有一个属性,id我想知道这是不是错误的地方?(听起来不对)
我正在查看源代码(第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.
Run Code Online (Sandbox Code Playgroud)
和堆栈跟踪是不是所有的有用的(对我来说)
如何找出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);
}
Run Code Online (Sandbox Code Playgroud)
而且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; }
}
Run Code Online (Sandbox Code Playgroud)
当你发现在调试时IdentityUser有Id而你的情况将代表用户的ID.
您需要删除UserId从您的User类,使用基本Id从IdentityUser并重命名UserId您的自定义用户表列Id.
您的User类中的任何属性都需要在数据库的用户表中具有匹配的列.如果没有,那么对于不匹配的属性,您将得到相同的错误.
这意味着Fullname,Address并且ContactNumber必须在AspNetUsers表中具有匹配的列名称,否则您将获得这些属性的相同错误.
| 归档时间: |
|
| 查看次数: |
8307 次 |
| 最近记录: |