简体   繁体   English

OWIN-在Web API控制器中获取dbo.AspNetUser Id。 User.Identity.GetUserId()为null

[英]OWIN-Getting dbo.AspNetUser Id in Web API controller. User.Identity.GetUserId() is null

I am trying to get reference to the ID the Identity framework assigns my users so I can make that a foreign key in my sql db, it is currently coming back as null: 我试图引用Identity框架分配我的用户的ID,这样我就可以在我的sql db中创建一个外键,它当前返回null: 在此输入图像描述

My Startup.cs: 我的Startup.cs:

  public class Startup
  {
    public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        config.Routes.MapHttpRoute("DefaultAPI",
            "api/{controller}/{id}",
            new { id = RouteParameter.Optional });

        config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

        app.UseCors(CorsOptions.AllowAll);
        app.UseWebApi(config); 
    }

    private void ConfigureOAuth(IAppBuilder app)
    {
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
            Provider = new SimpleAuthorizationServerProvider()
        };

        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    }
}

SimpleAuthorizationServerProvider: SimpleAuthorizationServerProvider:

 public class SimpleAuthorizationServerProvider : OAuthAuthorizationServerProvider 
{
    public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
    {
        context.Validated();
    }

    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"));
        identity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));

        context.Validated(identity);

    }
}

AuthRespository.cs: AuthRespository.cs:

 public class AuthRepository : IDisposable
{
    private AuthContext _ctx;
    private UserManager<IdentityUser> _userManager;

    public AuthRepository()
    {
        _ctx = new AuthContext();
        _userManager = new UserManager<IdentityUser>(new UserStore<IdentityUser>(_ctx));
    }

    public async Task<IdentityResult> RegisterUser(UserModel userModel)
    {
        IdentityUser user = new IdentityUser
        {
            UserName = userModel.UserName
        };

        var result = await _userManager.CreateAsync(user, userModel.Password);

        return result;
    }

    public async Task<IdentityUser> FindUser(string userName, string password)
    {
        IdentityUser user = await _userManager.FindAsync(userName, password);

        return user;
    }

    public void Dispose()
    {
        _ctx.Dispose();
        _userManager.Dispose();

    }
}

UserModel.cs: UserModel.cs:

 public class UserModel
{

    [Required]
    [Display(Name = "User name")]
    public string UserName { get; set; }

    [Required]
    [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [DataType(DataType.Password)]
    [Display(Name = "Confirm password")]
    [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
    public string ConfirmPassword { get; set; }

}

When the control flow gets into GrantResourceOwnerCredentials context.UserName is properly set but the context.ClientId is null. 当控制流进入GrantResourceOwnerCredentials context.UserName时,如果设置正确,则context.ClientId为null。 How can I get this piece of information? 我怎样才能得到这条信息?

Edit: 编辑:

I see that in the lines of code: 我在代码行中看到了:

 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;
            }
        }

user.Id is the exact Id I am looking for. user.Id是我正在寻找的确切ID。 But I am not allowed to assign it to context.ClientId. 但是我不允许将它分配给context.ClientId。 Any ideas? 有任何想法吗?

Got around this by taking the User.Id property and manually setting this to a SID Claim in my Identity. 通过获取User.Id属性并在我的标识中手动将其设置为SID声明来解决这个问题。 It isn't perfect but it is the same ID anyway. 它并不完美,但无论如何它都是相同的ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM