programing

ASP에서 현재 로그인한 사용자 ID를 가져오는 방법.NET 코어?

elecom 2023. 5. 8. 21:54
반응형

ASP에서 현재 로그인한 사용자 ID를 가져오는 방법.NET 코어?

를 사용해서 MVC5를 사용해서 이 있습니다.User.Identity.GetUserId()하지만 여기선 효과가 없는 것 같아요User.Identity을 가지고 있지 않습니다.GetUserId()방법.

는 사용중을 하고 있습니다.Microsoft.AspNet.Identity.

ASP에서 업데이트합니다.NET Core 버전 >= 2.0

컨트롤러에서:

public class YourControllerNameController : Controller
{
    private readonly UserManager<ApplicationUser> _userManager;
    
    public YourControllerNameController(UserManager<ApplicationUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> YourMethodName()
    {
        var userId =  User.FindFirstValue(ClaimTypes.NameIdentifier) // will give the user's userId
        var userName =  User.FindFirstValue(ClaimTypes.Name) // will give the user's userName
        
        // For ASP.NET Core <= 3.1
        ApplicationUser applicationUser = await _userManager.GetUserAsync(User);
        string userEmail = applicationUser?.Email; // will give the user's Email

       // For ASP.NET Core >= 5.0
       var userEmail =  User.FindFirstValue(ClaimTypes.Email) // will give the user's Email
    }
}

일부 다른 클래스에서는

public class OtherClass
{
    private readonly IHttpContextAccessor _httpContextAccessor;
    public OtherClass(IHttpContextAccessor httpContextAccessor)
    {
       _httpContextAccessor = httpContextAccessor;
    }

   public void YourMethodName()
   {
      var userId = _httpContextAccessor.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);
   }
}

은 그럼당신합니다야를 등록해야 .IHttpContextAccessor에 시대에Startup클래스는 다음과 같습니다.

public void ConfigureServices(IServiceCollection services)
{
    services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    // Or you can also register as follows

    services.AddHttpContextAccessor();
}

보다 읽기 쉬운 쓰기 확장 방법은 다음과 같습니다.

public static class ClaimsPrincipalExtensions
{
    public static T GetLoggedInUserId<T>(this ClaimsPrincipal principal)
    {
        if (principal == null)
            throw new ArgumentNullException(nameof(principal));

        var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);

        if (typeof(T) == typeof(string))
        {
            return (T)Convert.ChangeType(loggedInUserId, typeof(T));
        }
        else if (typeof(T) == typeof(int) || typeof(T) == typeof(long))
        {
            return loggedInUserId != null ? (T)Convert.ChangeType(loggedInUserId, typeof(T)) : (T)Convert.ChangeType(0, typeof(T));
        }
        else
        {
            throw new Exception("Invalid type provided");
        }
    }

    public static string GetLoggedInUserName(this ClaimsPrincipal principal)
    {
        if (principal == null)
            throw new ArgumentNullException(nameof(principal));

        return principal.FindFirstValue(ClaimTypes.Name);
    }

    public static string GetLoggedInUserEmail(this ClaimsPrincipal principal)
    {
        if (principal == null)
            throw new ArgumentNullException(nameof(principal));

        return principal.FindFirstValue(ClaimTypes.Email);
    }
}

그런 다음 다음과 같이 사용합니다.

public class YourControllerNameController : Controller
{
    public IActionResult YourMethodName()
    {
        var userId = User.GetLoggedInUserId<string>(); // Specify the type of your UserId;
        var userName = User.GetLoggedInUserName();
        var userEmail = User.GetLoggedInUserEmail();
    }
}

public class OtherClass
{
     private readonly IHttpContextAccessor _httpContextAccessor;
     public OtherClass(IHttpContextAccessor httpContextAccessor)
     {
         _httpContextAccessor = httpContextAccessor;
     }

     public void YourMethodName()
     {
         var userId = _httpContextAccessor.HttpContext.User.GetLoggedInUserId<string>(); // Specify the type of your UserId;
     }
}

ASP까지.NET Core 1.0 RC1 :

사용자입니다.시스템에서 사용자 ID()를 가져옵니다.보안.네임스페이스를 할당합니다.

ASP 이후.NET Core 1.0 RC2 :

이제 사용자 관리자를 사용해야 합니다.현재 사용자를 가져오는 메서드를 만들 수 있습니다.

private Task<ApplicationUser> GetCurrentUserAsync() => _userManager.GetUserAsync(HttpContext.User);

개체를 사용하여 사용자 정보를 가져옵니다.

var user = await GetCurrentUserAsync();

var userId = user?.Id;
string mail = user?.Email;

참고:한도 할 수 있어요.string mail = (await _userManager.GetUserAsync(HttpContext.User))?.Email단일 책임 원칙을 존중하지 않습니다.언젠가 Identity가 아닌 다른 솔루션을 사용하는 등 사용자 관리 시스템을 변경하기로 결정하면 전체 코드를 검토해야 하므로 사용자를 얻는 방식을 격리하는 것이 좋습니다.

컨트롤러에서 얻을 수 있습니다.

using System.Security.Claims;
var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

또는 이전과 같이 확장 방법을 작성합니다.코어 v1.0

using System;
using System.Security.Claims;

namespace Shared.Web.MvcExtensions
{
    public static class ClaimsPrincipalExtensions
    {
        public static string GetUserId(this ClaimsPrincipal principal)
        {
            if (principal == null)
                throw new ArgumentNullException(nameof(principal));

            return principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
        }
    }
}

사용자 클레임 주체가 사용 가능한 모든 곳에서 사용할 수 있습니다.

using Microsoft.AspNetCore.Mvc;
using Shared.Web.MvcExtensions;

namespace Web.Site.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return Content(this.User.GetUserId());
        }
    }
}

시스템 사용을 포함했습니다.보안.클레임과 나는 GetUserId() 확장 메서드에 액세스할 수 있습니다.

NB: 저는 Microsoft를 사용했습니다.AsNet.Identity가 이미 있지만 확장 메서드를 가져올 수 없습니다.그래서 저는 두 가지가 서로 연결되어 사용되어야 한다고 생각합니다.

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

편집: 이 답변은 이제 구식입니다.CORE 1.0에서 이를 달성하는 날짜별 방법은 Soren 또는 Adrien의 답변을 참조하십시오.

. 2에만 합니다.NET Core 2.0의 경우만 로그인한 사용자의 사용자 ID를 가져오려면 다음이 필요합니다.Controller 명령어:

var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

또는

var userId = HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier);

예.

contact.OwnerID = this.User.FindFirstValue(ClaimTypes.NameIdentifier);

이 게시물의 어딘가에 명시된 바와 같이 GetUserId() 메서드가 UserManager로 이동되었습니다.

private readonly UserManager<ApplicationUser> _userManager;

public YourController(UserManager<ApplicationUser> userManager)
{
    _userManager = userManager;
}

public IActionResult MyAction()
{
    var userId = _userManager.GetUserId(HttpContext.User);

    var model = GetSomeModelByUserId(userId);

    return View(model);
}

빈 프로젝트를 시작한 경우 startup.cs 의 서비스에 UserManager를 추가해야 할 수 있습니다.그렇지 않으면 이미 그럴 것입니다.

당신은 마이크로소프트를 수입해야 합니다.AsNetCore.아이덴티티 & 시스템.보안.주장하다

// to get current user ID
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

// to get current user info
var user = await _userManager.FindByIdAsync(userId);

ASP용.NET Core 2.0, Entity Framework Core 2.0, AsNet Core.아이덴티티 2.0 api(https://github.com/kkagill/ContosoUniversity-Backend) :

Id로 변경되었습니다.User.Identity.Name

    [Authorize, HttpGet("Profile")]
    public async Task<IActionResult> GetProfile()
    {
        var user = await _userManager.FindByIdAsync(User.Identity.Name);

        return Json(new
        {
            IsAuthenticated = User.Identity.IsAuthenticated,
            Id = User.Identity.Name,
            Name = $"{user.FirstName} {user.LastName}",
            Type = User.Identity.AuthenticationType,
        });
    }

응답:

여기에 이미지 설명 입력

.net core 3.1(및 기타 최신 버전)에서는 다음을 사용할 수 있습니다.

private readonly UserManager<IdentityUser> _userManager;

public ExampleController(UserManager<IdentityUser> userManager)
{
    _userManager = userManager;
}

그러면:

string userId = _userManager.GetUserId(User);

또는 비동기:

var user = await _userManager.GetUserAsync(User);
var userId = user.Id;

이 시점에서, 저는 당신이 왜 하나를 다른 하나보다 더 사용하는지 알아내려고 노력하고 있습니다.비동기의 일반적인 이점은 알고 있지만 두 가지 모두 자주 사용됩니다.아시는 분 있으면 댓글 달아주세요.

위해서ASP.NET 5.0다음과 같은 확장 방법이 있습니다.

using System;
using System.ComponentModel;
using System.Security.Claims;

namespace YOUR_PROJECT.Presentation.WebUI.Extensions
{
    public static class ClaimsPrincipalExtensions
    {
        public static TId GetId<TId>(this ClaimsPrincipal principal)
        {
            if (principal == null || principal.Identity == null || 
                !principal.Identity.IsAuthenticated)
            {
                throw new ArgumentNullException(nameof(principal));
            }

            var loggedInUserId = principal.FindFirstValue(ClaimTypes.NameIdentifier);

            if (typeof(TId) == typeof(string) || 
                typeof(TId) == typeof(int) || 
                typeof(TId) == typeof(long) || 
                typeof(TId) == typeof(Guid))
            {
                var converter = TypeDescriptor.GetConverter(typeof(TId));

                return (TId)converter.ConvertFromInvariantString(loggedInUserId);
            }

            throw new InvalidOperationException("The user id type is invalid.");
        }

        public static Guid GetId(this ClaimsPrincipal principal)
        {
            return principal.GetId<Guid>();
        }
    }
}

따라서 다음과 같이 사용할 수 있습니다.

using Microsoft.AspNetCore.Mvc;
using YOUR_PROJECT.Presentation.WebUI.Extensions;

namespace YOUR_PROJECT.Presentation.WebUI.Controllers
{
    public class YourController :Controller
    {
        public IActionResult YourMethod()
        {
            // If it's Guid
            var userId = User.GetId();

            // Or
            // var userId = User.GetId<int>();

            return View();
        }
    }
}

에 시대에APiController

User.FindFirst(ClaimTypes.NameIdentifier).Value

이와 같은 것은 당신이 클레임을 받을 것입니다.

비록 Adrien의 대답이 정확하지만, 당신은 이 모든 것을 한 줄로 할 수 있습니다.추가 기능이나 혼란이 필요하지 않습니다.

ASP에서 확인했습니다.NET Core 1.0

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

그러면 다음과 같은 변수의 다른 속성을 얻을 수 있습니다.user.Email이것이 누군가에게 도움이 되길 바랍니다.

레이저 뷰에서 현재 사용자 ID를 얻기 위해 다음과 같은 뷰에 UserManager를 삽입할 수 있습니다.

@inject Microsoft.AspNetCore.Identity.UserManager<ApplicationUser> _userManager
@{ string userId = _userManager.GetUserId(User); }

도움이 되길 바랍니다.

사용자. 신원.GetUserId();

이와 관련하여 asp.net ID 코어 2.0에는 존재하지 않습니다. 저는 다른 방식으로 관리했습니다. 저는 사용자 정보를 얻기 때문에 전체 응용 프로그램을 사용하기 위한 공통 클래스를 만들었습니다.

공통 클래스 PC공통 인터페이스 IP공통 추가 참조using System.Security.Claims

using Microsoft.AspNetCore.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Common.Web.Helper
{
    public class PCommon: IPCommon
    {
        private readonly IHttpContextAccessor _context;
        public PayraCommon(IHttpContextAccessor context)
        {
            _context = context;
        }
        public int GetUserId()
        {
            return Convert.ToInt16(_context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));
        }
        public string GetUserName()
        {
            return _context.HttpContext.User.Identity.Name;
        }

    }
    public interface IPCommon
    {
        int GetUserId();
        string GetUserName();        
    }    
}

여기서 공통 클래스의 구현.

using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.Extensions.Logging;
using Pay.DataManager.Concreate;
using Pay.DataManager.Helper;
using Pay.DataManager.Models;
using Pay.Web.Helper;
using Pay.Web.Models.GeneralViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Pay.Controllers
{

    [Authorize]
    public class BankController : Controller
    {

        private readonly IUnitOfWork _unitOfWork;
        private readonly ILogger _logger;
        private readonly IPCommon _iPCommon;


        public BankController(IUnitOfWork unitOfWork, IPCommon IPCommon, ILogger logger = null)
        {
            _unitOfWork = unitOfWork;
            _iPCommon = IPCommon;
            if (logger != null) { _logger = logger; }
        }


        public ActionResult Create()
        {
            BankViewModel _bank = new BankViewModel();
            CountryLoad(_bank);
            return View();
        }

        [HttpPost, ActionName("Create")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Insert(BankViewModel bankVM)
        {

            if (!ModelState.IsValid)
            {
                CountryLoad(bankVM);
                //TempData["show-message"] = Notification.Show(CommonMessage.RequiredFieldError("bank"), "Warning", type: ToastType.Warning);
                return View(bankVM);
            }


            try
            {
                bankVM.EntryBy = _iPCommon.GetUserId();
                var userName = _iPCommon.GetUserName()();
                //_unitOfWork.BankRepo.Add(ModelAdapter.ModelMap(new Bank(), bankVM));
                //_unitOfWork.Save();
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveMessage(), "Success", type: ToastType.Success);
            }
            catch (Exception ex)
            {
               // TempData["show-message"] = Notification.Show(CommonMessage.SaveErrorMessage("bank"), "Error", type: ToastType.Error);
            }
            return RedirectToAction(nameof(Index));
        }



    }
}

삽입 작업에서 userId 및 이름 가져오기

_iPCommon.GetUserId();

고마워, 막수드

TLDR:

컨트롤러에서 다음을 추가합니다.

using System.Security.Claims; 

그런 다음 다음을 사용할 수 있습니다.

var userId = User.FindFirstValue(ClaimTypes.NameIdentifier);

TLDR 종료;

닷넷 6에서 사용자를 얻는 방법을 테스트하는 간단한 방법입니다.기본 Blazor Web Assembly Core Hosted:

  • WeatherForecast 클래스에 userId라는 문자열을 추가했습니다.

      public class WeatherForecast
      {
          public DateTime Date { get; set; }
    
          public int TemperatureC { get; set; }
    
          public string? Summary { get; set; }
    
          public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
          public string userId { get; set; } = "nope";
      }
    

    그러면 기상 예보 컨트롤러에서.

  • 추가합니다using System.Security.Claims;

  • GET 메서드에서 WeatherForecast.userId를 User로 설정합니다.첫 번째 값 찾기(클레임 유형).이름 식별자):

      public IEnumerable<WeatherForecast> Get()
      {
    
          return Enumerable.Range(1, 5).Select(index => new WeatherForecast
          {
              Date = DateTime.Now.AddDays(index),
              TemperatureC = Random.Shared.Next(-20, 55),
              Summary = Summaries[Random.Shared.Next(Summaries.Length)],
              userId = User.FindFirstValue(ClaimTypes.NameIdentifier)
          })
          .ToArray();
      }
    

마지막으로 FetchData.razor에서 테이블을 다음과 같이 수정합니다.

    <table class="table">
    <thead>
        <tr>
            <th>Date</th>
            <th>Temp. (C)</th>
            <th>Temp. (F)</th>
            <th>Summary</th>
            <th>User Id</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var forecast in forecasts)
        {
            <tr>
                <td>@forecast.Date.ToShortDateString()</td>
                <td>@forecast.TemperatureC</td>
                <td>@forecast.TemperatureF</td>
                <td>@forecast.Summary</td>
                <td>@forecast.userId</td>
            </tr>
        }
    </tbody>
</table>

그리고 마침내 저는 다음을 얻습니다.

net core 6에서는 때때로 답을 찾는 것이 꽤 어렵기 때문에 도움이 되기를 바랍니다.

JWT 토큰을 사용하는 경우 이 코드는 다음과 같이 작동합니다.

User.FindFirstValue("sub");

사용할 수 있음

string userid = User.FindFirst("id").Value;

어떤 이유로 NameIdentifier가 이제 사용자 이름(.net core 2.2)을 검색합니다.

Windows 인증을 사용하도록 설정했는지 확인합니다.익명 인증을 사용하도록 설정한 경우 null 문자열을 받을 수 있습니다.

https://learn.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.1&tabs=visual-studio

이미 많은 답변이 게시되어 있다는 것을 알지만, 저에게 그랬던 것처럼 누군가에게 도움이 될 수도 있습니다.

두 솔루션을 하나로 혼합하여 로그인한 사용자와 해당 데이터를 가져올 수 있습니다.저는 닷넷 5를 사용하고 있었습니다.코드에 따라 로그인한 사용자를 얻는 데 도움이 됩니다.

var user = await _userManager.FindByNameAsync(HttpContext.User.Identity.Name);

_userManager에 대해 다음 패키지를 사용했습니다.

using Microsoft.AspNetCore.Identity;

그리고 HttpContext의 경우 ControllerBase에서 컨트롤러를 상속하고 ControllerBase Class의 경우 다음 패키지를 사용했습니다.

using Microsoft.AspNetCore.Mvc;

수입품

 using System.Security.Claims;

그런 다음 사용자 ID 또는 전자 메일을 검색하기 위해 다음 코드를 사용합니다.

 var userId = this.User.FindFirstValue(ClaimTypes.NameIdentifier);
 var email= this.User.Identity.Name;

다른 사용자의 프로필에서 작업하는 관리자로서 작업 중인 프로필의 ID를 가져와야 하는 경우 ViewBag를 사용하여 ID(예: ViewBag)를 캡처할 수 있습니다.UserId = userId이며, userId는 작업 중인 메서드의 매개 변수 문자열입니다.

    [HttpGet]

    public async Task<IActionResult> ManageUserRoles(string userId)
    {

          ViewBag.UserId = userId;


        var user = await userManager.FindByIdAsync(userId);

        if (user == null)
        {
            ViewBag.ErrorMessage = $"User with Id = {userId} cannot be found";
            return View("NotFound");
        }

        var model = new List<UserRolesViewModel>();

        foreach (var role in roleManager.Roles)
        {
            var userRolesViewModel = new UserRolesViewModel
            {
                RoleId = role.Id,
                RoleName = role.Name
            };

            if (await userManager.IsInRoleAsync(user, role.Name))
            {
                userRolesViewModel.IsSelected = true;
            }
            else
            {
                userRolesViewModel.IsSelected = false;
            }

            model.Add(userRolesViewModel);
        }
        return View(model);
    }

이것을 ASP에서 원한다면요.NET MVC 컨트롤러, 사용

using Microsoft.AspNet.Identity;

User.Identity.GetUserId();

추가해야 합니다.using진술 이유는GetUserId()그것 없이는 그곳에 없을 것입니다.

언급URL : https://stackoverflow.com/questions/30701006/how-to-get-the-current-logged-in-user-id-in-asp-net-core

반응형