gpt4 book ai didi

asp.net-core-webapi - 为什么我没有在经过 Windows 身份验证的 Web Core API 中获取我的用户名?

转载 作者:行者123 更新时间:2023-12-04 16:05:27 25 4
gpt4 key购买 nike

我的 Web Core API 中的这段代码确认我是经过身份验证的用户,但我没有获得我的用户名,而是获得了应用程序池的名称。
我该如何解决?

var testa = User.Identity.GetType();
NLogger.Info($"testa = {testa}");
var testd = User.Identity.IsAuthenticated;
NLogger.Info($"testd = {testd}");
var loggedInUser = User.Identity.Name;
NLogger.Info($"loggedInUser = {loggedInUser}");

在我的日志文件中,我得到了;
testa = System.Security.Principal.WindowsIdentity
testd = True
loggedInUser = IIS APPPOOL\SIR.WEBUI

我为 Controller 使用了 [Authorize] 标签,并且禁用了匿名身份验证。

好吧,我从 Postman 调用该方法,它工作正常,LoggedInUser 是正确的。但是当我从我的代码中调用时,我得到了上面显示的不正确的 loginUser。
我用来从我的客户端应用程序调用 web api 的代码是;
public static async Task<IEnumerable<ContractDto>> GetAllForUser()
{
using (var client = new HttpClient(new HttpClientHandler { UseDefaultCredentials = true }))
{
client.BaseAddress = new Uri(AppSettings.ServerPathApi);
var path = GetPath("getallforuser");
var response = await client.GetAsync(path);
response.EnsureSuccessStatusCode();
var stringResult = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<IEnumerable<ContractDto>>(stringResult);
}
}

在 IIS 中,我已将应用程序池类型设置为所有各种选项;
applicationpoolidentity、networkservice、localservice、localsystem 并且每次都测试了应用程序。我到底错过了什么?

最佳答案

尝试这个

if (System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
string username = System.Web.HttpContext.Current.User.Identity.Name;
}

或者你可以试试
var user = (System.Security.Principal.WindowsIdentity)HttpContext.Current.User.Identity;
var userName = user.Impersonate();

关于asp.net-core-webapi - 为什么我没有在经过 Windows 身份验证的 Web Core API 中获取我的用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45594896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com