J86
J86

Reputation: 15307

Id returned by UserManager is different from Id in Database

BACKGROUND

I'm working on a .Net Core API project to drive a community-driven lyrics website. So users can submit artists & lyrics. Each artist has many lyrics (classic one-to-many).

For authentication & authorization, I am using JWT tokens.

CODE

On my Lyrics Controller, I have a [HttpPost] method for the creation of a lyric. Here's the code:

[Authorize]
[HttpPost("{artistSlug}/lyrics")]
public async Task<IActionResult> CreateLyric(string artistSlug, [FromBody] LyricCreateDto newLyricCreateDto)
{
  if (newLyricCreateDto == null) return BadRequest();
  if (!ModelState.IsValid) return BadRequest(ModelState);
  var user = _userManager.GetUserAsync(HttpContext.User);
  var lyricReadDto = await _lyricsService.AddNewLyric(user.Id.ToString(), artistSlug, newLyricCreateDto);
  if (lyricReadDto == null) return NotFound();
  return CreatedAtRoute("GetLyric", new {artistSlug, lyricSlug = lyricReadDto.Slug}, lyricReadDto);
}

In my Startup.cs I have the following:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, DatabaseDataSeeder databaseDataSeeder)
{
  loggerFactory.AddConsole();

  app.UseJwtBearerAuthentication(new JwtBearerOptions
  {
    AutomaticAuthenticate = true,
    AutomaticChallenge = true,
    TokenValidationParameters = new TokenValidationParameters
    {
      ValidIssuer = _config["Tokens:Issuer"],
      ValidAudience = _config["Tokens:Audience"],
      ValidateIssuerSigningKey = true,
      IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])),
      ValidateLifetime = true
    }
  });
  app.UseMvc();
  databaseDataSeeder.Seed().Wait();
}

THE PROBLEM

The User returned by var user = _userManager.GetUserAsync(HttpContext.User); has an Id (of type int) that does not match the Id of the user in the dbo.AspNetUsers table. Plus the Id column in the table dbo.AspNetUsers is of type Guid.

I'm not sure how this can be! Here's a screenshot:

user in code

And here's a query against dbo.AspNetUsers in SQL Management Studio:

user in database

Why is this happening?

Upvotes: 0

Views: 221

Answers (2)

Igor
Igor

Reputation: 62268

You are not awaiting the result of the Task so you are not actually debugging / looking at the User but the Task object. Add the await keyword.

var user = await _userManager.GetUserAsync(HttpContext.User);

Upvotes: 5

DavidG
DavidG

Reputation: 119116

The problem is that you are looking at the result of an async method, in other words a Task<>, which has an Id property that is not related in any way to your user. You need to await the method call:

var user = await _userManager.GetUserAsync(HttpContext.User);

Upvotes: 5

Related Questions