As I understand, you have to relate the AspNetUsers table from Asp.Net Identity with your current Users table. One possibility to achieve it is creating a new column (foreign key) in AspNetUsers table with your current UserId from Users table like this:
protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
var applicationUser = modelBuilder.Entity<ApplicationUser>().HasKey(u => u.Id).ToTable("Users", "dbo");
applicationUser.Property(iu => iu.UserId).HasColumnName("UserId");
...
Or just adding a new table with the relationship as you did in your question.
Web Api
Then you can override the OnAuthorizationAsync
method from AuthorizeAttribute
and get your UserId from Db using Principal.Identity.GetUserId()
:
public class WebApiAuthorizeAttribute : AuthorizeAttribute
{
public override async Task OnAuthorizationAsync(HttpActionContext actionContext, CancellationToken cancellationToken)
{
base.OnAuthorization(actionContext);
Guid userId;
if (actionContext.RequestContext.Principal.Identity.IsAuthenticated
&& Guid.TryParse(actionContext.RequestContext.Principal.Identity.GetUserId(), out userId))
{
ApplicationUserManager manager = new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext())) { PasswordHasher = new CustomPasswordHasher() };
ApplicationUser user = await manager.FindByIdAsync(userId);
actionContext.Request.Properties.Add("MyCustomId", user.MyCustomId);
}
}
}
To retrieve the value on you controller action do:
object MyCustomId;
Request.Properties.TryGetValue("MyCustomId", out MyCustomId);
ASP.NET MVC
For ASP.Net MVC override OnAuthorization instead of OnAuthorizationAsync:
public class MvcAuthorizeAttribute : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
if (HttpContext.Current.User.Identity.IsAuthenticated)
{
var userId = new Guid(HttpContext.Current.User.Identity.GetUserId());
ApplicationUserManager manager =
new ApplicationUserManager(new ApplicationUserStore(new ApplicationDbContext()))
{
PasswordHasher = new CustomPasswordHasher()
};
var user = manager.FindById(userId);
actionContext.Request.Properties.Add("MyCustomId", user.MyCustomId);
}
else
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}