Retrieving the current user ID

Before closing the QuizControllerfile, we should take the chance to remove that phony item.UserId value override we defined back in Chapter 5, Client-Server Interactions, when we had no authentication mechanism in place. The offending lines are still lying within the Put() method implementation:

[...]

// Set a temporary author using the Admin user's userId
// as user login isn't supported yet: we'll change this later on.
quiz.UserId = DbContext.Users.Where(u => u.UserName == "Admin")
.FirstOrDefault().Id;

[...]

Now that we're working with real authenticated accounts, we can easily retrieve the current userID; if we remember correctly, we did actually put it in the JWT token claims, as we can see by taking another quick look at the GetToken() method of the TokenController class:

[...]

var claims = new[] {
new Claim(JwtRegisteredClaimNames.Sub, user.Id),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),

[...]

This means that we can retrieve it in the following way (updated code is highlighted):

[...]

// retrieve the current user's Id
quiz.UserId = User.FindFirst(ClaimTypes.NameIdentifier).Value;

[...]

Let's perform this change and move on.

This minor update should be enough for now. However, it won't work when dealing with external providers, as they will put their own data in these claims. Retrieving our local UserId in such scenarios will require some additional work, such as querying a dedicated lookup table; we'll see more about this later on.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.103.96