A-Sharabiani
A-Sharabiani

Reputation: 19329

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...
}

Upvotes: 3

Views: 1788

Answers (3)

Xavier Egea
Xavier Egea

Reputation: 4763

When the user is logged into your app, the server, using ASP.NET Identity, validates your user using DB and creates a valid token that returns to the UI. This token will be valid to its expiration and has inside all information needed to authenticate and authorize the user, including the user's Id. Next calls from client side to server side must be done using this token in the http request header, but server will not call the DB again, because ASP.NET identity knows how to decrypt the token and get all the information of your user.

The use of cookies is only a way to store the token in the client side. As I commented above, you have to send the token on the next requests after the login, so you can store this token in cookies or in Session Storage in your browser.

Upvotes: 3

Hezye
Hezye

Reputation: 1551

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.

Upvotes: 5

thitemple
thitemple

Reputation: 6059

First, make sure you're not allowing for non-authenticated users.

After that, you want to parse Bearer tokens you have to configure it.

You're going to the need this package Microsoft.Owin.Security.OAuth

And at startup if have to configure ASP.NET Identity to use Bearer Authentication with:

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions {
    // your options;
});

Probably on your StartupAuth.cs file

Upvotes: 1

Related Questions