0

I'm currently working on a website which is being developed in ASP.NET and C#. To get theUserId from AspNetUsers table by simply doing User.Identity.GetUserId() which returns something like m13t79j0-4p5e-829h-4x10-fyv74k0w2ff6. Now I need to change this to a custom UserId which will be an int so something like

1
2
3
and so on

In the IdentityModel I have the following code to point to the table custom table and Id

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<ApplicationUser>().ToTable("CustomTable").Property(p => p.Id).HasColumnName("MyCustomId");
    }

However when I do User.Identity.GetUserId() it still returns this id User.Identity.GetUserId(). I'm fairly new to C# and ASP.NET so can someone tell me where I'm going wrong? Do I have to override the GetUserId() method? Thanks in advance for all your help and support

Izzy
  • 6,740
  • 7
  • 40
  • 84
  • [`IdentityExtensions.GetUserId`](http://msdn.microsoft.com/en-us/library/microsoft.aspnet.identity.identityextensions.getuserid(v=vs.108).aspx) is an extension method. You cannot override an extension but you could provide another. – Tim Schmelter Nov 17 '14 at 14:39
  • 1
    @TimSchmelter Can you elaborate a little please? – Izzy Nov 17 '14 at 14:46
  • @Downvoter care to say why? – Izzy Nov 17 '14 at 14:52

2 Answers2

2

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();
        }
    }
}
Xavier Egea
  • 4,712
  • 3
  • 25
  • 39
  • Thanks for the detailed answer. I get an error no method `OnAuthorizationAsync` to override. I'm pretty new to C# so do excuse me if I'm making an obvious mistake – Izzy Nov 17 '14 at 16:37
  • @Code Try with OnAuthorization instead of OnAuthorizationAsync. You should be using ASP.Net Mvc instead of ASP.Net Web Api, shouldn't you? – Xavier Egea Nov 17 '14 at 17:19
  • I'm not using ASP.NET MVC. I'm picking the project up more than halfway through the development lifecycle so can't really change it to MVC either – Izzy Nov 17 '14 at 17:24
  • @Code At the end, what you have to do is only retrieve from Db the UserId using User.Identity.GetUserId() as a parameter. Something like "Select UserId from AspNetUsers Where Id = 'm13t79j0-4p5e-829h-4x10-fyv74k0w2ff6'". So use the Code of OnModelCreaing that I've posted and then try to retrieve the UserId on the place you need it querying the Db. – Xavier Egea Nov 17 '14 at 17:35
  • I can retrieve the normal UserId no problem I want to retrieve a custom Id which will be an `int` instead of the long UserId `'m13t79j0-4p5e-829h-4x10-fyv74k0w2ff6` – Izzy Nov 18 '14 at 09:00
  • @Code Then you have to access to Db to retrieve the int UserId using the Guid UserId as a filter. Example: "Select UserId from AspNetUsers Where Id = 'm13t79j0-4p5e-829h-4x10-fyv74k0w2ff6' – Xavier Egea Nov 18 '14 at 09:19
  • Right, I understand what you mean. Thanks! – Izzy Nov 18 '14 at 09:33
0

try this :

var curretlyLoggedInUserId = (((System.Security.Claims.ClaimsPrincipal)System.Web.HttpContext.Current.User).Claims).ToList()[0].Value;

This gets me the Id from the AspNetUsers Table in ASP.

Anubis77
  • 102
  • 1
  • 6