Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current UserId in Identity 3.0? User.GetUserId returns null

I need to get ID of user that made some request. In previous versions of Identity I could do it like this:

User.Identity.GetUserId();

But it seems it isn't available anymore.

There is also something like:

User.GetUserId();

But it always returns null, even if User.Identity.IsAuthenticated in true and User.Identity.Name is set correctly.

What should I use to do it?

EDIT: My authenticaton logic is based on [default Visual Studio 2015 template], I hadn't changed much so far in identity, so if you want to check how is it done, you can simply see it on github link I pasted.

like image 437
Piotrek Avatar asked Feb 23 '16 12:02

Piotrek


People also ask

How can we get logged in user details in asp net core?

You can create a method to get the current user : private Task<ApplicationUser> GetCurrentUserAsync() => _userManager. GetUserAsync(HttpContext. User);

What is user identity in C#?

Identity is Users Authentication and Authorization. In this article we will see how users are able to log in with their social identities so that they can have a rich experience on their website. Description. Identity is Users Authentication and Authorization.


2 Answers

@Joe Audette

it turns out it has been move to other place.

User.GetUserId => UserManager.GetUserId(User)
User.GetUserName => UserManager.GetUserName(User)
User.IsSignedIn => SignInManager.IsSignedIn(User)

detail on github

like image 176
maxisam Avatar answered Oct 12 '22 11:10

maxisam


I think there was a built in extension method for that in previous versions but they removed it. you can implement your own to replace it:

using System;
using System.Security.Claims;
using Microsoft.AspNet.Identity;

namespace cloudscribe.Core.Identity
{
    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal)
        {
            if (principal == null)
            {
                throw new ArgumentNullException(nameof(principal));
            }
            var claim = principal.FindFirst(ClaimTypes.NameIdentifier);
            return claim != null ? claim.Value : null;
        }
    }
}

ClaimType.NameIdentifier should map to userid

like image 42
Joe Audette Avatar answered Oct 12 '22 11:10

Joe Audette