Asp Identity将新实体与其用户

时间:2017-02-06 18:00:16

标签: c# asp.net

我正在使用一个快速演示,其中我使用Asp Identities来处理身份验证以及持票人令牌。

我创建了一个评论实体:

public class CommentModel
{
    public IdentityUser User { get; set; }
    [Key]
    public int ID { get; set; }
    public String Text { get; set; }
}

有了上下文:

public class AuthContext : IdentityDbContext<IdentityUser>
{
    public DbSet<CommentModel> Comments { get; set; }
    public AuthContext() : base("WebDatabase")
    {

    }
}

控制器方法:

[Authorize]
    // POST: api/Comments
    [ResponseType(typeof(CommentModel))]
    public async Task<IHttpActionResult> PostCommentModel(CommentModel commentModel)
    {
        if (!ModelState.IsValid)
        {
            return BadRequest(ModelState);
        }

        commentModel.User = await _repo.FindUser(User.Identity.GetUserName());
        db.Comments.Add(commentModel);
        await db.SaveChangesAsync();

        return CreatedAtRoute("DefaultApi", new { id = commentModel.ID }, commentModel);
    }

令牌生成:

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {

        context.OwinContext.Response.Headers.Add("Access-Control-Allow-Origin", new[] { "*" });

        using (AuthRepository _repo = new AuthRepository())
        {
            IdentityUser user = await _repo.FindUser(context.UserName, context.Password);

            if (user == null)
            {
                context.SetError("invalid_grant", "The user name or password is incorrect.");
                return;
            }
        }

        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        identity.AddClaim(new Claim("sub", context.UserName));
        identity.AddClaim(new Claim("role", "user"));

        context.Validated(identity);

    }

然后我创建了一个CommentsController,当用户提交一个CommentModel时,我试图在post方法中,用户字段将=当前用户。但是,当我执行类似的操作时,commentModel.User = await _repo.FindUser(User.Identity.GetUserName());传递给FindUser的变量始终为null,我也尝试使用User.Identity.GetUserId()

0 个答案:

没有答案