Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Identity.GetUserId() finds the user Id?

Question

How does User.Identity.GetUserId() finds the current user's Id?

Does it find the user Id from the Cookies, or does it query the database? Or any other methods?

Problem

For some reason, User.Identity.GetUserId() returns null when I add a valid Bearer Token to my Http request header and send the request to my controller's endpoint:

// MVC Controller Action Method

[Authorize]
public HttpResponseMessage(UserInfoViewModel model)
{
    // Request passes the Authorization filter since a valid oauth token 
    // is attached to the request header.

    string userId = User.Identity.GetUserId();

    // However, userId is null!

    // Other stuff...
}
like image 711
A-Sharabiani Avatar asked Dec 17 '25 14:12

A-Sharabiani


1 Answers

How does User.Identity.GetUserId() finds the current user's Id?

ClaimTypes.NameIdentifier is the claim used by the function User.Identity.GetUserId()

You would need to add the claim in your authorization code,

identity.AddClaim(ClaimTypes.NameIdentifier, user.Id);

identity is of type ClaimIdentity.

like image 88
Hezye Avatar answered Dec 19 '25 05:12

Hezye



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!